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
|
|---|---|---|---|---|---|
57314025ed559b75a604dccae38a4c420fe2e50f
| 4,463
|
package com.catenax.tdm.sampledata;
import java.util.ArrayList;
import java.util.List;
import com.catenax.tdm.model.v1.BusinessPartner;
import com.catenax.tdm.model.v1.MemberCompany;
import com.catenax.tdm.model.v1.MemberCompanyRole;
public class InitialSampleData {
public static class BPMC {
private BusinessPartner businessPartner = null;
private MemberCompany memberCompany = null;
public BPMC(BusinessPartner bp, MemberCompany mc) {
this.businessPartner = bp;
this.memberCompany = mc;
}
public BusinessPartner getBusinessPartner() {
return businessPartner;
}
public MemberCompany getMemberCompany() {
return memberCompany;
}
}
public static List<BPMC> createInitialBusinessPartners() {
List<BPMC> result = new ArrayList<BPMC>();
List<MemberCompanyRole> participant = new ArrayList<MemberCompanyRole>();
List<MemberCompanyRole> infra = new ArrayList<MemberCompanyRole>();
List<MemberCompanyRole> app = new ArrayList<MemberCompanyRole>();
List<MemberCompanyRole> partapp = new ArrayList<MemberCompanyRole>();
participant.add(MemberCompanyRole.ACTIVE_PARTICIPANT);
infra.add(MemberCompanyRole.OPERATIONS_INFRASTRUCTURE_PROVIDER);
app.add(MemberCompanyRole.APP_PROVIDER);
partapp.add(MemberCompanyRole.ACTIVE_PARTICIPANT);
partapp.add(MemberCompanyRole.APP_PROVIDER);
BPMC bmwGroup = createBPMC(BusinessPartnerSampleData.BPN_BMWGROUP, "Bayerische Motoren Werke Aktiengesellschaft", null, "OEM", participant);
BPMC bmwMuc = createBPMC(BusinessPartnerSampleData.BPN_BMWMUC, "BMW Plant Munich", bmwGroup.getBusinessPartner().getBpn(), "OEM Plant", participant);
BPMC bmwDgf = createBPMC(BusinessPartnerSampleData.BPN_BMWDGF, "BMW Plant Dingolfing", bmwGroup.getBusinessPartner().getBpn(), "OEM Plant", participant);
BPMC bmwLpz = createBPMC(BusinessPartnerSampleData.BPN_BMWLPZ, "BMW Plant Leipzig", bmwGroup.getBusinessPartner().getBpn(), "OEM Plant", participant);
BPMC daimler = createBPMC(BusinessPartnerSampleData.BPN_DAI, "Daimler AG", null, "OEM", participant);
BPMC zfGroup = createBPMC(BusinessPartnerSampleData.BPN_ZF, "ZF Friedrichshafen AG", null, "Supplier", participant);
BPMC bosch = createBPMC(BusinessPartnerSampleData.BPN_BOSCH, "Robert Bosch GmbH", null, "Supplier", participant);
BPMC basf = createBPMC(BusinessPartnerSampleData.BPN_BASF, "BASF", null, "Supplier", participant);
BPMC henkel = createBPMC(BusinessPartnerSampleData.BPN_HENKEL, "Henkel", null, "Supplier", participant);
BPMC kaputt = createBPMC(BusinessPartnerSampleData.BPN_KAPUTT, "Kaputt GmbH", null, "Supplier", partapp);
BPMC sap = createBPMC(BusinessPartnerSampleData.BPN_SAP, "SAP AG", null, "Technology", app);
BPMC microsoft = createBPMC(BusinessPartnerSampleData.BPN_MICROSOFT, "Microsoft", null, "Technology", infra);
BPMC tsystems = createBPMC(BusinessPartnerSampleData.BPN_TSYSTEMS, "T-Systems", null, "Technology", infra);
result.add(bmwGroup);
result.add(bmwMuc);
result.add(bmwDgf);
result.add(bmwLpz);
result.add(daimler);
result.add(zfGroup);
result.add(bosch);
result.add(basf);
result.add(henkel);
result.add(kaputt);
result.add(sap);
result.add(microsoft);
result.add(tsystems);
return result;
}
public static BPMC createBPMC(String name, char classification, String parent, String accountGroup, List<MemberCompanyRole> roles) {
BusinessPartner bp = BusinessPartnerSampleData.createBusinessPartner(name, classification, parent, accountGroup);
MemberCompany mc = createMemberCompanyFromBusinessPartner(bp, roles);
return new BPMC(bp, mc);
}
public static BPMC createBPMC(String BPN, String name, String parent, String accountGroup, List<MemberCompanyRole> roles) {
BusinessPartner bp = BusinessPartnerSampleData.createBusinessPartner(BPN, name, parent, accountGroup);
MemberCompany mc = createMemberCompanyFromBusinessPartner(bp, roles);
return new BPMC(bp, mc);
}
public static MemberCompany createMemberCompanyFromBusinessPartner(BusinessPartner businessPartner, List<MemberCompanyRole> roles) {
MemberCompany member = null;
if(businessPartner != null && businessPartner.getParent() == null) {
member = new MemberCompany();
member.setBPN(businessPartner.getBpn());
member.setName(businessPartner.getName1());
member.setParent(businessPartner.getParent());
member.setRoles(roles);
}
return member;
}
}
| 40.207207
| 157
| 0.762268
|
9e4f517d8d0587de8b4e7ffbbae3c9bd583d0751
| 2,078
|
package com.tumblr.backboard.example;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import com.facebook.rebound.Spring;
import com.facebook.rebound.SpringSystem;
import com.tumblr.backboard.performer.Performer;
/**
* Scale a view with a finger.
* <p/>
* Created by ericleong on 5/7/14.
*/
public class ScaleFragment extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_scale, container, false);
final View rect = rootView.findViewById(R.id.rect);
final SpringSystem springSystem = SpringSystem.create();
final Spring spring = springSystem.createSpring();
spring.addListener(new Performer(rect, View.SCALE_X));
spring.addListener(new Performer(rect, View.SCALE_Y));
rootView.setOnTouchListener(new View.OnTouchListener() {
@Override
@SuppressLint("ClickableViewAccessibility")
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
spring.setVelocity(0);
case MotionEvent.ACTION_MOVE:
// can't use Imitation here because there is no nice mapping from
// an event property to a Spring
float scaleX, scaleY;
float delta = event.getX() - (rect.getX() + rect.getMeasuredWidth() / 2);
scaleX = Math.abs(delta) / (rect.getMeasuredWidth() / 2);
delta = event.getY() - (rect.getY() + rect.getMeasuredHeight() / 2);
scaleY = Math.abs(delta) / (rect.getMeasuredHeight() / 2);
float scale = Math.max(scaleX, scaleY);
spring.setEndValue(scale);
break;
case MotionEvent.ACTION_UP:
spring.setEndValue(1f);
break;
}
return true;
}
});
return rootView;
}
}
| 26.641026
| 84
| 0.714629
|
5013938d8545c235fcda2e0f582a40bd6a489968
| 5,591
|
package com.example.betterweather;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
public class MainWeatherAdapter extends RecyclerView.Adapter<MainWeatherAdapter.MainWeatherHolder> {
private ArrayList<String> cities = new ArrayList<>(Arrays.asList("Barnaul", "Moscow"));
private String dayTemplate;
private boolean additionalInfoVisibility;
public MainWeatherAdapter(String dayTemplate) {
this.dayTemplate = dayTemplate;
additionalInfoVisibility = true;
}
public ArrayList<String> getCities() {
return cities;
}
public void setCities(ArrayList<String> cities) {
this.cities = cities;
}
public boolean getLinearLayoutAdditionalInfoVisibility() {
return additionalInfoVisibility;
}
public void setLinearLayoutAdditionalInfoVisibility(boolean showAdditional) {
additionalInfoVisibility = showAdditional;
notifyDataSetChanged();
}
@NonNull
@Override
public MainWeatherHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
final LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
return new MainWeatherHolder(layoutInflater
.inflate(R.layout.weather_item, viewGroup, false));
}
@Override
public void onBindViewHolder(@NonNull MainWeatherHolder mainWeatherHolder, int i) {
String city = cities.get(i);
String dayText = String.format(dayTemplate, Helpers.getDayOfWeek(), Helpers.getPartOfDay(mainWeatherHolder.itemView.getContext()));
mainWeatherHolder.binds(city, dayText, Helpers.getFutureWeather(mainWeatherHolder.itemView.getContext()), additionalInfoVisibility);
}
@Override
public int getItemCount() {
return cities.size();
}
static class MainWeatherHolder extends RecyclerView.ViewHolder {
final Random random = new Random();
private TextView textViewLocationName;
private LinearLayout linearLayoutAdditionalInfo;
private TextView day;
private GridView gridView;
public MainWeatherHolder(@NonNull View itemView) {
super(itemView);
initElements(itemView);
initWeatherValue(itemView);
initHumidityValue(itemView);
initPressureValue(itemView);
initWindValue(itemView);
}
private void initElements(@NonNull View itemView) {
textViewLocationName = itemView.findViewById(R.id.location_name);
linearLayoutAdditionalInfo = itemView.findViewById(R.id.additional_info);
day = itemView.findViewById(R.id.text_part_of_day);
gridView = itemView.findViewById(R.id.grid_view_feature_weather);
}
private void initWeatherValue(@NonNull View itemView) {
TextView weather = itemView.findViewById(R.id.text_weather_now);
String weatherTemplate = itemView.getResources().getString(R.string.main_weather_now);
int weatherValue = random.nextInt(100) - 50;
String weatherText = String.format(weatherTemplate, String.valueOf(weatherValue));
weather.setText(weatherText);
}
private void initHumidityValue(@NonNull View itemView) {
TextView humidity = itemView.findViewById(R.id.text_humidity_now);
String humidityTemplate = itemView.getResources().getString(R.string.main_humidity);
int humidityValue = random.nextInt(100);
String humidityText = String.format(humidityTemplate, String.valueOf(humidityValue));
humidity.setText(humidityText);
}
private void initPressureValue(@NonNull View itemView) {
TextView pressure = itemView.findViewById(R.id.text_pressure_now);
String pressureTemplate = itemView.getResources().getString(R.string.main_pressure);
int pressureValue = random.nextInt(100) + 680;
String pressureText = String.format(pressureTemplate, String.valueOf(pressureValue));
pressure.setText(pressureText);
}
private void initWindValue(@NonNull View itemView) {
TextView wind = itemView.findViewById(R.id.text_wind_now);
String windTemplate = itemView.getResources().getString(R.string.main_wind);
int windValue = random.nextInt(20);
String[] winds = itemView.getResources().getStringArray(R.array.winds);
int idx = random.nextInt(winds.length);
String windText = String.format(windTemplate, String.valueOf(windValue), winds[idx]);
wind.setText(windText);
}
public void binds(String cityName, String dayText, FutureWeather[] futureWeathers, boolean visibility) {
textViewLocationName.setText(cityName);
day.setText(dayText);
FutureWeatherAdapter futureWeatherAdapter = new FutureWeatherAdapter(linearLayoutAdditionalInfo.getContext(), futureWeathers);
gridView.setAdapter(futureWeatherAdapter);
linearLayoutAdditionalInfo.setVisibility(visibility ? View.VISIBLE : View.GONE);
}
}
}
| 41.723881
| 141
| 0.682168
|
cd4ec57470ce16f7516d3e03367ad0a1f5b9ac81
| 2,051
|
/*
* Copyright 2015 Adaptris Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adaptris.core;
import com.adaptris.core.event.StandardAdapterStartUpEvent;
/**
* Concrete implementations of this <code>Event</code> contains details of the {@link Adapter} configuration.
* <p>
* The earliest point in the adapter lifecycle that an event can be emitted is after <code>init</code>, therefore this event is
* always emitted at the end of the initialisation phase.
* </p>
* <p>
* Concrete implementations of this class provide solution-specific behaviour, such as extracting valid receive destinations,
* sending the entire adapter config, etc.
* </p>
*
* @see StandardAdapterStartUpEvent
*/
public abstract class AdapterStartUpEvent extends AdapterLifecycleEvent {
private static final long serialVersionUID = 2014012301L;
public AdapterStartUpEvent() {
super(EventNameSpaceConstants.ADAPTER_START_UP);
}
/**
* <p>
* Sets the <code>Adapter</code> that generated this start up event.
* Solution-specific sub-classes should implement this method and extract
* information that they need (such as valid consume destinations) from the
* <code>Adapter</code> object (hence the ability to throw
* <code>Exception</code>s from a set).
* </p>
* @param adapter the <code>Adapter</code> that generated this start-up event
* @throws CoreException wrapping any underlying Exceptions that may occur
*/
public abstract void setAdapter(Adapter adapter) throws CoreException;
}
| 36.625
| 127
| 0.744027
|
08d728add6bbcd087207e402bc7f0f0b2a309e6c
| 1,575
|
package redis.manager.controller.operation.panel;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import redis.manager.controller.ConnectController;
import java.io.IOException;
/**
* 连接属性面板.
* User: huang
* Date: 17-6-29
*/
public class ConnectPanel {
private ConnectController connectController;
/**
* 显示连接属性面板.
* @return 是否点击确认
*/
public boolean showConnectPanel(String poolId) {
boolean ok = false;
// 创建 FXMLLoader 对象
FXMLLoader loader = new FXMLLoader();
// 加载文件
loader.setLocation(this.getClass().getResource("/views/ConnectLayout.fxml"));
AnchorPane pane = null;
try {
pane = loader.load();
} catch (IOException e) {
e.printStackTrace();
}
// 创建对话框
Stage dialogStage = new Stage();
dialogStage.setTitle("创建连接");
dialogStage.initModality(Modality.WINDOW_MODAL);
Scene scene = new Scene(pane);
dialogStage.setScene(scene);
connectController = loader.getController();
connectController.setDialogStage(dialogStage);
connectController.setPoolId(poolId);
// 显示对话框, 并等待, 直到用户关闭
dialogStage.showAndWait();
ok = connectController.isOkChecked();
return ok;
}
/**
* 设置是否为新建连接.
* @param flag true为新建连接, false为修改属性
*/
public void isNewLink(boolean flag) {
ConnectController.setFlag(flag);
}
}
| 23.863636
| 85
| 0.634286
|
0a9ba52bad8494dd4875f6e4d176430e37f9258a
| 3,606
|
package com.linuxtek.kona.app.util;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.linuxtek.kona.app.comm.entity.KEmailAddress;
import com.linuxtek.kona.app.core.entity.KUser;
import com.linuxtek.kona.util.KClassUtil;
import com.linuxtek.kona.util.KDateUtil;
import com.linuxtek.kona.util.KStringUtil;
public class KUtil {
private static Logger logger = LoggerFactory.getLogger(KUtil.class);
private static KUtil instance = null;
public static KUtil getInstance() {
if (instance == null) {
instance = new KUtil();
}
return instance;
}
public static String uuid() {
String uuid = UUID.randomUUID().toString();
uuid = uuid.replaceAll("-", "");
return uuid;
}
public static String year() {
Integer year = KDateUtil.getYear(new Date());
return year.toString();
}
public static String toString(Object obj) {
if (obj == null) {
return "[null]";
}
return KClassUtil.toString(obj);
}
public static String toHtml(String s) {
if (s == null) {
return "";
}
return KStringUtil.toHtml(s);
}
public static <Email extends KEmailAddress> String emailFirstName(Email email) {
if (email == null) return "";
if (email.getFirstName() != null) {
return email.getFirstName();
}
return "";
}
public static <User extends KUser> String formatFirstName(User user) {
if (user == null) return "";
if (user.getFirstName() != null) {
return user.getFirstName();
}
if (user.getUsername() != null) {
return user.getUsername();
}
if (user.getEmail() != null) {
return user.getEmail();
}
return "";
}
public String createLink(String baseUrl, String url) {
if (baseUrl == null) baseUrl = "";
if (url == null) url = "/";
if (baseUrl.endsWith("/")) {
baseUrl = KStringUtil.chop(baseUrl);
}
if (!url.startsWith("/")) {
url = "/" + url;
}
String link = baseUrl + url;
logger.debug("LINK: " + link);
return link;
}
public static String formatDate(Date date) {
String f = "MM/dd/yyyy";
return formatDate(date, f);
}
public static String formatDate(Date date, String format) {
return formatDate(date, format, null);
}
public static String formatDate(Date date, String format, String timeZone) {
if (date == null) return "";
Locale locale = Locale.getDefault();
if (timeZone == null) {
timeZone = "America/New_York";
}
TimeZone tz = TimeZone.getTimeZone(timeZone);
return KDateUtil.format(date, format, locale, tz);
}
public static String formatCurrency(BigDecimal bd) {
//Locale locale = new Locale("en_US");
return formatCurrency(bd, Locale.US);
}
public static String formatCurrency(BigDecimal bd, Locale locale) {
if (bd == null)
return (null);
double d = bd.doubleValue();
NumberFormat form = NumberFormat.getCurrencyInstance(locale);
return (form.format(d));
}
public static void sleep(Long ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { }
}
}
| 25.216783
| 84
| 0.584027
|
f4155ebebdc025348973097eb1d20b27de5b12c0
| 185
|
package cast_in;
public class TestReturnValue4 {
Integer foo() {
return 1 + 1;
}
void x() {
/*]*/
int a = /*[*/
foo().intValue();
}
}
| 12.333333
| 31
| 0.427027
|
bebb5c46b463f7405f42a54bcb79a2225de21fa7
| 3,606
|
package com.crc.service;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import com.crc.constants.Constants;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class TickerServiceImpl {
static OkHttpClient client = new OkHttpClient();
static LoadingCache<String, String> tickersCache = null;
static LoadingCache<String, String> tickerCache = null;
static {
tickersCache = CacheBuilder.newBuilder().maximumSize(5)
.expireAfterWrite(Constants.TICKER_TIMEOUT, TimeUnit.MINUTES).build(new CacheLoader<String, String>() {
@Override
public String load(String param) throws Exception {
return getTickers();
}
});
tickerCache = CacheBuilder.newBuilder().maximumSize(1500)
.expireAfterWrite(Constants.TICKER_TIMEOUT, TimeUnit.MINUTES).build(new CacheLoader<String, String>() {
@Override
public String load(String param) throws Exception {
return getTicker(param);
}
});
}
/**
* Load tickers from cache. If not present, call underlying service
*
* @return
*/
public String getTickersFromCache() {
String result = null;
try {
result = tickersCache.get(Constants.TICKERS);
} catch (ExecutionException ex) {
System.out.println("Exception within getTickersFromCache() " + ex.getClass().getName());
}
return result;
}
/**
* Get price ticker for a single currency
*
* @param id
* @return
*/
public String getTickerFromCache(String id) {
String result = null;
try {
result = tickerCache.get(id);
} catch (ExecutionException ex) {
System.out.println("Exception within getTickerFromCache() " + ex.getClass().getName());
}
return result;
}
/**
* Return all tickers
*
* @return
*/
private static String getTickers() {
System.out.println("Getting data from service : getTickers()");
String result = null;
Request request = new Request.Builder().url(Constants.COINMARKETCAP_ALL_TICKER_URL).build();
try (Response response = client.newCall(request).execute()) {
result = response.body().string();
} catch (Exception ex) {
System.out.println("Exception within getTickers() " + ex.getClass().getName());
}
return result;
}
/**
* Return ticker for specified coin
*
* @return
*/
private static String getTicker(String id) {
System.out.println("Getting data from service : getTicker() " + id);
String result = null;
Request request = new Request.Builder().url(Constants.COINMARKETCAP_TICKER_URL + id).build();
try (Response response = client.newCall(request).execute()) {
result = response.body().string();
} catch (Exception ex) {
System.out.println("Exception within getTicker() " + ex.getClass().getName());
}
return result;
}
/**
* Utility method to print options
* TODO: Need to store it in DB
* @param result
*/
private void printOptions(String result) {
JsonParser parser = new JsonParser();
JsonArray arr = parser.parse(result).getAsJsonArray();
for(int i=0; i<arr.size(); i++) {
JsonObject obj = arr.get(i).getAsJsonObject();
System.out.println("<option value =\"" + obj.get("id").getAsString().replaceAll(" ", "-").toLowerCase() + "~" + obj.get("symbol").getAsString() + "\">");
System.out.println(obj.get("name").getAsString());
System.out.println("</option>");
}
}
}
| 27.738462
| 156
| 0.695507
|
f6117c554d424ba19a74978162d0e84cadaca6cc
| 2,604
|
package net.canarymod.api.entity;
import net.canarymod.api.inventory.CanaryItem;
import net.canarymod.api.inventory.Item;
/**
* EntityItem wrapper implementation
*
* @author Jason (darkdiplomat)
*/
public class CanaryEntityItem extends CanaryEntity implements EntityItem {
/**
* Constructs a new wrapper for EntityItem
*
* @param entity
* the EntityItem to be wrapped
*/
public CanaryEntityItem(net.minecraft.entity.item.EntityItem entity) {
super(entity);
}
@Override
public boolean isItem() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public EntityType getEntityType() {
return EntityType.ENTITYITEM;
}
@Override
public String getFqName() {
return "Item";
}
/**
* {@inheritDoc}
*/
@Override
public void setAge(short age) {
getHandle().a = age;
}
/**
* {@inheritDoc}
*/
@Override
public short getAge() {
return (short) getHandle().a;
}
/**
* {@inheritDoc}
*/
@Override
public int getPickUpDelay() {
return getHandle().b;
}
/**
* {@inheritDoc}
*/
@Override
public void setPickUpDelay(int delay) {
getHandle().b = delay;
}
/**
* {@inheritDoc}
*/
@Override
public short getHealth() {
return (short) getHandle().e;
}
/**
* {@inheritDoc}
*/
@Override
public void setHealth(short health) {
getHandle().e = Math.min(health, 255);
}
/**
* {@inheritDoc}
*/
@Override
public CanaryItem getItem() {
return getHandle().f().getCanaryItem();
}
/**
* {@inheritDoc}
*/
@Override
public void setItem(Item item) {
if (item != null) {
getHandle().a(((CanaryItem) item).getHandle());
}
}
/**
* {@inheritDoc}
*/
@Override
public String getOwner() {
return getHandle().i();
}
/**
* {@inheritDoc}
*/
@Override
public void setOwner(String owner) {
getHandle().a(owner);
}
/**
* {@inheritDoc}
*/
@Override
public String getThrower() {
return getHandle().j();
}
/**
* {@inheritDoc}
*/
@Override
public void setThrower(String thrower) {
getHandle().b(thrower);
}
/**
* {@inheritDoc}
*/
@Override
public net.minecraft.entity.item.EntityItem getHandle() {
return (net.minecraft.entity.item.EntityItem) entity;
}
}
| 17.714286
| 74
| 0.530722
|
545a71cb931a7d5814cef00b45c56b23ed33a6e5
| 1,923
|
package co.com.ingenesys.utils;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.CalendarView;
import android.widget.DatePicker;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import co.com.ingenesys.fragment.ReporteDiarioFragment;
public class SelectDateFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
private static String fecha;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//Obtener fecha actual del sistema
final Calendar c= Calendar.getInstance();
int year=c.get(Calendar.YEAR);
int month=c.get(Calendar.MONTH);
int day=c.get(Calendar.DAY_OF_MONTH);
//retorna una instancia del dialogo selector de fecha
return new DatePickerDialog(getContext(), this,year,month,day);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyy-MM-dd", Locale.getDefault());
Date date = null;
Date fecha_final = null;
final int mesActual = month + 1;
String diaFormat = (dayOfMonth < 10) ? 0 + String.valueOf(dayOfMonth) : String.valueOf(dayOfMonth);
String mesFormat = (mesActual< 10) ? 0 + String.valueOf(mesActual) : String.valueOf(mesActual);
try{
date = dateFormat.parse(year + "-" + mesFormat + "-" + diaFormat);
fecha_final = dateFormat.parse(year + "-" + mesFormat + "-" + (diaFormat+1));
}catch (ParseException e){
e.printStackTrace();
}
String outDate = dateFormat.format(date);
fecha = outDate;
}
public static String date(){
return fecha;
}
}
| 33.736842
| 107
| 0.685907
|
5d3e7de863c313afd523d8e52314124268e6fc5d
| 802
|
package me.zhyd.oauth.enums.scope;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* Stackoverflow 平台 OAuth 授权范围
*
* @author yadong.zhang (yadong.zhang0415(a)gmail.com)
* @version 1.0.0
* @since 1.0.0
*/
@Getter
@AllArgsConstructor
public enum AuthStackoverflowScope implements AuthScope {
/**
* {@code scope} 含义,以{@code description} 为准
*/
read_inbox("read_inbox", "access a user's global inbox", true),
NO_EXPIRY("no_expiry", "access_token's with this scope do not expire", false),
WRITE_ACCESS("write_access", "perform write operations as a user", false),
PRIVATE_INFO("private_info", "access full history of a user's private actions on the site", false);
private String scope;
private String description;
private boolean isDefault;
}
| 26.733333
| 103
| 0.710723
|
c671bb70fad1ae69213da16046821a3c66ec0a7e
| 599
|
package inheritance;
public class Main {
public static void main(String[] args) {
IndividualCustomer yasin = new IndividualCustomer();
yasin.customerNumber = "12345";
CorporateCustomer zrBey = new CorporateCustomer();
zrBey.customerNumber = "54321";
Customer ali = new RetiredCustomer();
ali.customerNumber = "13579";
CustomerManager customerManager = new CustomerManager();
/*
* customerManager.add(yasin); customerManager.add(zrBey);
* customerManager.add(ali);
*
*/
Customer[] customers = { yasin, zrBey, ali };
customerManager.addMuliple(customers);
}
}
| 23.038462
| 60
| 0.712855
|
1c687fd3be873eb0ffdbc771e0e3dc4a01a8d5d9
| 2,687
|
package com.gitlab.pedrioko.spring.beans;
import com.gitlab.pedrioko.config.AppInfo;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.convert.DefaultListDelimiterHandler;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import java.util.Iterator;
import java.util.Properties;
@Configuration
public class RootBeans {
private static final Logger LOGGER = LoggerFactory.getLogger(RootBeans.class);
@Autowired
private Environment environment;
static AppInfo loadApplicationInfo() {
PropertiesConfiguration external = null;
try {
external = new FileBasedConfigurationBuilder<>(PropertiesConfiguration.class)
.configure(new Parameters().properties().setFileName("META-INF/applicationInfo.properties")
.setThrowExceptionOnMissing(true)
.setListDelimiterHandler(new DefaultListDelimiterHandler(',')).setIncludesAllowed(false)
).getConfiguration();
} catch (ConfigurationException e) {
LOGGER.warn("WARNING -- NOT FOUND applicationInfo.properties");
}
Properties pro = new Properties();
Iterator<String> keys = null;
if (external != null) {
keys = external.getKeys();
PropertiesConfiguration finalExternal = external;
keys.forEachRemaining(e -> pro.setProperty(e, finalExternal.getString(e)));
}
AppInfo applicationInfo = AppInfo.load(pro);
return applicationInfo;
}
@Bean
public AppInfo appInfo() {
try {
LOGGER.info("Initializing Application Info");
AppInfo applicationInfo = loadApplicationInfo();
if (applicationInfo.getName() == null) {
applicationInfo.setName(environment.getProperty("spring.application.name"));
}
if (applicationInfo.getName() == null || applicationInfo.getName().isEmpty()) {
applicationInfo.setName("ATS App");
}
return applicationInfo;
} catch (Exception e) {
LOGGER.error("ERROR LOADING APP INFO");
return null;
}
}
}
| 37.84507
| 116
| 0.681057
|
4278aecfcb80565045a6801d2776fab0e954b716
| 3,152
|
package com.uddernetworks.lak.sounds.modulation;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.jsyn.Synthesizer;
import com.jsyn.unitgen.VariableRateDataReader;
import com.uddernetworks.lak.sounds.SoundVariant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Map;
import static com.uddernetworks.lak.Utility.clamp;
import static com.uddernetworks.lak.Utility.copyBuffer;
import static com.uddernetworks.lak.Utility.mapRange;
/**
* A modulator to change the pitch of a sound.
*/
public class VolumeModulation extends SoundModulation {
private static final Logger LOGGER = LoggerFactory.getLogger(VolumeModulation.class);
@JsonIgnore
private final SoundVariant soundVariant;
// The change in volume of the sound from 0.0 - 1.0
private float volume = 0;
public VolumeModulation(SoundVariant soundVariant) {
this.soundVariant = soundVariant;
}
@Override
public ModulationId getId() {
return ModulationId.VOLUME;
}
@Override
public SoundVariant getSoundVariant() {
return soundVariant;
}
/**
* Sets the volume of the sound.
* <br>Range: [0.0, 1.0]
* <br>Default: 1.0
*
* @return The volume of the sound
*/
public float getVolume() {
return volume;
}
/**
* Sets the volume of the sound.
* <br>Range: [0.0, 1.0]
* <br>Default: 1.0
*
* @param volume The volume of the sound to set
* @return The current {@link PitchModulation}
*/
public VolumeModulation setVolume(float volume) {
this.volume = clamp(volume, 0, 1);
return this;
}
@Override
public void updateFromEndpoint(ModulatorData data) {
volume = clamp(data.<Number>get("volume", 1F).floatValue(), 0, 1);
}
@Override
public ModulatorData getSerializable() {
return new ModulatorData(Map.of("volume", volume));
}
public static VolumeModulation fromModularData(SoundVariant soundVariant, ModulatorData data) {
var volumeModulation = new VolumeModulation(soundVariant);
volumeModulation.updateFromEndpoint(data);
return volumeModulation;
}
@Override
public void modulateSound(Synthesizer synth, VariableRateDataReader player) {
LOGGER.debug("Current amplitude {} range: [{}, {}]", player.amplitude.get(), player.amplitude.getMinimum(), player.amplitude.getMaximum());
player.amplitude.set(mapRange(volume, 0, 1, player.amplitude.getMinimum(), player.amplitude.getMaximum()));
}
@Override
public byte[] serialize() {
var output = copyBuffer(super.serialize(), 32);
output.putFloat(volume);
return output.array();
}
public static VolumeModulation deserialize(SoundVariant soundVariant, ByteBuffer buffer) {
var modulation = new VolumeModulation(soundVariant);
modulation.volume = buffer.getFloat();
return modulation;
}
}
| 29.185185
| 147
| 0.688769
|
a3415855d0118657c5b63f79a19c601bcd733b33
| 441
|
package com.kent.gumiho.sql.dialect.ppas.ast.clause;
import com.kent.gumiho.sql.basic.ast.AbstractSQLObject;
import com.kent.gumiho.sql.basic.visitor.SQLVisitor;
import lombok.Getter;
import lombok.Setter;
/**
* @author kongtong.ouyang on 2018/2/8.
*/
@Setter
@Getter
public class SQLCallSpec extends AbstractSQLObject {
private SQLDeclaration declaration;
@Override
protected void accept0(SQLVisitor visitor) {
}
}
| 18.375
| 55
| 0.755102
|
df7afb5f5c34056c39779bcdf031b729b5c3ce8a
| 172
|
package com.github.chenqimiao.component;
/**
* @Auther: chenqimiao
* @Date: 2019/11/3 20:41
* @Description:
*/
public interface IndexService {
void getIndex();
}
| 14.333333
| 40
| 0.674419
|
dc863591d10811ab5d97e5d9dbc806232104eb4f
| 3,216
|
/**
* Copyright (c) 2018-2019, Jie Li 李杰 (mqgnsds@163.com).
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.momo.mapper.res.authority;
import com.google.common.collect.Lists;
import lombok.*;
import org.apache.commons.collections4.CollectionUtils;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
/**
* @ProjectName: momo-cloud-permission
* @Package: com.momo.mapper.res.authority
* @Description: 比较两个list集合里的值 大小 ,并知道最大的那个值在哪个list里
* @Author: Jie Li
* @CreateDate: 2019/8/24 0024 15:05
* @UpdateDate: 2019/8/24 0024 15:05
* @Version: 1.0
* <p>Copyright: Copyright (c) 2019</p>
*/
@Getter
@Setter
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(of = {"roleType"})
public class CheckTwoSetSizeRes {
//set类型 1 当前登录用户所拥有的 角色类型
// 2 为用户授权所拥有的 角色类型
private Integer whichType;
//需要比较的值
private Integer roleType;
/**
* @param currentLoginRoleType 1 当前登录用户所拥有的 角色类型
* @param authorRoleType 2 为用户授权所拥有的 角色类型
* @return
*/
public static boolean CheckTwoSetSize(Set<Integer> currentLoginRoleType, Set<Integer> authorRoleType) {
if (CollectionUtils.isEmpty(currentLoginRoleType)) {
return true;
}
if (CollectionUtils.isEmpty(authorRoleType)) {
return false;
}
//角色的类型,0:管理员(老板),1:管理员(员工) 2:普通员工 3:其他
if (currentLoginRoleType.contains(0)) {
return false;
}
List<CheckTwoSetSizeRes> checkTwoSetSizeRes = Lists.newArrayList();
currentLoginRoleType.forEach(integer -> {
CheckTwoSetSizeRes setSizeRes = new CheckTwoSetSizeRes();
setSizeRes.setWhichType(1);
setSizeRes.setRoleType(integer);
checkTwoSetSizeRes.add(setSizeRes);
});
authorRoleType.forEach(integer -> {
CheckTwoSetSizeRes setSizeRes = new CheckTwoSetSizeRes();
setSizeRes.setWhichType(2);
setSizeRes.setRoleType(integer);
checkTwoSetSizeRes.add(setSizeRes);
});
checkTwoSetSizeRes.sort(deptSeqComparator);
return !checkTwoSetSizeRes.get(0).getWhichType().equals(1);
}
//由小到大
//优先保证 当前登录用户所拥有的 角色类型 在前面
private static Comparator<CheckTwoSetSizeRes> deptSeqComparator = new Comparator<CheckTwoSetSizeRes>() {
@Override
public int compare(CheckTwoSetSizeRes o1, CheckTwoSetSizeRes o2) {
Integer size = o1.getRoleType() - o2.getRoleType();
if (size.equals(0)) {
return o1.getWhichType() - o2.getWhichType();
}
return o1.getRoleType() - o2.getRoleType();
}
};
}
| 33.5
| 108
| 0.666356
|
c164b5111a624f79c27e515c5a0f2c8c25bdc73e
| 129
|
package dev.wearkit.core.common;
import android.graphics.Bitmap;
public interface Stampable {
void stamp(Bitmap bitmap);
}
| 16.125
| 32
| 0.767442
|
f298f5c3305f85305bc160a72cbf16d5c515ce60
| 3,580
|
/*
* The MIT License
*
* Copyright 2019 WildBees Labs, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.wildbeeslabs.sensiblemetrics.diffy.validator.digits.impl;
import com.wildbeeslabs.sensiblemetrics.diffy.common.utils.ValidationUtils;
import com.wildbeeslabs.sensiblemetrics.diffy.processor.digits.impl.BaseDigitProcessor;
import com.wildbeeslabs.sensiblemetrics.diffy.validator.digits.iface.DigitValidator;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;
import java.security.InvalidParameterException;
/**
* Abstract <b>Modulus</b> Check digit calculation/validation.
* <p>
* Provides a <i>base</i> class for building <i>modulus</i> Check
* Digit routines.
* <p>
* This implementation only handles <i>single-digit numeric</i> codes, such as
* <b>EAN-13</b>. For <i>alphanumeric</i> codes such as <b>EAN-128</b> you
* will need to implement/override the <code>toInt()</code> and
* <code>toChar()</code> methods.
* <p>
*
* @version $Revision: 1739357 $
* @since Validator 1.4
*/
/**
* Base {@link DigitValidator} implementation
*/
@Data
@EqualsAndHashCode
@ToString
public abstract class BaseDigitValidator implements DigitValidator {
/**
* Default explicit serialVersionUID for interoperability
*/
private static final long serialVersionUID = 6459345454087974579L;
// N.B. The modulus can be > 10 provided that the implementing class overrides toCheckDigit and toInt
// (for example as in ISBN10DigitValidator)
private final BaseDigitProcessor processor;
/**
* Construct modulus check digit routine for a specified modulus.
*
* @param processor The processor value to use for the check digit calculation
*/
public BaseDigitValidator(final BaseDigitProcessor processor) {
ValidationUtils.notNull(processor, "Processor should not be null");
this.processor = processor;
}
/**
* Validate a modulus check digit for a code.
*
* @param code The code to validate
* @return <code>true</code> if the check digit is valid, otherwise
* <code>false</code>
*/
@Override
public boolean validate(final String code) {
if (StringUtils.isBlank(code)) {
return false;
}
try {
int modulusResult = this.getProcessor().calculateModulus(code, true);
return (modulusResult == 0);
} catch (InvalidParameterException ex) {
return false;
}
}
}
| 36.161616
| 105
| 0.718715
|
66986779716d8c614765a9950921666bee3db23f
| 1,799
|
package com.gmail.willramanand.RamMMO.item.items.tools;
import com.gmail.willramanand.RamMMO.RamMMO;
import com.gmail.willramanand.RamMMO.item.Item;
import com.gmail.willramanand.RamMMO.item.ItemManager;
import com.gmail.willramanand.RamMMO.item.ItemRarity;
import com.gmail.willramanand.RamMMO.item.items.BaseItem;
import com.gmail.willramanand.RamMMO.utils.DataUtils;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ShapedRecipe;
import org.bukkit.persistence.PersistentDataType;
public class VulcansPick extends BaseItem {
public VulcansPick() {
super(Item.VULCANS_PICK, Material.NETHERITE_PICKAXE, ItemRarity.MYTHICAL, Item.VULCANS_PICK.version());
setLore("Breaks all pickaxe materials with a single swing");
setFinal();
}
@Override
protected void setAttributes() {
}
@Override
protected void setEnchantments() {
meta.addEnchant(Enchantment.DURABILITY, 5, true);
meta.addEnchant(Enchantment.DIG_SPEED, 10, true);
}
@Override
protected void setTags() {
DataUtils.set(meta, "insta_break", PersistentDataType.INTEGER, 1);
}
@Override
protected void setRecipe() {
ShapedRecipe shapedRecipe = new ShapedRecipe(new NamespacedKey(RamMMO.getInstance(), item.getRecipeKey()), itemStack);
shapedRecipe.shape("fpf", " s ", " n ");
shapedRecipe.setIngredient('p', Material.NETHERITE_PICKAXE);
shapedRecipe.setIngredient('s', ItemManager.getItem(Item.ENCHANTED_NETHERSTAR));
shapedRecipe.setIngredient('f', ItemManager.getItem(Item.FIERY_SCALE));
shapedRecipe.setIngredient('n', ItemManager.getItem(Item.ENCHANTED_NETHERITE));
recipe = shapedRecipe;
}
}
| 35.98
| 126
| 0.734853
|
b16e50574f81733bfa4af8ffcdcbe5e0ba683b8a
| 2,683
|
package scipts.postanalysis;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import model.Experiment;
import model.PSM;
import model.Peptide;
import model.Protein;
import model.ProteinGroup;
import model.ProteinSubGroup;
public class ExportUpSet {
public static void fromProteinGroups(Experiment[] experiments, LinkedList<ProteinGroup> proteingroups, String dataFolder, String filename) {
try {
// find experiment ids
HashMap<String, Integer> exps = new HashMap<String, Integer>();
int i = 0;
for (Experiment exp : experiments) {
exps.put(exp.getId(), i);
i++;
}
// write file subgroup
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(dataFolder + "/upsetplot/" + filename + "_subgroups.tsv")));
bw.write("ProteinSubgroup");
for (Experiment exp : experiments) {
bw.write("\t" + exp.getId());
}
bw.write("\n");
for (ProteinGroup pg : proteingroups) {
for (ProteinSubGroup sg : pg.getSubgroups()) {
bw.write(sg.getId());
// get counts
int[] psmCounts = new int[exps.size()];
HashSet<PSM> psms = new HashSet<PSM>();
for (Protein p : sg.getProteins()) {
for (Peptide pep : p.getPeptides()) {
for (PSM psm : pep.getPsms()) {
if (!psms.contains(psm)) {
int index = exps.get(psm.getExperiment());
psmCounts[index]++;
psms.add(psm);
}
}
}
}
for (int j = 0; j < psmCounts.length; j++) {
bw.write("\t" + psmCounts[j]);
}
bw.write("\n");
}
}
bw.close();
// write file group
bw = new BufferedWriter(new FileWriter(new File(dataFolder + "/upsetplot/" + filename + "_groups.tsv")));
bw.write("ProteinGroup");
for (Experiment exp : experiments) {
bw.write("\t" + exp.getId());
}
bw.write("\n");
for (ProteinGroup pg : proteingroups) {
bw.write(pg.getId());
// get counts
int[] psmCounts = new int[exps.size()];
HashSet<PSM> psms = new HashSet<PSM>();
for (Protein p : pg.getProteins()) {
for (Peptide pep : p.getPeptides()) {
for (PSM psm : pep.getPsms()) {
if (!psms.contains(psm)) {
int index = exps.get(psm.getExperiment());
psmCounts[index]++;
psms.add(psm);
}
}
}
}
for (int j = 0; j < psmCounts.length; j++) {
bw.write("\t" + psmCounts[j]);
}
bw.write("\n");
}
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 28.542553
| 142
| 0.576966
|
5dd30adad63db07485582e8142b86d706308e7f2
| 779
|
package com.repomgr.repomanager.ui;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class UiErrorController implements ErrorController {
@GetMapping(value = "/error")
public String handleError() {
return "redirect:/public/index.html";
}
/**
* The return value from this method is not used; the property `server.error.path`
* must be set to override the default error page path.
* @return the error path
* @deprecated since 2.3.0 in favor of setting the property `server.error.path`
*/
@Override
@Deprecated
public String getErrorPath() {
return null;
}
}
| 28.851852
| 86
| 0.709884
|
ef63bf99d946d026f4be8b3df49af4227e6b2569
| 1,235
|
package com.montealegreluis.servicebuses.querybus.locator;
import com.montealegreluis.servicebuses.ReflectionsActionMapper;
import com.montealegreluis.servicebuses.querybus.Query;
import com.montealegreluis.servicebuses.querybus.QueryHandler;
import com.montealegreluis.servicebuses.querybus.Response;
import java.util.Map;
public final class ReflectionsQueryHandlerLocator implements QueryHandlerLocator {
private final Map<
Class<? extends Query>,
Class<? extends QueryHandler<? extends Query, ? extends Response>>>
queryHandlers;
public ReflectionsQueryHandlerLocator(String packageName) {
ReflectionsActionMapper<
Class<? extends Query>,
Class<? extends QueryHandler<? extends Query, ? extends Response>>>
mapper = new ReflectionsActionMapper<>(packageName);
queryHandlers = mapper.map(QueryHandler.class);
}
@Override
public Class<? extends QueryHandler<? extends Query, ? extends Response>> search(
Class<? extends Query> queryClass) throws UnknownQueryHandler {
var queryHandlerClass = queryHandlers.get(queryClass);
if (null == queryHandlerClass) throw UnknownQueryHandler.forQuery(queryClass);
return queryHandlerClass;
}
}
| 37.424242
| 83
| 0.760324
|
2f24aab9f257c852ad830eec70577978bdca3f27
| 11,386
|
package com.weique.overhaul.v2.mvp.presenter;
import android.app.Activity;
import android.app.Application;
import com.google.gson.Gson;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.integration.IRepositoryManager;
import com.weique.overhaul.v2.app.ReworkBasePresenter;
import com.weique.overhaul.v2.app.common.CommonNetworkRequest;
import com.weique.overhaul.v2.app.common.Constant;
import com.weique.overhaul.v2.app.common.EventBusConstant;
import com.weique.overhaul.v2.app.common.RouterHub;
import com.weique.overhaul.v2.app.utils.CommonPermissionUtil;
import com.weique.overhaul.v2.app.utils.SignUtil;
import com.weique.overhaul.v2.mvp.contract.EventsReportedLookContract;
import com.weique.overhaul.v2.mvp.model.api.service.EventsReportedService;
import com.weique.overhaul.v2.mvp.model.entity.BaseBean;
import com.weique.overhaul.v2.mvp.model.entity.InformationItemPictureBean;
import com.weique.overhaul.v2.mvp.model.entity.UploadFileRsponseBean;
import com.weique.overhaul.v2.mvp.model.entity.event.EventBusBean;
import com.weique.overhaul.v2.mvp.ui.popupwindow.HeatDialog;
import org.simple.eventbus.EventBus;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import io.reactivex.Observable;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import static com.weique.overhaul.v2.mvp.model.entity.EventsReportedBean.ListBean;
/**
* ================================================
* Description:
* <p>
* ================================================
*
* @author GK
*/
@ActivityScope
public class EventsReportedLookPresenter extends ReworkBasePresenter<EventsReportedLookContract.Model, EventsReportedLookContract.View> {
@Inject
RxErrorHandler mErrorHandler;
@Inject
Application mApplication;
@Inject
ImageLoader mImageLoader;
@Inject
AppManager mAppManager;
@Inject
Gson gson;
@Inject
IRepositoryManager mRepositoryManager;
@Inject
public EventsReportedLookPresenter(EventsReportedLookContract.Model model, EventsReportedLookContract.View rootView) {
super(model, rootView);
}
@Override
public void onDestroy() {
super.onDestroy();
this.mErrorHandler = null;
this.mAppManager = null;
this.mImageLoader = null;
this.mApplication = null;
}
/**
* 获取事件详情
*
* @param id id
*/
public void getEventDetail(String id, String custId) {
commonGetData(mModel.getEventRecordInfo(id, custId), mErrorHandler, eventsReportedLookBean -> {
mRootView.setData(eventsReportedLookBean);
});
}
/**
* 评价
*
* @param evaluation
* @param recordId
*/
public void createEvaluation(String evaluation, String recordId, String images) {
commonGetData(mModel.createEvaluation(evaluation, recordId, images), mErrorHandler, o -> {
EventBus.getDefault().post(new EventBusBean(EventBusConstant.SELECT), RouterHub.APP_EVENTSREPORTEDACTIVITY);
mRootView.killMyself();
});
}
/**
* 获取小流程 - 办理人处理信息列表
*
* @param custId
*/
public void getEventProceedRecord(String custId, String eventRId) {
commonGetData(mModel.getEventProceedRecord(custId, eventRId), mErrorHandler, eventProceedRecordBeans -> {
mRootView.setTransactList(eventProceedRecordBeans);
});
}
public void getDepartment(String departmentId) {
commonGetData(mModel.getGetDepartment(departmentId), mErrorHandler, gridInformationBean -> {
mRootView.gotoMapTv(gridInformationBean.getPointsInJSON());
});
}
/**
* 处置
*
* @param id 事件流程记录Id
* @param fileUrls 图片上传
* @param returnReason 处理内容
*/
public void proceedingOrder(String id, String fileUrls, String returnReason) {
Map<String, Object> map = new HashMap<>(8);
map.put("Id", id);
map.put("FileUrls", fileUrls);
map.put("ReturnReason", returnReason);
Observable<BaseBean<Object>> observable = mRepositoryManager.obtainRetrofitService(EventsReportedService.class)
.proceedingOrder1(SignUtil.paramSign(map));
commonGetData(observable, mErrorHandler, o -> {
EventBus.getDefault().post(new EventBusBean(EventBusConstant.SELECT), RouterHub.APP_EVENTSREPORTEDACTIVITY);
mRootView.killMyself();
});
}
/**
* 同意 、 拒绝协同
*
* @param id 事件流程记录Id
* @param returnReason 处理内容
*/
public void eventRecordCoopReceivingOrder(String id, int enumEventProceedStatus, String returnReason) {
Map<String, Object> map = new HashMap<>(8);
map.put("Id", id);
map.put("enumEventProceedStatus", enumEventProceedStatus);
map.put("ReturnReason", returnReason);
Observable<BaseBean<Object>> observable = mRepositoryManager.obtainRetrofitService(EventsReportedService.class)
.eventRecordCoopReceivingOrder(SignUtil.paramSign(map));
commonGetData(observable, mErrorHandler, o -> {
EventBus.getDefault().post(new EventBusBean(EventBusConstant.SELECT), RouterHub.APP_EVENTSREPORTEDACTIVITY);
mRootView.killMyself();
});
}
/**
* 受理 退回
*
* @param intEventProceedStatus
*/
public void receivingOrder(String id, int intEventProceedStatus, String returnReason) {
Map<String, Object> map = new HashMap<>(8);
map.put("Id", id);
map.put("intEventProceedStatus", intEventProceedStatus);
map.put("ReturnReason", returnReason);
Observable<BaseBean<Object>> observable = mRepositoryManager.obtainRetrofitService(EventsReportedService.class)
.receivingOrder(SignUtil.paramSign(map));
commonGetData(observable, mErrorHandler, o -> {
EventBus.getDefault().post(new EventBusBean(EventBusConstant.SELECT), RouterHub.APP_EVENTSREPORTEDACTIVITY);
mRootView.killMyself();
});
}
/**
* 核查通过 退回
*
* @param id
* @param enumOrderStatus enumOrderStatus
* @param returnReason
*/
public void eventRecordCheckOrder(String id, int enumOrderStatus, String returnReason) {
Map<String, Object> map = new HashMap<>(8);
map.put("Id", id);
map.put("enumOrderStatus", enumOrderStatus);
map.put("ReturnReason", returnReason);
Observable<BaseBean<Object>> observable = mRepositoryManager.obtainRetrofitService(EventsReportedService.class)
.EventRecordCheckOrder(SignUtil.paramSign(map));
commonGetData(observable, mErrorHandler, o -> {
EventBus.getDefault().post(new EventBusBean(EventBusConstant.SELECT), RouterHub.APP_EVENTSREPORTEDACTIVITY);
mRootView.killMyself();
});
}
/**
* 作废
*
* @param id id
*/
public void invalid(String id) {
commonGetData(mModel.invalid(id), mErrorHandler, o -> {
EventBus.getDefault().post(new EventBusBean(EventBusConstant.SELECT), RouterHub.APP_EVENTSREPORTEDACTIVITY);
mRootView.killMyself();
});
}
public void getPermission(int max) {
CommonPermissionUtil.getPermission((Activity) mRootView.getActivity(), mErrorHandler,
() -> mRootView.goToPhotoAlbum(max), Constant.PERMISSIONS_LIST_READ_WRITE_CAMERA);
}
/**
* 上传文件
*
* @param compressPaths compressPath 文件压缩路径
*/
public void upLoadFile(String elementId, List<String> compressPaths) {
try {
CommonNetworkRequest.upLoadFile(elementId, compressPaths,
mErrorHandler, mRootView, mRepositoryManager,
uploadFileRsponseBeans -> {
try {
List<InformationItemPictureBean> list = new ArrayList<>();
for (UploadFileRsponseBean uploadFileRsponseBean : uploadFileRsponseBeans) {
String path = uploadFileRsponseBean.getUrl();
list.add(new InformationItemPictureBean(path));
}
mRootView.setUpLoadItem(list);
} catch (Exception e) {
e.printStackTrace();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 初始化dialog
*
* @param id 事件id
* @param dialog 弹框
* @param status 要操作到的 目标状态
*/
public void initDialog(String id, HeatDialog dialog, int status) {
try {
if (status == ListBean.EventsReportedEnumNewBean.DISPOSE_END) {
dialog.setContentHint("请填写处置意见");
dialog.setConfirmBtnText("处置");
}
if (status == ListBean.EventsReportedEnumNewBean.EXIT) {
dialog.setContentHint("请填写退回原因");
dialog.setConfirmBtnText("退回");
}
if (status == ListBean.EventsReportedEnumNewBean.INSPECT_FAIL) {
dialog.setContentHint("请填写核查退回原因");
dialog.setConfirmBtnText("核查退回");
}
if (status == ListBean.EventsReportedEnumNewBean.EVALUATE) {
dialog.setContentHint("请填写评价信息");
dialog.setConfirmBtnText("评价");
}
if (status == ListBean.SYNCHRONIZE) {
dialog.setContentHint("请填写同意协同理由");
dialog.setConfirmBtnText("同意协同");
}
if (status == ListBean.REFUSED) {
dialog.setContentHint("请填写拒绝协同理由");
dialog.setConfirmBtnText("拒绝协同");
}
dialog.setOnConfirmClickListener((heatDialog, content) -> {
try {
switch (status) {
case ListBean.EventsReportedEnumNewBean.DISPOSE_END:
proceedingOrder(id, dialog.getImageUrls(), content);
break;
case ListBean.EventsReportedEnumNewBean.EXIT:
receivingOrder(id, 1, "");
break;
case ListBean.EventsReportedEnumNewBean.INSPECT_FAIL:
eventRecordCheckOrder(id, 7, "");
break;
case ListBean.EventsReportedEnumNewBean.EVALUATE:
createEvaluation(content, id, dialog.getImageUrls());
break;
case ListBean.SYNCHRONIZE:
eventRecordCoopReceivingOrder(id, 2, content);
break;
case ListBean.REFUSED:
eventRecordCoopReceivingOrder(id, 3, content);
break;
default:
break;
}
} catch (Exception e) {
e.printStackTrace();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 36.610932
| 137
| 0.60996
|
bfae7723f1017b5e39bbcf00a95f68fd70bbedc6
| 9,449
|
package de.metas.handlingunits.attribute.storage.impl;
/*
* #%L
* de.metas.handlingunits.base
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import de.metas.handlingunits.AbstractHUTest;
import de.metas.handlingunits.HUTestHelper;
import de.metas.handlingunits.IHandlingUnitsDAO;
import de.metas.handlingunits.attribute.storage.IAttributeStorageFactory;
import de.metas.handlingunits.attributes.sscc18.ISSCC18CodeBL;
import de.metas.handlingunits.attributes.sscc18.impl.SSCC18CodeBL;
import de.metas.handlingunits.attributes.sscc18.impl.SSCC18CodeBLTests;
import de.metas.handlingunits.model.I_M_HU;
import de.metas.handlingunits.model.I_M_HU_PI;
import de.metas.handlingunits.model.I_M_HU_PI_Attribute;
import de.metas.handlingunits.model.I_M_HU_PI_Version;
import de.metas.handlingunits.model.X_M_HU_PI_Attribute;
import de.metas.handlingunits.model.X_M_HU_PI_Version;
import de.metas.handlingunits.test.misc.builders.HUPIAttributeBuilder;
import de.metas.util.Services;
import de.metas.util.lang.ReferenceListAwareEnum;
import de.metas.util.lang.ReferenceListAwareEnums;
import lombok.NonNull;
import org.adempiere.mm.attributes.AttributeId;
import org.adempiere.mm.attributes.api.impl.AttributesTestHelper;
import org.adempiere.mm.attributes.spi.IAttributeValueGenerator;
import org.adempiere.model.InterfaceWrapperHelper;
import org.compiere.model.I_M_Attribute;
import org.compiere.model.X_M_Attribute;
import org.junit.jupiter.api.Test;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* This test is making sure current {@link IAttributeValueGenerator} implementations are not failing when {@link HUAttributeStorage#generateInitialAttributes()} is invoked.
*
* @author tsa
*
*/
public class HUAttributeStorage_generateInitialAttributes_Integration_Test extends AbstractHUTest
{
private IAttributeStorageFactory attributeStorageFactory;
private int nextSSCC18SerialNumber;
private I_M_HU_PI huPI;
private I_M_HU_PI_Version huPIVersion;
private final HashMap<Class<? extends IAttributeValueGenerator>, Class<? extends ReferenceListAwareEnum>> //
registeredEnums = new HashMap<>();
protected final void registerEnum(
@NonNull final Class<? extends IAttributeValueGenerator> generatorClass,
@NonNull final Class<? extends ReferenceListAwareEnum> enumType)
{
registeredEnums.put(generatorClass, enumType);
}
@Override
protected void initialize()
{
attributeStorageFactory = helper.getHUContext().getHUAttributeStorageFactory();
huPI = helper.createHUDefinition(HUTestHelper.NAME_IFCO_Product, X_M_HU_PI_Version.HU_UNITTYPE_TransportUnit);
huPIVersion = Services.get(IHandlingUnitsDAO.class).retrievePICurrentVersion(huPI);
setupSSCC18AttributeValueGenerator();
}
private void setupSSCC18AttributeValueGenerator()
{
nextSSCC18SerialNumber = 0;
final SSCC18CodeBL sscc18CodeService = new SSCC18CodeBL(orgId -> ++nextSSCC18SerialNumber);
Services.registerService(ISSCC18CodeBL.class, sscc18CodeService);
SSCC18CodeBLTests.setManufacturerCode("0001");
}
private void setupHUPIAttribute(
final I_M_HU_PI huPI,
final Class<? extends IAttributeValueGenerator> attributeValueGeneratorClass)
{
IAttributeValueGenerator attributeValueGenerator;
try
{
attributeValueGenerator = attributeValueGeneratorClass.newInstance();
}
catch (InstantiationException | IllegalAccessException ex)
{
throw new AssertionError("Cannot instantiate " + attributeValueGeneratorClass, ex);
}
final Set<String> attributeValueTypes;
if (attributeValueGenerator.getAttributeValueType() != null)
{
attributeValueTypes = ImmutableSet.of(attributeValueGenerator.getAttributeValueType());
}
else
{
attributeValueTypes = ImmutableSet.of(
X_M_Attribute.ATTRIBUTEVALUETYPE_StringMax40,
X_M_Attribute.ATTRIBUTEVALUETYPE_Number,
X_M_Attribute.ATTRIBUTEVALUETYPE_Date,
X_M_Attribute.ATTRIBUTEVALUETYPE_List);
}
for (final String attributeValueType : attributeValueTypes)
{
final String attributeName = "ATTR_" + attributeValueGeneratorClass.getSimpleName() + "_" + attributeValueType;
final boolean isInstanceAttribute = true;
final I_M_Attribute attribute = new AttributesTestHelper().createM_Attribute(
attributeName, // Attribute Name
attributeValueType, // Attribute Type
attributeValueGeneratorClass,
uomKg,
isInstanceAttribute);
createAttributeValues(attribute, attributeValueGeneratorClass);
final I_M_HU_PI_Attribute piAttribute = helper.createM_HU_PI_Attribute(HUPIAttributeBuilder.newInstance(attribute)
.setM_HU_PI(huPI)
.setPropagationType(X_M_HU_PI_Attribute.PROPAGATIONTYPE_NoPropagation));
piAttribute.setIsReadOnly(false);
piAttribute.setSeqNo(10);
InterfaceWrapperHelper.save(piAttribute);
}
}
private void createAttributeValues(final I_M_Attribute attribute, final Class<? extends IAttributeValueGenerator> attributeValueGeneratorClass)
{
final Class<? extends ReferenceListAwareEnum> enumType = registeredEnums.get(attributeValueGeneratorClass);
if (enumType != null)
{
final AttributesTestHelper attributesTestHelper = new AttributesTestHelper();
for (final ReferenceListAwareEnum value : ReferenceListAwareEnums.values(enumType))
{
attributesTestHelper.createM_AttributeValue(attribute, value.getCode());
}
}
}
@Test
public void test()
{
for (final Class<? extends IAttributeValueGenerator> attributeValueGeneratorClass : retrieveAttributeValueGeneratorClassnames())
{
if (isSkipTesting(attributeValueGeneratorClass))
{
continue;
}
test(attributeValueGeneratorClass);
}
}
private static final Set<Class<? extends IAttributeValueGenerator>> retrieveAttributeValueGeneratorClassnames()
{
final Stopwatch stopwatch = Stopwatch.createStarted();
final Reflections reflections = new Reflections(new ConfigurationBuilder()
.addUrls(ClasspathHelper.forClassLoader())
.setScanners(new SubTypesScanner()));
final Set<Class<? extends IAttributeValueGenerator>> attributeValueGeneratorClassnames = reflections.getSubTypesOf(IAttributeValueGenerator.class);
if (attributeValueGeneratorClassnames.isEmpty())
{
throw new RuntimeException("No classes found. Might be because for some reason Reflections does not work correctly with maven surefire plugin."
+ "\n See https://github.com/metasfresh/metasfresh/issues/4773.");
}
System.out.println("Found " + attributeValueGeneratorClassnames.size() + " classes in " + stopwatch.toString());
return attributeValueGeneratorClassnames;
}
private boolean isSkipTesting(final Class<? extends IAttributeValueGenerator> attributeValueGeneratorClass)
{
// Skip Mocked implementations, used for testing
final String attributeValueGeneratorClassname = attributeValueGeneratorClass.getName();
if (attributeValueGeneratorClassname.startsWith("Mocked")
|| attributeValueGeneratorClassname.indexOf("$Mocked") > 0)
{
return true;
}
// Skip interfaces
if (attributeValueGeneratorClass.isInterface())
{
return true;
}
// Skip abstract classes
if (Modifier.isAbstract(attributeValueGeneratorClass.getModifiers()))
{
return true;
}
return false;
}
/**
* Create a new {@link I_M_HU_PI_Attribute} configuration for given <code>attributeValueGeneratorClass</code>.
*
* The create a new {@link HUAttributeStorage} instance and invoke {@link HUAttributeStorage#generateInitialAttributes()}.
*
* @param attributeValueGeneratorClass
*/
public void test(final Class<? extends IAttributeValueGenerator> attributeValueGeneratorClass)
{
testWatcher.putContext(attributeValueGeneratorClass);
System.out.println("Testing: " + attributeValueGeneratorClass);
//
// Create an M_HU_PI_Attribute for given generator
setupHUPIAttribute(huPI, attributeValueGeneratorClass);
//
// Create a new dummy HU
final I_M_HU hu = InterfaceWrapperHelper.newInstance(I_M_HU.class, helper.getContextProvider());
hu.setM_HU_PI_Version(huPIVersion);
InterfaceWrapperHelper.save(hu);
//
// Create a new HU Attribute Storage instance
final HUAttributeStorage attributesStorage = new HUAttributeStorage(attributeStorageFactory, hu);
//
// Ask it to generate it's initial attributes and hope to not fail ;)
final Map<AttributeId, Object> defaultAttributesValue = ImmutableMap.of();
attributesStorage.generateInitialAttributes(defaultAttributesValue);
}
}
| 35.927757
| 172
| 0.79437
|
5c456428e49ab73d71bb2cc4d153da1d4c7864a4
| 572
|
package nl.knmi.geoweb.backend.product.sigmetairmet;
public enum SigmetAirmetDirection {
N(0),NNE(22.5),NE(45),ENE(67.5),E(90),ESE(112.5),SE(135),SSE(157.5),S(180),SSW(202.5),SW(225),WSW(247.5),W(270),WNW(292.5),NW(315),NNW(337.5);
public static SigmetAirmetDirection getDirection(String dir) {
for (SigmetAirmetDirection v: SigmetAirmetDirection.values()) {
if (dir.equals(v.toString())) return v;
}
return null;
}
private double dir;
public double getDir() {
return this.dir;
}
SigmetAirmetDirection(double dir) {
this.dir=dir;
}}
| 27.238095
| 144
| 0.685315
|
46672219c65b9dbaef0c41fb3fab58e62fbdd7cd
| 1,042
|
package io.undertow.servlet;
import org.jboss.logging.Logger;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation that can be applied to exceptions to control how they are logged by Undertow.
*
* Note that this will only take effect if the deployments error handler has not been changed.
*
* @author Stuart Douglas
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface ExceptionLog {
/**
* The default log level for this exception.
*/
Logger.Level value() default Logger.Level.ERROR;
/**
* The level at which to log stack traces. If this is a higher level
* than the default then they will be logged by default at the default level.
*/
Logger.Level stackTraceLevel() default Logger.Level.FATAL;
/**
* The category to log this exception under
*/
String category();
}
| 26.717949
| 94
| 0.726488
|
43013a0fa9f22e3319a2c977009a0ae7246e2e43
| 1,260
|
package com.atlassian.plugin.connect.testsupport.filter;
import com.atlassian.sal.api.user.UserManager;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Record all requests to the fake add-on servlet, throwing errors on any that get this far and do not match.
* Also see {@link com.atlassian.plugin.connect.testsupport.filter.AddonTestFilterBase}.
*/
public class AddonTestFilter extends AddonTestFilterBase {
public AddonTestFilter(AddonTestFilterResults testFilterResults, UserManager userManager,
AddonPrecannedResponseHelper addonPrecannedResponseHelper) {
super(testFilterResults, userManager, addonPrecannedResponseHelper);
}
@Override
protected boolean shouldProcess(HttpServletRequest request) {
// process all incoming requests
return true;
}
@Override
protected void processNonMatch(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException {
// capture all requests and stop; if it doesn't match then something is misconfigured
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
| 39.375
| 138
| 0.769048
|
5d493955ad632059516ea7b34b1d9eb3bd1ddeb9
| 4,323
|
package com.nepxion.thunder.common.container;
/**
* <p>Title: Nepxion Thunder</p>
* <p>Description: Nepxion Thunder For Distribution</p>
* <p>Copyright: Copyright (c) 2017-2050</p>
* <p>Company: Nepxion</p>
* @author Haojun Ren
* @version 1.0
*/
import java.util.List;
import com.nepxion.thunder.cluster.consistency.ConsistencyExecutor;
import com.nepxion.thunder.cluster.loadbalance.LoadBalanceExecutor;
import com.nepxion.thunder.monitor.MonitorExecutor;
import com.nepxion.thunder.protocol.ClientExecutor;
import com.nepxion.thunder.protocol.ClientExecutorAdapter;
import com.nepxion.thunder.protocol.ClientInterceptorAdapter;
import com.nepxion.thunder.protocol.ServerExecutor;
import com.nepxion.thunder.protocol.ServerExecutorAdapter;
import com.nepxion.thunder.registry.RegistryExecutor;
import com.nepxion.thunder.registry.RegistryInitializer;
import com.nepxion.thunder.security.SecurityExecutor;
public class ExecutorContainer {
// 服务端启动适配器
private ServerExecutorAdapter serverExecutorAdapter;
// 客户端启动适配器
private ClientExecutorAdapter clientExecutorAdapter;
// 客户端调用拦截适配器
private ClientInterceptorAdapter clientInterceptorAdapter;
// 服务端启动器
private ServerExecutor serverExecutor;
// 客户端启动器
private ClientExecutor clientExecutor;
// 注册中心初始器
private RegistryInitializer registryInitializer;
// 注册中心执行器
private RegistryExecutor registryExecutor;
// 集群同步器
private ConsistencyExecutor consistencyExecutor;
// 负载均衡器
private LoadBalanceExecutor loadBalanceExecutor;
// 安全控制器
private SecurityExecutor securityExecutor;
// 监控器
private List<MonitorExecutor> monitorExecutors;
public ServerExecutorAdapter getServerExecutorAdapter() {
return serverExecutorAdapter;
}
public void setServerExecutorAdapter(ServerExecutorAdapter serverExecutorAdapter) {
this.serverExecutorAdapter = serverExecutorAdapter;
}
public ClientExecutorAdapter getClientExecutorAdapter() {
return clientExecutorAdapter;
}
public void setClientExecutorAdapter(ClientExecutorAdapter clientExecutorAdapter) {
this.clientExecutorAdapter = clientExecutorAdapter;
}
public ClientInterceptorAdapter getClientInterceptorAdapter() {
return clientInterceptorAdapter;
}
public void setClientInterceptorAdapter(ClientInterceptorAdapter clientInterceptorAdapter) {
this.clientInterceptorAdapter = clientInterceptorAdapter;
}
public ServerExecutor getServerExecutor() {
return serverExecutor;
}
public void setServerExecutor(ServerExecutor serverExecutor) {
this.serverExecutor = serverExecutor;
}
public ClientExecutor getClientExecutor() {
return clientExecutor;
}
public void setClientExecutor(ClientExecutor clientExecutor) {
this.clientExecutor = clientExecutor;
}
public RegistryInitializer getRegistryInitializer() {
return registryInitializer;
}
public void setRegistryInitializer(RegistryInitializer registryInitializer) {
this.registryInitializer = registryInitializer;
}
public RegistryExecutor getRegistryExecutor() {
return registryExecutor;
}
public void setRegistryExecutor(RegistryExecutor registryExecutor) {
this.registryExecutor = registryExecutor;
}
public ConsistencyExecutor getConsistencyExecutor() {
return consistencyExecutor;
}
public void setConsistencyExecutor(ConsistencyExecutor consistencyExecutor) {
this.consistencyExecutor = consistencyExecutor;
}
public LoadBalanceExecutor getLoadBalanceExecutor() {
return loadBalanceExecutor;
}
public void setLoadBalanceExecutor(LoadBalanceExecutor loadBalanceExecutor) {
this.loadBalanceExecutor = loadBalanceExecutor;
}
public SecurityExecutor getSecurityExecutor() {
return securityExecutor;
}
public void setSecurityExecutor(SecurityExecutor securityExecutor) {
this.securityExecutor = securityExecutor;
}
public List<MonitorExecutor> getMonitorExecutors() {
return monitorExecutors;
}
public void setMonitorExecutors(List<MonitorExecutor> monitorExecutors) {
this.monitorExecutors = monitorExecutors;
}
}
| 29.408163
| 96
| 0.757113
|
066d40203cad848ce1c728862fbcf9f874f923f4
| 339
|
package com.epam.training.microservice.service.pharmacies.service.load;
import com.google.common.collect.Lists;
import lombok.Data;
import java.util.Collection;
@Data
public class PharmacyLoadModel {
private String name;
private String address;
private Collection<PharmacyAvailableLoadModel> drugs = Lists.newArrayList();
}
| 24.214286
| 80
| 0.79351
|
9d68a8e1dcf4f88396031cd6472f1b4cb7a45752
| 321
|
package cz.tacr.elza.repository;
import cz.tacr.elza.domain.ArrRequestQueueItem;
import org.springframework.stereotype.Repository;
/**
* @author Martin Šlapa
* @since 12.12.2016
*/
@Repository
public interface RequestQueueItemRepositoryCustom {
ArrRequestQueueItem findNext(final Integer externalSystemId);
}
| 18.882353
| 65
| 0.791277
|
48dc83b3c689a868597242546bd8892a1a2f5eed
| 9,906
|
package com.example.bell_hangma;
/**
* This is an android hangman game, uses shared preferences on the device to keep the score
* This program filters keyboard input to only accept letters, and will convert to lowercase
* a reveal word button has been added for testing. at the end of each game, there is a 2 second delay, the score is saved and then the main activity restarts.
* Author: Jesse Bell
*/
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.Editable;
import android.text.method.KeyListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class MainActivity extends AppCompatActivity {
char[] alphabet = {'a','b','c','d','e','f','g','h','i',
'j','k','l','m','n','o','p','q','r',
's','t','u','v','w','x','y','z'};
int[] imageResources = {
R.drawable.h,
R.drawable.h0,
R.drawable.h1,
R.drawable.h2,
R.drawable.h3,
R.drawable.h4,
R.drawable.h5,
R.drawable.h6,
R.drawable.h7
};
int step = 0;
ImageView iv;
TextView focus, wins, loses,tv,tvGuesses;
String reveal;
private static final String TAG = "MainActivity";
SharedPreferences preferences;
private int winCount;
private int loseCount;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Started");
focus = findViewById(R.id.tvMsg);
wins = findViewById(R.id.tvScoreWins);
loses = findViewById(R.id.tvScoreLoses);
iv = findViewById(R.id.ivHangman);
tv = findViewById(R.id.tvWord);
tvGuesses = findViewById(R.id.tvGuessedLetters);
preferences = this.getSharedPreferences("win",MODE_PRIVATE);
preferences = this.getSharedPreferences("loses",MODE_PRIVATE);
winCount = preferences.getInt("win",0);
wins.setText("Wins = " + winCount);
loseCount = preferences.getInt("loses",0);
loses.setText("Loses = " + loseCount);
DDataSource dataSource = new DDataSource(this);
InputStream myInputStream = null;
Scanner in = null;
String aWord = "";
try {
myInputStream = getAssets().open("database_file.txt");
in = new Scanner(myInputStream);
while(in.hasNext()){
aWord = in.next();
dataSource.addWord(new Word(aWord));
}
} catch (IOException e) {
Toast.makeText(MainActivity.this, e.getClass().getSimpleName() + ": " + e.getMessage(),
Toast.LENGTH_SHORT).show();
} finally {
if(in != null) {
in.close();
}
try {
myInputStream.close();
} catch (IOException e) {
Toast.makeText(MainActivity.this,
e.getClass().getSimpleName() + ": " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
///////////////////////////
//gets a random word
int randomSelector = new Random().nextInt(200);
final String randomWord = dataSource.findItemById((long) randomSelector).getText().toLowerCase();
reveal = randomWord;
Log.i(TAG, "randomWord: " + randomWord);
///// Setting up Game ////////////
//take the random word and replace/represent it with '-' then put on the screen
final char[] filler = new char[randomWord.length()];
int i = 0;
while (i < randomWord.length()) {
filler[i] = '-';
if (randomWord.charAt(i) == ' ') { //to handle spaces in the case of multi words.
filler[i] = ' ';
}
i++;
}
//rebuild a word with the char array and display in on the screen
String outputWord = new String(filler);
tv.setText(outputWord);
final ArrayList<Character> l = new ArrayList<Character>(); //arraylist to hold letters pressed.
ArrayList<Character> guessedLetters = new ArrayList<Character>();
//////////////////////////////////
focus.setKeyListener(new KeyListener() {
@Override
public int getInputType() {
return 0;
}
@Override
public boolean onKeyDown(View view, Editable text, int keyCode, KeyEvent event) {
return false;
}
@Override
public boolean onKeyUp(View view, Editable text, int keyCode, KeyEvent event) {
char letter = Character.toLowerCase((char) event.getUnicodeChar());
if (step < imageResources.length -1 ) {
//compare char to word. handle (if its already pressed, correct or wrong)
if(!l.contains(letter) && contains(letter,alphabet)){
if(randomWord.contains(letter + "")) {
for (int y = 0; y < randomWord.length(); y++) {
if (randomWord.charAt(y) == letter) { // if characters match
filler[y] = letter; // change that index pos value from dash to character guessed.
}
}
String outputWord = new String(filler);
tv.setText(outputWord);
focus.setText("Correct!");
if (randomWord.equals(String.valueOf(filler))){
Toast.makeText(getApplicationContext(), "YOU WIN!", Toast.LENGTH_SHORT).show();
win();
}
}
else{
step++;
focus.setText("Wrong letter, body part added!!!");
}
l.add(letter);
Collections.sort(l);
StringBuilder sb = new StringBuilder();
for(char i:l) {
sb.append(i);
}
tvGuesses.setText(sb.toString());
}else{
focus.setText("Try another letter");
}
int imageResourceId = imageResources[step];
iv.setImageDrawable(ContextCompat.getDrawable(MainActivity.this, imageResourceId));
}
if (step == imageResources.length -1){ //check if there is any more body parts left/guesses remaining, if there is not then do this...
Toast.makeText(getApplicationContext(),"YOU LOSE!",Toast.LENGTH_SHORT).show();
lose();
}
return true;
}
@Override
public boolean onKeyOther(View view, Editable text, KeyEvent event) {
return false;
}
@Override
public void clearMetaKeyState(View view, Editable content, int states) {
}
});
}
void win(){
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
winCount++;
wins.setText("Wins = " + winCount);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("win",winCount); //record loss in the Shared Preferences
editor.commit();
Intent intent = getIntent();
finish();
startActivity(intent);
} //Add 2000ms delay to end of game, (freeze/ignore user input, then close and restart the activity)
}, 2000);
}
void lose(){
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
loseCount++;
loses.setText("Loses = " + loseCount);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("loses",loseCount); //record loss in the Shared Preferences
editor.commit();
Intent intent = getIntent();
finish();
startActivity(intent);
} //Add 2000ms delay to end of game, (freeze/ignore user input, then close and restart the activity)
}, 2000);
}
boolean contains(char c, char[] array) {
for (char x : array) {
if (x == c) {
return true;
}
}
return false;
}
public void onClickReveal (View view) {
focus.setText(reveal);
}
public void onClickResetScore (View view) {
preferences.edit().clear().commit();
winCount = preferences.getInt("win",0);
wins.setText("Wins = " + winCount);
loseCount = preferences.getInt("loses",0);
loses.setText("Loses = " + loseCount);
}
}
| 36.021818
| 159
| 0.529679
|
4363eb2fe6953b2f9a7bcdeb4eecf420bb7778d7
| 1,365
|
/* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.uccollaborationlib.impl;
import com.wilutions.com.*;
@SuppressWarnings("all")
@CoClass(guid="{1E4A4ED6-E300-9A93-0704-DB26E6B2805E}")
public class IModalityActionAvailabilityChangedEventDataImpl extends Dispatch implements com.wilutions.mslib.uccollaborationlib.IModalityActionAvailabilityChangedEventData {
@DeclDISPID(1610743808) public com.wilutions.mslib.uccollaborationlib.ModalityAction getAction() throws ComException {
final Object obj = this._dispatchCall(1610743808,"Action", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return com.wilutions.mslib.uccollaborationlib.ModalityAction.valueOf((Integer)obj);
}
@DeclDISPID(1610743809) public Boolean getIsAvailable() throws ComException {
final Object obj = this._dispatchCall(1610743809,"IsAvailable", DISPATCH_PROPERTYGET,null);
if (obj == null) return null;
return (Boolean)obj;
}
public IModalityActionAvailabilityChangedEventDataImpl(String progId) throws ComException {
super(progId, "{DEDDD7BD-4763-41D2-9AAA-B2C143457CA4}");
}
protected IModalityActionAvailabilityChangedEventDataImpl(long ndisp) {
super(ndisp);
}
public String toString() {
return "[IModalityActionAvailabilityChangedEventDataImpl" + super.toString() + "]";
}
}
| 48.75
| 174
| 0.76337
|
d1c37f591b02d817e71b28093fd7c08cb8148283
| 3,970
|
package squire.Networking;
import squire.Users.Project;
import squire.Users.ProjectFile;
import squire.Users.Session;
import squire.Users.User;
import java.util.ArrayList;
/**
* The request handler dealing with all things Users
*/
@Route("project/")
class ProjectRequestHandler {
@Route("addProject")
static void addProject(Request req, Response res) {
User u = Session.find.activeSession((String) req.get("sessionID")).getUser();
Project p = new Project();
p.setName((String) req.get("name"));
p.setOwner(u);
p.setProjectDescription((String) req.get("description"));
p.save();
u.getWorkingOn().add(p);
u.save();
//create the starting file
ProjectFile mainFile = new ProjectFile("Main.java");
mainFile.setProject(p);
mainFile.save();
res.set("projectUUID", p.getProjectUuid());
}
@Route("addFileToProject")
static void addFileToProject(Request req, Response res) {
Project p = Project.find.where().projectUuid.equalTo((String) req.get("projectUUID")).findUnique();
if (p == null) {
//can't find project
res.setFail();
} else {
ProjectFile f = new ProjectFile((String) req.get("name"));
f.setProject(p);
f.save();
}
}
@Route("getFileName")
static void getFileName(Request req, Response res) {
ProjectFile f = ProjectFile.find.where().id.equalTo((int) req.get("id")).findUnique();
if (f == null) {
res.setFail();
} else {
res.set("name", f.getName());
}
}
@Route("getFilesInProject")
static void getFilesInProject(Request req, Response res) {
Project p = Project.find.where().projectUuid.equalTo((String) req.get("projectUUID")).findUnique();
if (p == null) {
res.setFail();
} else {
ArrayList<String> fileNames = new ArrayList<>();
for(ProjectFile f: p.getFiles()) {
fileNames.add(f.getName());
}
res.set("files", fileNames);
}
}
@Route("getProjectName")
static void getProjectName(Request req, Response res) {
Project p = Project.find.where().projectUuid.equalTo((String) req.get("projectUUID")).findUnique();
if (p == null) {
//can't find project
res.setFail();
}
res.set("name", p.getName());
}
@Route("getProjectList")
static void getProjectList(Request req, Response res) {
ArrayList<ProjectData> projects = new ArrayList<>();
for(Project p: Project.find.all()) {
projects.add(new ProjectData(p.getName(), p.getProjectUuid(), p.getProjectDescription()));
}
res.set("projects", projects);
}
@Route("getUserRecentProjects")
static void getUserRecentProjects(Request req, Response res) {
User u = Session.find.activeSession((String) req.get("sessionID")).getUser();
ArrayList<ProjectData> projects = new ArrayList<>();
for(Project p: u.getWorkingOn()) {
projects.add(new ProjectData(p.getName(), p.getProjectUuid(), p.getProjectDescription()));
}
res.set("projects", projects);
}
@Route("addRecentProject")
static void addRecentProject(Request req, Response res) {
User u = Session.find.activeSession((String) req.get("sessionID")).getUser();
Project p = Project.find.where().projectUuid.equalTo((String) req.get("projectUUID")).findUnique();
for(Project recent: u.getWorkingOn()) {
if(p.getName().equals(recent.getName())) {
//don't add a project if it already exists in the recent projects
return;
}
}
u.getWorkingOn().add(p);
u.save();
}
@Route("getProjectsWithUid")
static void getProjectsWithUid(Request req, Response res) {
}
}
| 33.644068
| 107
| 0.593955
|
80b2cc1052152ba42920fad8a0544d7bb8efc3a2
| 3,317
|
package thredds.catalog2.simpleImpl;
import org.junit.Test;
import static org.junit.Assert.*;
import thredds.catalog2.builder.BuilderIssues;
import thredds.catalog2.builder.ThreddsMetadataBuilder;
import java.util.List;
/**
* _more_
*
* @author edavis
* @since 4.0
*/
public class VariableGroupTest
{
@Test
public void checkVariableGroupSetAndGet()
{
String vocabAuthId = "vocabAuthId";
String vocabAuthUrl = "vocabAuthUrl";
ThreddsMetadataBuilder.VariableGroupBuilder varGrpBldr = new ThreddsMetadataImpl.VariableGroupImpl();
varGrpBldr.setVocabularyAuthorityId( vocabAuthId );
varGrpBldr.setVocabularyAuthorityUrl( vocabAuthUrl );
assertTrue( varGrpBldr.isEmpty());
assertNotNull( varGrpBldr.getVariableBuilders());
assertTrue( varGrpBldr.getVariableBuilders().isEmpty());
String name = "name";
String desc = "descrip";
String units = "unit";
String vocabId = "vocabId";
String vocabName = "vocabName";
varGrpBldr.addVariableBuilder( name, desc, units, vocabId, vocabName );
String name2 = "name2";
String desc2 = "descrip2";
String units2 = "unit2";
String vocabId2 = "vocabId2";
String vocabName2 = "vocabName2";
varGrpBldr.addVariableBuilder( name2, desc2, units2, vocabId2, vocabName2 );
assertEquals( vocabAuthId, varGrpBldr.getVocabularyAuthorityId());
assertEquals( vocabAuthUrl, varGrpBldr.getVocabularyAuthorityUrl());
assertNull( varGrpBldr.getVariableMapUrl());
assertFalse( varGrpBldr.isEmpty());
List<ThreddsMetadataBuilder.VariableBuilder> varBldrs = varGrpBldr.getVariableBuilders();
assertEquals( 2, varBldrs.size());
assertEquals( name, varBldrs.get( 0).getName());
assertEquals( name2, varBldrs.get( 1).getName());
}
@Test
public void checkVariableGroupSetAndGetVarMap()
{
String vocabAuthId = "vocabAuthId";
String vocabAuthUrl = "vocabAuthUrl";
String varMapUrl = "varMapUrl";
ThreddsMetadataBuilder.VariableGroupBuilder varGrpBldr = new ThreddsMetadataImpl.VariableGroupImpl();
varGrpBldr.setVocabularyAuthorityId( vocabAuthId );
varGrpBldr.setVocabularyAuthorityUrl( vocabAuthUrl );
varGrpBldr.setVariableMapUrl( varMapUrl );
assertEquals( vocabAuthId, varGrpBldr.getVocabularyAuthorityId());
assertEquals( vocabAuthUrl, varGrpBldr.getVocabularyAuthorityUrl());
assertEquals( varMapUrl, varGrpBldr.getVariableMapUrl());
assertFalse( varGrpBldr.isEmpty());
assertNotNull( varGrpBldr.getVariableBuilders());
assertTrue( varGrpBldr.getVariableBuilders().isEmpty());
}
@Test
public void checkVariableGroupNoBuildIssuesWithVars()
{
ThreddsMetadataBuilder.VariableGroupBuilder varGrpBldr = new ThreddsMetadataImpl.VariableGroupImpl();
varGrpBldr.addVariableBuilder( "name", "desc", "units", "vocabId", "vocabName" );
BuilderIssues bldrIssues = varGrpBldr.getIssues();
assertTrue( bldrIssues.isEmpty());
}
@Test
public void checkVariableGroupNoBuildIssuesWithVarMap()
{
ThreddsMetadataBuilder.VariableGroupBuilder varGrpBldr = new ThreddsMetadataImpl.VariableGroupImpl();
varGrpBldr.setVariableMapUrl( "varMapUrl" );
BuilderIssues bldrIssues = varGrpBldr.getIssues();
assertTrue( bldrIssues.isEmpty());
assertTrue( bldrIssues.isValid());
}
}
| 32.203883
| 105
| 0.746156
|
f7564b7614aab1d1ebacfa5fae7fcac51a056df3
| 1,757
|
/*
* Copyright © 2016 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package co.cask.cdap.etl.spark.streaming.function;
import co.cask.cdap.api.metrics.Metrics;
import co.cask.cdap.api.preview.DataTracer;
import co.cask.cdap.etl.spark.function.CountingFunction;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.Function;
import javax.annotation.Nullable;
/**
* Function used to emit a metric for every item in an RDD.
*
* @param <T> type of object in the rdd.
*/
public class CountingTranformFunction<T> implements Function<JavaRDD<T>, JavaRDD<T>> {
private final Metrics metrics;
private final String stageName;
private final String metricName;
private final DataTracer dataTracer;
// DataTracer is null for records.in
public CountingTranformFunction(String stageName, Metrics metrics, String metricName,
@Nullable DataTracer dataTracer) {
this.metrics = metrics;
this.stageName = stageName;
this.metricName = metricName;
this.dataTracer = dataTracer;
}
@Override
public JavaRDD<T> call(JavaRDD<T> in) throws Exception {
return in.map(new CountingFunction<T>(stageName, metrics, metricName, dataTracer));
}
}
| 33.788462
| 87
| 0.737052
|
4cfda404c0adf8588badb33bdcd36cccfbb62c3e
| 3,347
|
//The MIT License (MIT)
//
//Copyright (c) 2014 - Mathieu Nayrolles
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package com.concordia.SOEN6461.MVC.model;
import com.concordia.SOEN6461.DAO.AppointmentDAOImpl;
import com.concordia.SOEN6461.beans.appointment.Appointment;
import com.concordia.SOEN6461.beans.human.Patient;
import java.util.List;
/**
* @author Mathieu Nayrolles
*/
public class ManageAppointmentModel implements IModel{
private Patient patient;
private List<Appointment> appointments;
private Appointment selectedAppointment;
/**
*
* @param patient
*/
public void init(Patient patient){
this.patient = patient;
this.appointments = AppointmentDAOImpl.getInstance()
.getAppointmentsByPatient(patient.getSin());
}
/**
*
*/
public void deleteAppointment(){
AppointmentDAOImpl.getInstance().deleteAppointmentByID(selectedAppointment.getId());
this.appointments.remove(selectedAppointment);
this.selectedAppointment = null;
}
/**
*
* @param selectedAppointment
* @return
*/
public boolean setSelectedAppointment(int selectedAppointment){
if(this.appointments.get(selectedAppointment).getStart() >= System.currentTimeMillis()){
this.selectedAppointment = appointments.get(selectedAppointment);
return true;
}
return false;
}
/**
*
* @return
*/
public Patient getPatient() {
return patient;
}
/**
*
* @param patient
*/
public void setPatient(Patient patient) {
this.patient = patient;
}
/**
*
* @return
*/
public List<Appointment> getAppointments() {
return appointments;
}
/**
*
* @param appointments
*/
public void setAppointments(List<Appointment> appointments) {
this.appointments = appointments;
}
/**
*
* @return
*/
public Appointment getSelectedAppointment() {
return selectedAppointment;
}
/**
*
* @param selectedAppointment
*/
public void setSelectedAppointment(Appointment selectedAppointment) {
this.selectedAppointment = selectedAppointment;
}
}
| 27.661157
| 96
| 0.66836
|
29a32102597b75391c225ebafa0da1e3b5ba4ec7
| 3,841
|
/*
* Copyright 2020 Shinya Mochida
*
* Licensed under the Apache License,Version2.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.mikeneck.duration;
import java.util.Objects;
import java.util.function.Function;
import org.jetbrains.annotations.NotNull;
interface Either<@NotNull L, @NotNull R> {
boolean isRight();
default boolean isLeft() {
return !isRight();
}
@NotNull
<@NotNull N> Either<L, N> map(@NotNull Function<@NotNull ? super R, @NotNull ? extends N> mapping);
@NotNull
R orElse(@NotNull Function<@NotNull ? super L, @NotNull ? extends R> mapping);
@NotNull
default R get() {
throw new IllegalStateException("invalid state to call get");
}
@NotNull
default L error() {
throw new IllegalStateException("invalid state to call error");
}
@NotNull
static <@NotNull L, @NotNull R> Either<L, R> left(@NotNull L left) {
return new Left<>(left);
}
@NotNull
static <@NotNull L, @NotNull R> Either<L, R> right(@NotNull R right) {
return new Right<>(right);
}
}
class Left<@NotNull L, @NotNull R> implements Either<L, R> {
@NotNull
private final L value;
Left(@NotNull L value) {
this.value = value;
}
@Override
public boolean isRight() {
return false;
}
@NotNull
@Override
public L error() {
return value;
}
@Override
public <N> @NotNull Either<L, N> map(@NotNull Function<? super R, ? extends N> mapping) {
return new Left<>(value);
}
@Override
public @NotNull R orElse(@NotNull Function<? super L, ? extends R> mapping) {
return mapping.apply(this.value);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Left)) return false;
Left<?, ?> left = (Left<?, ?>) o;
return value.equals(left.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Left{");
sb.append("value=").append(value);
sb.append('}');
return sb.toString();
}
}
class Right<@NotNull L, @NotNull R> implements Either<L, R> {
@NotNull
private final R value;
Right(@NotNull R value) {
this.value = value;
}
@Override
public boolean isRight() {
return true;
}
@NotNull
@Override
public R get() {
return value;
}
@Override
public <N> @NotNull Either<L, N> map(@NotNull Function<? super R, ? extends N> mapping) {
return new Right<>(mapping.apply(this.value));
}
@Override
public @NotNull R orElse(@NotNull Function<? super L, ? extends R> mapping) {
return this.value;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Right)) return false;
Right<?, ?> right = (Right<?, ?>) o;
return value.equals(right.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Right{");
sb.append("value=").append(value);
sb.append('}');
return sb.toString();
}
}
| 24.00625
| 103
| 0.608435
|
8080b2208033e13adb6c707be2555763b5e03444
| 1,434
|
package com.tangxiaolv.simple;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.tangxiaolv.router.AndroidRouter;
import com.tangxiaolv.router.VPromise;
public class LocalActivity extends Activity {
private String tag;
@SuppressWarnings("all")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remote);
Button btn = (Button) findViewById(R.id.btn);
TextView tit = (TextView) findViewById(R.id.tit);
tit.setText("Local");
tag = getIntent().getStringExtra("tag");
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
VPromise promise = AndroidRouter.findPromiseByTag(tag);
assert promise != null;
Toast.makeText(LocalActivity.this, "I'm from local", Toast.LENGTH_SHORT).show();
LocalActivity.this.finish();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
//if AndroidRouter.findPromiseByTag not called.Need remove promise from cache pool.
AndroidRouter.removePromiseByTag(tag);
}
}
| 30.510638
| 96
| 0.671548
|
701db4ae775c72c11fda4faa98455d2c26fd9726
| 2,252
|
/*
* Copyright © 2017 <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jregions.core.parameterized.volumes;
import com.io7m.junreachable.UnreachableCodeException;
import java.math.BigInteger;
import java.util.Objects;
final class PVolumeBIOps
{
public static final BigInteger ZERO = BigInteger.ZERO;
public static final BigInteger ONE = BigInteger.ONE;
private PVolumeBIOps()
{
throw new UnreachableCodeException();
}
public static BigInteger minimum(
final BigInteger a,
final BigInteger b)
{
return a.min(b);
}
public static int compare(
final BigInteger a,
final BigInteger b)
{
return a.compareTo(b);
}
public static BigInteger maximum(
final BigInteger a,
final BigInteger b)
{
return a.max(b);
}
public static BigInteger add(
final BigInteger a,
final BigInteger b)
{
return a.add(b);
}
public static BigInteger subtract(
final BigInteger a,
final BigInteger b)
{
return a.subtract(b);
}
public static BigInteger divide(
final BigInteger a,
final BigInteger b)
{
return a.divide(b);
}
public static BigInteger constant(
final long x)
{
return BigInteger.valueOf(x);
}
public static void notNullVolume(
final Object expression,
final String name)
{
Objects.requireNonNull(expression, name);
}
public static void notNullScalar(
final BigInteger expression,
final String name)
{
Objects.requireNonNull(expression, name);
}
}
| 23.216495
| 78
| 0.713588
|
faa40004a530543db0b37ffd5903c67d8f0b9543
| 2,463
|
package com.utility;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import com.action.AbstractAction;
/**
* The Class CommonFunctions.
*/
public class WebUtils extends AbstractAction implements SessionAware,RequestAware,ServletResponseAware{
/**
* Instantiates a new web utils.
*/
public WebUtils() {
super();
logger.info("WebUtils instantiated..");
}
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The response. */
protected HttpServletResponse response;
/** The session. */
protected Map<String,Object> session;
/** The req. */
protected Map<String,Object> req;
/**
* Gets the req.
*
* @return the req
*/
public Map<String, Object> getReq() {
return req;
}
/**
* Gets the session.
*
* @return the session
*/
public Map<String, Object> getSession() {
return session;
}
/* (non-Javadoc)
* @see org.apache.struts2.interceptor.SessionAware#setSession(java.util.Map)
*/
@Override
public void setSession(Map<String, Object> arg0) {
this.session=arg0;
}
/* (non-Javadoc)
* @see org.apache.struts2.interceptor.RequestAware#setRequest(java.util.Map)
*/
@Override
public void setRequest(Map<String, Object> arg0) {
this.req=arg0;
}
/* (non-Javadoc)
* @see org.apache.struts2.interceptor.ServletResponseAware#setServletResponse(javax.servlet.http.HttpServletResponse)
*/
@Override
public void setServletResponse(HttpServletResponse arg0) {
this.response=arg0;
}
/**
* Gets the response.
*
* @return the response
*/
public HttpServletResponse getResponse() {
return response;
}
/**
* Sets the response.
*
* @param response the new response
*/
public void setResponse(HttpServletResponse response) {
this.response = response;
}
/**
* Gets the cookie value.
*
* @param cookies the cookies
* @param cookieName the cookie name
* @param defaultValue the default value
* @return the cookie value
*/
public static String getCookieValue(Cookie[] cookies,String cookieName,String defaultValue)
{
for(int i=0; i<cookies.length; i++)
{
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
return(cookie.getValue());
}
return(defaultValue);
}
}
| 20.525
| 119
| 0.707268
|
55e63a9150cd95686f1f60ad490dfab8ad854760
| 5,245
|
package com.huaweicloud.sdk.cloudtest.v1;
import com.huaweicloud.sdk.core.HcClient;
import com.huaweicloud.sdk.core.ClientBuilder;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import com.huaweicloud.sdk.cloudtest.v1.model.*;
public class CloudtestAsyncClient {
protected HcClient hcClient;
public CloudtestAsyncClient(HcClient hcClient) {
this.hcClient = hcClient;
}
public static ClientBuilder<CloudtestAsyncClient> newBuilder() {
return new ClientBuilder<>(CloudtestAsyncClient::new);
}
/**
* 项目下创建计划
* 项目下创建计划
*
* @param CreatePlanRequest 请求对象
* @return CompletableFuture<CreatePlanResponse>
*/
public CompletableFuture<CreatePlanResponse> createPlanAsync(CreatePlanRequest request) {
return hcClient.asyncInvokeHttp(request, CloudtestMeta.createPlan);
}
/**
* 计划中批量添加测试用例
* 计划中批量添加测试用例
*
* @param CreateTestCaseInPlanRequest 请求对象
* @return CompletableFuture<CreateTestCaseInPlanResponse>
*/
public CompletableFuture<CreateTestCaseInPlanResponse> createTestCaseInPlanAsync(CreateTestCaseInPlanRequest request) {
return hcClient.asyncInvokeHttp(request, CloudtestMeta.createTestCaseInPlan);
}
/**
* 新测试类型服务注册到云测
* 新测试类型服务注册到云测
*
* @param CreateServiceRequest 请求对象
* @return CompletableFuture<CreateServiceResponse>
*/
public CompletableFuture<CreateServiceResponse> createServiceAsync(CreateServiceRequest request) {
return hcClient.asyncInvokeHttp(request, CloudtestMeta.createService);
}
/**
* 删除已注册服务
* 删除已注册服务
*
* @param DeleteServiceRequest 请求对象
* @return CompletableFuture<DeleteServiceResponse>
*/
public CompletableFuture<DeleteServiceResponse> deleteServiceAsync(DeleteServiceRequest request) {
return hcClient.asyncInvokeHttp(request, CloudtestMeta.deleteService);
}
/**
* 用户获取自己当前已经注册的服务
* 用户获取自己当前已经注册的服务
*
* @param ShowRegisterServiceRequest 请求对象
* @return CompletableFuture<ShowRegisterServiceResponse>
*/
public CompletableFuture<ShowRegisterServiceResponse> showRegisterServiceAsync(ShowRegisterServiceRequest request) {
return hcClient.asyncInvokeHttp(request, CloudtestMeta.showRegisterService);
}
/**
* 更新已注册服务
* 更新已注册服务
*
* @param UpdateServiceRequest 请求对象
* @return CompletableFuture<UpdateServiceResponse>
*/
public CompletableFuture<UpdateServiceResponse> updateServiceAsync(UpdateServiceRequest request) {
return hcClient.asyncInvokeHttp(request, CloudtestMeta.updateService);
}
/**
* 批量删除测试用例
* 批量删除测试用例
*
* @param BatchDeleteTestCaseRequest 请求对象
* @return CompletableFuture<BatchDeleteTestCaseResponse>
*/
public CompletableFuture<BatchDeleteTestCaseResponse> batchDeleteTestCaseAsync(BatchDeleteTestCaseRequest request) {
return hcClient.asyncInvokeHttp(request, CloudtestMeta.batchDeleteTestCase);
}
/**
* 创建测试用例
* 创建测试用例
*
* @param CreateTestCaseRequest 请求对象
* @return CompletableFuture<CreateTestCaseResponse>
*/
public CompletableFuture<CreateTestCaseResponse> createTestCaseAsync(CreateTestCaseRequest request) {
return hcClient.asyncInvokeHttp(request, CloudtestMeta.createTestCase);
}
/**
* 批量执行测试用例
* 批量执行测试用例
*
* @param RunTestCaseRequest 请求对象
* @return CompletableFuture<RunTestCaseResponse>
*/
public CompletableFuture<RunTestCaseResponse> runTestCaseAsync(RunTestCaseRequest request) {
return hcClient.asyncInvokeHttp(request, CloudtestMeta.runTestCase);
}
/**
* 获取测试用例详情
* 获取测试用例详情
*
* @param ShowTestCaseDetailRequest 请求对象
* @return CompletableFuture<ShowTestCaseDetailResponse>
*/
public CompletableFuture<ShowTestCaseDetailResponse> showTestCaseDetailAsync(ShowTestCaseDetailRequest request) {
return hcClient.asyncInvokeHttp(request, CloudtestMeta.showTestCaseDetail);
}
/**
* 通过用例编号或用例ID获取测试用例详情
* 通过用例编号或用例ID获取测试用例详情
*
* @param ShowTestCaseDetailV2Request 请求对象
* @return CompletableFuture<ShowTestCaseDetailV2Response>
*/
public CompletableFuture<ShowTestCaseDetailV2Response> showTestCaseDetailV2Async(ShowTestCaseDetailV2Request request) {
return hcClient.asyncInvokeHttp(request, CloudtestMeta.showTestCaseDetailV2);
}
/**
* 更新测试用例接口
* 更新测试用例接口
*
* @param UpdateTestCaseRequest 请求对象
* @return CompletableFuture<UpdateTestCaseResponse>
*/
public CompletableFuture<UpdateTestCaseResponse> updateTestCaseAsync(UpdateTestCaseRequest request) {
return hcClient.asyncInvokeHttp(request, CloudtestMeta.updateTestCase);
}
/**
* 批量更新测试用例结果
* 批量更新测试用例结果
*
* @param UpdateTestCaseResultRequest 请求对象
* @return CompletableFuture<UpdateTestCaseResultResponse>
*/
public CompletableFuture<UpdateTestCaseResultResponse> updateTestCaseResultAsync(UpdateTestCaseResultRequest request) {
return hcClient.asyncInvokeHttp(request, CloudtestMeta.updateTestCaseResult);
}
}
| 31.787879
| 123
| 0.726787
|
8a9fe8c72c3a68612bd6fd0bf5b170f5b901048b
| 795
|
package de.hpi.isg.mdms.java.fk.feature;
import de.hpi.isg.mdms.java.fk.Dataset;
import de.hpi.isg.mdms.java.fk.Instance;
import java.util.Collection;
/**
* Super class for various feature classes.
* @author Lan Jiang
*/
abstract public class Feature implements FeatureUpdate {
protected String featureName;
/**
* Indicate whether the feature is numeric or nominal.
*/
protected String featureType;
/**
* Indicate the count of distinct value.
*/
protected long distinctCount;
/**
* Indicate the unique value count in this dataset.
*/
protected long uniqueCount;
/**
* Indicate the missing value count.
*/
protected long missingCount;
public String getFeatureName() {
return featureName;
}
}
| 19.875
| 58
| 0.664151
|
47f0353014ab8c5c4cf94f9dc9fe7d4db6c8cb6c
| 928
|
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 3.0.0
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package OpenIGTLink.swig;
public class IGTLheader implements IGTLheaderConstants {
public static void igtl_header_convert_byte_order(igtl_header header) {
IGTLheaderJNI.igtl_header_convert_byte_order(igtl_header.getCPtr(header), header);
}
public static SWIGTYPE_p_unsigned_char PackHeader(igtl_header header, SWIGTYPE_p_unsigned_char body) {
long cPtr = IGTLheaderJNI.PackHeader(igtl_header.getCPtr(header), header, SWIGTYPE_p_unsigned_char.getCPtr(body));
return (cPtr == 0) ? null : new SWIGTYPE_p_unsigned_char(cPtr, false);
}
}
| 42.181818
| 118
| 0.642241
|
33ce1f8a48e16529616176a2e3679d69c1f091d3
| 2,661
|
/*
* Copyright 2017 Hewlett-Packard Development Company, L.P.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.hp.application.automation.tools.octane.tests.gherkin;
import com.hp.application.automation.tools.octane.actions.cucumber.CucumberTestResultsAction;
import com.hp.application.automation.tools.octane.tests.HPRunnerType;
import com.hp.application.automation.tools.octane.tests.MqmTestsExtension;
import com.hp.application.automation.tools.octane.tests.TestProcessingException;
import com.hp.application.automation.tools.octane.tests.TestResultContainer;
import com.hp.application.automation.tools.octane.tests.testResult.TestResult;
import hudson.Extension;
import hudson.model.Run;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.util.List;
@Extension
public class GherkinTestExtention extends MqmTestsExtension {
private static Logger logger = LogManager.getLogger(GherkinTestExtention.class);
@Override
public boolean supports(Run<?, ?> build) throws IOException, InterruptedException {
if (build.getAction(CucumberTestResultsAction.class) != null) {
logger.debug("CucumberTestResultsAction found, gherkin results expected");
return true;
} else {
logger.debug("CucumberTestResultsAction not found, no gherkin results expected");
return false;
}
}
@Override
public TestResultContainer getTestResults(Run<?, ?> build, HPRunnerType hpRunnerType, String jenkinsRootUrl) throws TestProcessingException, IOException, InterruptedException {
try {
List<TestResult> testResults = GherkinTestResultsCollector.collectGherkinTestsResults(build.getRootDir());
return new TestResultContainer(testResults.iterator(), null);
} catch (IOException e) {
throw e;
} catch (InterruptedException e) {
throw e;
} catch (Exception e) {
throw new TestProcessingException("Error while processing gherkin test results", e);
}
}
}
| 42.919355
| 180
| 0.730552
|
46550ba3995bcedee8bc2276d56be83b54d5a593
| 626
|
package com.stylefeng.guns.rest.persistence.dao;
import com.stylefeng.guns.rest.persistence.model.MtimeFieldT;
import com.stylefeng.guns.rest.persistence.model.MtimeHallFilmInfoT;
import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.stylefeng.guns.rest.vo.fields.FilmVo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* <p>
* 影厅电影信息表 Mapper 接口
* </p>
*
* @author wangdi
* @since 2019-10-12
*/
public interface MtimeHallFilmInfoTMapper extends BaseMapper<MtimeHallFilmInfoT> {
//通过影厅得到的电影id查找电影
MtimeHallFilmInfoT selectHallFilmByFilmId(@Param("filmId") Integer filmId);
}
| 24.076923
| 82
| 0.779553
|
2f5e92a1a105744edf988e92a848ea529debe344
| 2,268
|
// Copyright 2000-2021 Nokia
//
// Licensed under the Apache License 2.0
// SPDX-License-Identifier: Apache-2.0
//
package com.alcatel.as.util.sctp;
/**
* The different options to that we can get/set </br>
* Each options returns/takes a different class: </br>
SCTP_STATUS (only get): sctp_status </br>
SCTP_DISABLEFRAGMENTS: sctp_boolean</br>
SCTP_EVENTS: sctp_event_subscribe </br>
SCTP_PEER_ADDR_PARAMS: sctp_paddrparams </br>
SCTP_DELAYED_SACK: sctp_sack_info </br>
SCTP_INITMSG: sctp_initmsg </br>
SCTP_DEFAULT_SEND_PARAM: sctp_sndrcvinfo </br>
SCTP_PRIMARY_ADDR: SocketAddress </br>
SCTP_NODELAY: sctp_boolean</br>
SCTP_RTOINFO: sctp_rtoinfo </br>
SCTP_ASSOCINFO: sctp_assocparams </br>
SCTP_I_WANT_MAPPED_V4_ADDR: sctp_boolean</br>
SCTP_MAXSEG: sctp_assoc_value</br>
SCTP_GET_PEER_ADDR_INFO (only get): sctp_paddrinfo</br>
SCTP_ADAPTATION_LAYER: sctp_setadaptation</br>
SCTP_CONTEXT: sctp_assoc_value</br>
SCTP_FRAGMENT_INTERLEAVE: sctp_boolean</br>
SCTP_PARTIAL_DELIVERY_POINT: Long</br>
SCTP_MAX_BURST: sctp_assoc_value</br>
SCTP_HMAC_IDENT: sctp_hmacalgo</br>
SCTP_AUTH_ACTIVE_KEY: sctp_authkeyid</br>
SCTP_PEER_AUTH_CHUNKS (only get): sctp_authchunks</br>
SCTP_LOCAL_AUTH_CHUNKS (only get): sctp_authchunks</br>
SCTP_AUTH_KEY (only set): sctp_authkey</br>
SCTP_AUTH_DELETE_KEY (only set): sctp_authkeyid</br>
SCTP_AUTH_CHUNK (only set): sctp_authchunk</br>
SCTP_SO_REUSEADDR: sctp_boolean</br>
*/
public enum SctpSocketOption {
SCTP_STATUS,
SCTP_DISABLEFRAGMENTS,
SCTP_EVENTS,
//SCTP_AUTOCLOSE,
SCTP_PEER_ADDR_PARAMS,
SCTP_DELAYED_SACK,
SCTP_INITMSG,
SCTP_DEFAULT_SEND_PARAM,
SCTP_PRIMARY_ADDR,
SCTP_NODELAY,
SCTP_RTOINFO,
SCTP_ASSOCINFO,
SCTP_I_WANT_MAPPED_V4_ADDR,
SCTP_MAXSEG,
SCTP_GET_PEER_ADDR_INFO,
SCTP_ADAPTATION_LAYER,
SCTP_CONTEXT,
SCTP_FRAGMENT_INTERLEAVE,
SCTP_PARTIAL_DELIVERY_POINT,
SCTP_MAX_BURST,
SCTP_HMAC_IDENT,
SCTP_AUTH_ACTIVE_KEY,
SCTP_PEER_AUTH_CHUNKS,
SCTP_LOCAL_AUTH_CHUNKS,
//SCTP_GET_ASSOC_NUMBER,
//SCTP_SET_PEER_PRIMARY_ADDR,
SCTP_AUTH_KEY,
SCTP_AUTH_DELETE_KEY,
SCTP_AUTH_CHUNK,
SCTP_SO_REUSEADDR
}
| 31.5
| 59
| 0.745591
|
d1bf1d391f5a68288e72fd4612d9440f9ba449a0
| 695
|
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
/**
* The purpose of the this class is to provide a method that
* enables you to create an alert in a few of lines
*/
public class CustomAlert {
//Instance Variable Section
private Alert alert;
//Default CustomAlert Constructor
public CustomAlert() {
}
public void Create(AlertType alertType, String title, String headerText,
String contentText)
{
alert = new Alert(alertType);
alert.setTitle(title);
alert.setHeaderText(headerText);
alert.setContentText(contentText);
alert.showAndWait();
}
}
| 26.730769
| 77
| 0.648921
|
c1bb24c8f26253efe1bca120fa33d496b606d284
| 1,671
|
package com.bingoogol.smartbulb.ui.sub;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.bingoogol.smartbulb.App;
import com.bingoogol.smartbulb.R;
import com.bingoogol.smartbulb.util.Constants;
/**
* 提示设置wifi的自定义对话框
*
* @author 王浩 bingoogol@sina.com
*/
public class SetWifiDialog extends Dialog implements OnClickListener {
private Button commitBtn;
private Button exitBtn;
private Activity activity;
public SetWifiDialog(Activity activity) {
super(activity, R.style.DialogTheme);
this.activity = activity;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_set_wifi);
this.setCancelable(false);
this.setCanceledOnTouchOutside(false);
commitBtn = (Button) this.findViewById(R.id.btn_set_wifi_commit);
exitBtn = (Button) this.findViewById(R.id.btn_set_wifi_exit);
commitBtn.setOnClickListener(this);
exitBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_set_wifi_commit:
Intent intent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);
activity.startActivityForResult(intent, Constants.activity.OPEN_WIFI_SETTINGS);
activity.overridePendingTransition(R.anim.translate_in, R.anim.translate_out);
this.dismiss();
break;
case R.id.btn_set_wifi_exit:
this.dismiss();
App app = (App) activity.getApplication();
app.exit();
break;
default:
break;
}
this.dismiss();
}
}
| 26.109375
| 82
| 0.767804
|
164998b211b1ce156dd2609e8e60b2e14a205f06
| 1,893
|
/*
* Copyright 1999-2021 Seata.io Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.seata.samples.api.service.impl;
import java.sql.SQLException;
import io.seata.samples.api.service.AccountService;
import io.seata.samples.api.service.OrderService;
import io.seata.samples.api.utils.DataSourceUtil;
/**
* The type Order service.
*
* @author jimin.jm @alibaba-inc.com
* @date 2019 /08/21
*/
public class OrderServiceImpl implements OrderService {
/**
* The constant DB_KEY.
*/
public static final String DB_KEY = "order";
private AccountService accountService;
@Override
public void setAccountService(AccountService accountService) {
this.accountService = accountService;
}
@Override
public void create(String userId, String commodityCode, Integer count) throws SQLException {
int money = count * 200;
String sql = "insert into order_tbl (user_id, commodity_code, count, money) values ('" + userId + "','"
+ commodityCode + "'," + count + "," + money + ")";
DataSourceUtil.executeUpdate(DB_KEY, sql);
accountService.reduce(userId, money);
}
@Override
public void reset(String key, String value) throws SQLException {
String deleteSql = "delete from order_tbl";
DataSourceUtil.executeUpdate(DB_KEY, deleteSql);
}
}
| 32.084746
| 111
| 0.696778
|
76058b9e963b415b7487d7b9677646c5ae1c957f
| 7,417
|
/*
* Copyright 2020 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.execution.streams;
import io.confluent.ksql.GenericRow;
import io.confluent.ksql.execution.codegen.CodeGenRunner;
import io.confluent.ksql.execution.codegen.ExpressionMetadata;
import io.confluent.ksql.execution.expression.tree.ColumnReferenceExp;
import io.confluent.ksql.execution.expression.tree.Expression;
import io.confluent.ksql.execution.util.ExpressionTypeManager;
import io.confluent.ksql.execution.util.StructKeyUtil;
import io.confluent.ksql.execution.util.StructKeyUtil.KeyBuilder;
import io.confluent.ksql.function.FunctionRegistry;
import io.confluent.ksql.logging.processing.ProcessingLogger;
import io.confluent.ksql.name.ColumnName;
import io.confluent.ksql.schema.ksql.Column;
import io.confluent.ksql.schema.ksql.ColumnNames;
import io.confluent.ksql.schema.ksql.LogicalSchema;
import io.confluent.ksql.schema.ksql.LogicalSchema.Builder;
import io.confluent.ksql.schema.ksql.types.SqlType;
import io.confluent.ksql.util.KsqlConfig;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.streams.KeyValue;
/**
* Factory for PartitionByParams.
*
* <p>Behaviour differs slightly depending on whether PARTITIONing BY a column reference or some
* other expression:
*
* <p>When PARTITIONing BY a column reference the existing key column(s) are moved into the value
* schema and the new key column is moved to the key, e.g. logically {@code A => B, C}, when
* {@code PARTITION BY B}, becomes {@code B => C, A}. However, processing schemas contain a copy of
* the key columns in the value, so actually {@code A => B, C, A} becomes {@code B => B, C, A}:
* Note: the value columns does not need to change.
*
* <p>When PARTITIONing BY any other type of expression no column can be removed from the logical
* schema's value columns. The PARTITION BY expression is creating a <i>new</i> column. Hence, the
* existing key column(s) are moved to the value schema and a <i>new</i> key column is added, e.g.
* logically {@code A => B, C}, when {@code PARTITION BY exp}, becomes {@code KSQL_COL_0 => B, C, A}
* However, processing schemas contain a copy of the key columns in the value, so actually {@code
* A => B, C, A} becomes {@code KSQL_COL_0 => B, C, A, KSQL_COL_0}. Note: the value column only has
* the new key column added.
*/
public final class PartitionByParamsFactory {
private PartitionByParamsFactory() {
}
public static PartitionByParams build(
final LogicalSchema sourceSchema,
final Expression partitionBy,
final KsqlConfig ksqlConfig,
final FunctionRegistry functionRegistry,
final ProcessingLogger logger
) {
final Optional<ColumnName> partitionByCol = getPartitionByColumnName(sourceSchema, partitionBy);
final Function<GenericRow, Object> evaluator = buildExpressionEvaluator(
sourceSchema,
partitionBy,
ksqlConfig,
functionRegistry,
logger
);
final LogicalSchema resultSchema =
buildSchema(sourceSchema, partitionBy, functionRegistry, partitionByCol);
final BiFunction<Object, GenericRow, KeyValue<Struct, GenericRow>> mapper =
buildMapper(resultSchema, partitionByCol, evaluator);
return new PartitionByParams(resultSchema, mapper);
}
public static LogicalSchema buildSchema(
final LogicalSchema sourceSchema,
final Expression partitionBy,
final FunctionRegistry functionRegistry
) {
final Optional<ColumnName> partitionByCol =
getPartitionByColumnName(sourceSchema, partitionBy);
return buildSchema(sourceSchema, partitionBy, functionRegistry, partitionByCol);
}
private static LogicalSchema buildSchema(
final LogicalSchema sourceSchema,
final Expression partitionBy,
final FunctionRegistry functionRegistry,
final Optional<ColumnName> partitionByCol
) {
final ExpressionTypeManager expressionTypeManager =
new ExpressionTypeManager(sourceSchema, functionRegistry);
final SqlType keyType = expressionTypeManager
.getExpressionSqlType(partitionBy);
final ColumnName newKeyName = partitionByCol
.orElseGet(() -> ColumnNames.uniqueAliasFor(partitionBy, sourceSchema));
final Builder builder = LogicalSchema.builder()
.keyColumn(newKeyName, keyType)
.valueColumns(sourceSchema.value());
if (!partitionByCol.isPresent()) {
// New key column added, copy in to value schema:
builder.valueColumn(newKeyName, keyType);
}
return builder.build();
}
private static Optional<ColumnName> getPartitionByColumnName(
final LogicalSchema sourceSchema,
final Expression partitionBy
) {
if (partitionBy instanceof ColumnReferenceExp) {
// PARTITION BY column:
final ColumnName columnName = ((ColumnReferenceExp) partitionBy).getColumnName();
final Column column = sourceSchema
.findValueColumn(columnName)
.orElseThrow(() ->
new IllegalStateException("Unknown partition by column: " + columnName));
return Optional.of(column.name());
}
return Optional.empty();
}
private static BiFunction<Object, GenericRow, KeyValue<Struct, GenericRow>> buildMapper(
final LogicalSchema resultSchema,
final Optional<ColumnName> partitionByCol,
final Function<GenericRow, Object> evaluator
) {
// If partitioning by something other than an existing column, then a new key will have
// been synthesized. This new key must be appended to the value to make it available for
// stream processing, in the same way SourceBuilder appends the key and rowtime to the value:
final boolean appendNewKey = !partitionByCol.isPresent();
final KeyBuilder keyBuilder = StructKeyUtil.keyBuilder(resultSchema);
return (k, v) -> {
final Object newKey = evaluator.apply(v);
final Struct structKey = keyBuilder.build(newKey);
if (appendNewKey) {
v.append(newKey);
}
return new KeyValue<>(structKey, v);
};
}
private static Function<GenericRow, Object> buildExpressionEvaluator(
final LogicalSchema schema,
final Expression partitionBy,
final KsqlConfig ksqlConfig,
final FunctionRegistry functionRegistry,
final ProcessingLogger logger
) {
final CodeGenRunner codeGen = new CodeGenRunner(
schema,
ksqlConfig,
functionRegistry
);
final ExpressionMetadata expressionMetadata = codeGen
.buildCodeGenFromParseTree(partitionBy, "SelectKey");
final String errorMsg = "Error computing new key from expression "
+ expressionMetadata.getExpression();
return row -> expressionMetadata.evaluate(row, null, logger, () -> errorMsg);
}
}
| 38.035897
| 100
| 0.735473
|
030ddd101768d00aedf83abfa02e127abfa81c14
| 485
|
package org.telegram.ui.Components;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.view.View;
public class HideViewAfterAnimation extends AnimatorListenerAdapter {
private final View view;
public HideViewAfterAnimation(View view) {
this.view = view;
}
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
view.setVisibility(View.GONE);
}
}
| 23.095238
| 69
| 0.740206
|
83aef8a140aa9c4aa9c4e3b750521f972471898e
| 1,224
|
package jadx.tests.integration.loops;
import jadx.core.dex.nodes.ClassNode;
import jadx.tests.api.IntegrationTest;
import java.lang.reflect.Method;
import org.junit.Test;
import static jadx.tests.api.utils.JadxMatchers.containsOne;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
public class TestBreakWithLabel extends IntegrationTest {
public static class TestCls {
public boolean test(int[][] arr, int b) {
boolean found = false;
loop0:
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == b) {
found = true;
break loop0;
}
}
}
System.out.println("found: " + found);
return found;
}
}
@Test
public void test() throws Exception {
ClassNode cls = getClassNode(TestCls.class);
String code = cls.getCode().toString();
assertThat(code, containsOne("loop0:"));
assertThat(code, containsOne("break loop0;"));
Method test = getReflectMethod("test", int[][].class, int.class);
int[][] testArray = {{1, 2}, {3, 4}};
assertTrue((Boolean) invoke(test, testArray, 3));
assertFalse((Boolean) invoke(test, testArray, 5));
}
}
| 24.979592
| 67
| 0.676471
|
efc579acd0671e262b1c90a9667d46457754de89
| 1,823
|
package softuni.realestateapp.web.controllers;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import softuni.realestateapp.domain.models.binding.OfferFindBindingModel;
import softuni.realestateapp.domain.models.binding.OfferRegisterBindingModel;
import softuni.realestateapp.domain.models.service.OfferServiceModel;
import softuni.realestateapp.service.OfferService;
@Controller
public class OfferController {
private final OfferService offerService;
private final ModelMapper modelMapper;
public OfferController(OfferService offerService, ModelMapper modelMapper) {
this.offerService = offerService;
this.modelMapper = modelMapper;
}
@GetMapping("/reg")
public String register(){
return "register.html";
}
@PostMapping("/reg")
public String registerConfirm(@ModelAttribute(name = "model") OfferRegisterBindingModel model) {
try {
this.offerService.registerOffer(this.modelMapper.map(model, OfferServiceModel.class));
} catch (IllegalArgumentException e){
e.printStackTrace();
return "redirect:/reg";
}
return "redirect:/";
}
@GetMapping("/find")
public String find(){
return "find.html";
}
@PostMapping("/find")
public String findConfirm(@ModelAttribute(name = "model") OfferFindBindingModel model) {
try {
this.offerService.findOffer(model);
} catch (IllegalArgumentException e){
e.printStackTrace();
return "redirect:/find";
}
return "redirect:/";
}
}
| 28.936508
| 100
| 0.704882
|
25fcbc9154f6fd253ef5c32258129b9121d0abad
| 6,500
|
package cn.yiya.shiji.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import cn.yiya.shiji.R;
import cn.yiya.shiji.adapter.MyRememberUserAdapter;
import cn.yiya.shiji.business.ApiRequest;
import cn.yiya.shiji.business.HttpMessage;
import cn.yiya.shiji.business.MapRequest;
import cn.yiya.shiji.business.MsgCallBack;
import cn.yiya.shiji.business.RetrofitRequest;
import cn.yiya.shiji.config.BaseApplication;
import cn.yiya.shiji.entity.RememberUserItem;
import cn.yiya.shiji.entity.RememberUserObject;
/**
* Created by weixuewu on 15/8/2.
*/
public class DiscoverFriendActivity extends BaseAppCompatActivity implements View.OnClickListener{
private TextView tvTitle;
private ImageView ivBack;
private Handler mHandler;
private RecyclerView mListView;
private SwipeRefreshLayout mSwipeRefreshLayout;
private MyRememberUserAdapter mAdapter;
private boolean isAge;
public boolean followChanged;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_tab);
isAge=false;
mHandler = new Handler(this.getMainLooper());
initViews();
initEvents();
init();
}
@Override
protected void initViews() {
tvTitle= (TextView) this.findViewById(R.id.title_txt);
tvTitle.setText("发现好友");
ivBack= (ImageView) this.findViewById(R.id.title_back);
findViewById(R.id.title_right).setVisibility(View.GONE);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.pulldown);
mListView = (RecyclerView) this.findViewById(R.id.listView);
mListView.setLayoutManager(new LinearLayoutManager(this));
mListView.setItemAnimator(new DefaultItemAnimator());
mAdapter = new MyRememberUserAdapter(this);
mListView.setAdapter(mAdapter);
}
@Override
protected void initEvents() {
ivBack.setOnClickListener(this);
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
loadMoreData(0);
}
});
mAdapter.setOnActionClickListener(new MyRememberUserAdapter.OnActionClickListener() {
@Override
public void onWorkClick(RememberUserItem.Work work) {
Intent intent1 = new Intent(DiscoverFriendActivity.this, NewWorkDetailsActivity.class);
intent1.putExtra("work_id", work.getWork_id());
startActivity(intent1);
}
});
}
@Override
protected void init() {
loadMoreData(0);
}
private void followUser(final RememberUserItem item) {
showPreDialog("");
new RetrofitRequest<>(ApiRequest.getApiShiji().setFollow(String.valueOf(item.getUser_id()))).handRequest(new MsgCallBack() {
@Override
public void onResult(HttpMessage msg) {
hidePreDialog();
if (msg.isSuccess()) {
item.setIs_follow(true);
mAdapter.notifyDataSetChanged();
} else {
showTips(msg.message);
}
}
});
}
/**
* 加载更多
*/
private void loadMoreData(final int offset){
if(isAge){
new RetrofitRequest<RememberUserObject>(ApiRequest.getApiShiji().getRecFriends(MapRequest.setUserIdMap(
BaseApplication.getInstance().readUserId(), offset))).handRequest(new MsgCallBack() {
@Override
public void onResult(HttpMessage msg) {
if (msg.isSuccess()) {
RememberUserObject obj = (RememberUserObject) msg.obj;
if (obj.list != null && obj.list.size() > 0) {
if (offset > 0) {
mAdapter.getList().addAll(obj.list);
} else {
mAdapter.setList(obj.list);
}
mAdapter.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
}
} else {
showTips(msg.message);
}
}
});
}else{
new RetrofitRequest<RememberUserObject>(ApiRequest.getApiShiji().getUserFriends(MapRequest.setMapTen(offset))).
handRequest(new MsgCallBack() {
@Override
public void onResult(HttpMessage msg) {
if(msg.isSuccess()){
RememberUserObject obj = (RememberUserObject)msg.obj;
if(obj.list != null && obj.list.size() > 0){
if(offset > 0){
mAdapter.getList().addAll(obj.list);
}else{
mAdapter.setList(obj.list);
}
mAdapter.notifyDataSetChanged();
mSwipeRefreshLayout.setRefreshing(false);
}
}else{
showTips(msg.message);
}
}
}
);
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.title_back:
setResult(RESULT_OK);
finish();
break;
}
}
@Override
public void onBackPressed() {
Intent intent = new Intent();
intent.putExtra("followChanged", followChanged);
setResult(RESULT_OK, intent);
finish();
}
}
| 36.931818
| 133
| 0.545846
|
ec970c16c5cf8824fa93aeb4becbcce90267cccf
| 1,816
|
/*
* Copyright (C) 2011-2016 Rinde van Lon, iMinds-DistriNet, KU Leuven
*
* 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.github.rinde.rinsim.core.model.time;
import com.google.auto.value.AutoValue;
/**
* A timestamp marks the end of one {@link TimeLapse} and the start of another.
* @author Rinde van Lon
*/
@AutoValue
public abstract class Timestamp {
Timestamp() {}
/**
* The tick count. If tick count is <code>n</code> it means that this is the
* n-th {@link TimeLapse} in the current real-time period of the
* {@link RealtimeClockController}. Each time a new real-time period is
* started the counter is reset to <code>0</code>.
* @return The tick count, <code>≥ 0</code>
*/
public abstract long getTickCount();
/**
* @return The value of {@link System#currentTimeMillis()} at the start of the
* tick.
*/
public abstract long getMillis();
/**
* @return The value of {@link System#nanoTime()} at the start of the tick.
*/
public abstract long getNanos();
static Timestamp now(long tickCount) {
return create(tickCount, System.currentTimeMillis(), System.nanoTime());
}
static Timestamp create(long tickCount, long millis, long nanos) {
return new AutoValue_Timestamp(tickCount, millis, nanos);
}
}
| 31.859649
| 80
| 0.69989
|
9cb6b8e3fcb8163a47d23d4497d799670cf136c6
| 5,875
|
/*
* Copyright 2018. Gatekeeper Contributors
*
* 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.finra.gatekeeper.services.accessrequest.delegates;
import com.amazonaws.services.rds.model.DBCluster;
import org.activiti.engine.ManagementService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.runtime.Job;
import org.finra.gatekeeper.common.services.eventlogging.EventType;
import org.finra.gatekeeper.common.services.eventlogging.RequestEventLogger;
import org.finra.gatekeeper.rds.model.RoleType;
import org.finra.gatekeeper.services.accessrequest.AccessRequestService;
import org.finra.gatekeeper.services.accessrequest.model.AWSRdsDatabase;
import org.finra.gatekeeper.services.accessrequest.model.AccessRequest;
import org.finra.gatekeeper.services.accessrequest.model.User;
import org.finra.gatekeeper.services.accessrequest.model.UserRole;
import org.finra.gatekeeper.services.aws.RdsLookupService;
import org.finra.gatekeeper.services.aws.model.AWSEnvironment;
import org.finra.gatekeeper.services.aws.model.DatabaseType;
import org.finra.gatekeeper.services.db.DatabaseConnectionService;
import org.finra.gatekeeper.services.email.wrappers.EmailServiceWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* The Service task to grant access using the details from an AccessRequest
*/
@Component
public class RevokeAccessServiceTask implements JavaDelegate {
private static final Logger logger = LoggerFactory.getLogger(RevokeAccessServiceTask.class);
private final EmailServiceWrapper emailServiceWrapper;
private final DatabaseConnectionService databaseConnectionService;
private final RdsLookupService rdsLookupService;
private final ManagementService managementService;
private final AccessRequestService accessRequestService;
@Autowired
public RevokeAccessServiceTask(EmailServiceWrapper emailServiceWrapper,
DatabaseConnectionService databaseConnectionService,
ManagementService managementService,
RdsLookupService rdsLookupService,
AccessRequestService accessRequestService) {
this.emailServiceWrapper = emailServiceWrapper;
this.databaseConnectionService = databaseConnectionService;
this.managementService = managementService;
this.rdsLookupService = rdsLookupService;
this.accessRequestService = accessRequestService;
}
/***
* @param execution - the request to execute on
* @throws Exception - if the revocation fails
*/
public void execute(DelegateExecution execution) throws Exception{
Job job = managementService.createJobQuery().processInstanceId(execution.getProcessInstanceId()).singleResult();
AccessRequest accessRequest = (AccessRequest)execution.getVariable("accessRequest");
try {
AWSEnvironment awsEnvironment = new AWSEnvironment(accessRequest.getAccount(), accessRequest.getRegion(), accessRequest.getAccountSdlc());
logger.info("Revoking access for Users, Attempts remaining: " + job.getRetries());
for(User user : accessRequest.getUsers()) {
AWSRdsDatabase database = accessRequest.getAwsRdsInstances().get(0);
for (UserRole role : accessRequest.getRoles()) {
if (accessRequestService.getLiveRequestsForUserOnDatabase(user.getUserId(), accessRequest.getAccount(), database.getName(), role).isEmpty()) {
// if the db was actually an aurora global cluster then we should re-fetch the primary cluster
// as that could have changed
if (database.getDatabaseType() != null && database.getDatabaseType() == DatabaseType.AURORA_GLOBAL) {
logger.info("Re-fetching the Primary Cluster for this global cluster since it could have changed over time.");
DBCluster primaryCluster = rdsLookupService.getPrimaryClusterForGlobalCluster(awsEnvironment, database.getName()).get();
database.setEndpoint(String.format("%s:%s", primaryCluster.getEndpoint(), primaryCluster.getPort()));
}
databaseConnectionService.revokeAccess(database, awsEnvironment, RoleType.valueOf(role.getRole().toUpperCase()), user.getUserId());
} else {
logger.info("Skipping revocation of user " + user.getUserId() + " with role " + role.toString() + " as they have another active access request for this instance.");
}
}
}
RequestEventLogger.logEventToJson(EventType.AccessExpired, accessRequest);
}catch(Exception e){
if(job.getRetries() - 1 == 0){
logger.error("Maximum attempt limit reached. Notify Ops team for manual removal");
emailServiceWrapper.notifyOps(accessRequest);
emailServiceWrapper.notifyAdminsOfFailure(accessRequest,e);
}else{
throw e;
}
}
}
}
| 53.409091
| 188
| 0.711319
|
07fda4984d66187a3459b8f4171a743b65ba02ed
| 874
|
package net.sf.jmoney.model;
/**
* An implementation of the Category interface
*/
public class SimpleCategory extends AbstractCategory {
private String categoryName;
private String fullCategoryName = null;
public SimpleCategory() {
}
public SimpleCategory(String aCategoryName) {
setCategoryName(aCategoryName);
}
public String getCategoryName() {
return categoryName;
}
public String getFullCategoryName() {
if (fullCategoryName == null) {
Object[] path = getCategoryNode().getUserObjectPath();
if (path.length > 1) {
fullCategoryName = path[1].toString();
for (int i = 2; i < path.length; i++)
fullCategoryName += ":" + path[i];
} else
fullCategoryName = categoryName;
}
return fullCategoryName;
}
public void setCategoryName(String aCategoryName) {
categoryName = aCategoryName;
fullCategoryName = null;
}
}
| 20.809524
| 57
| 0.709382
|
73f41bb1dda105526e7deb1c0bc2f5cfc46d4e7e
| 4,660
|
package com.ysyx.commons.wx.requests.stat.respbeans;
import org.codehaus.jackson.annotate.JsonProperty;
import java.util.List;
/**
* statisic data of article total.
*
* @author duanbn
*
*/
public class ArticleTotal {
@JsonProperty("list")
private List<Article> list;
/**
*
* @return
*/
public List<Article> getList() {
return list;
}
/**
*
* @param list
*/
public void setList(final List<Article> list) {
this.list = list;
}
/**
*
* @author duanbn
*
*/
public static class Article {
@JsonProperty("ref_date")
private String refDate;
@JsonProperty("msgid")
private String msgId;
@JsonProperty("title")
private String title;
@JsonProperty("details")
private List<Summary> details;
/**
*
* @return
*/
public String getRefDate() {
return refDate;
}
/**
*
* @param refDate
*/
public void setRefDate(final String refDate) {
this.refDate = refDate;
}
/**
*
* @return
*/
public String getMsgId() {
return msgId;
}
/**
*
* @param msgId
*/
public void setMsgId(final String msgId) {
this.msgId = msgId;
}
/**
*
* @return
*/
public String getTitle() {
return title;
}
/**
*
* @param title
*/
public void setTitle(final String title) {
this.title = title;
}
/**
*
* @return
*/
public List<Summary> getDetails() {
return details;
}
/**
*
* @param details
*/
public void setDetails(final List<Summary> details) {
this.details = details;
}
}
/**
*
* @author duanbn
*
*/
public static class Summary {
@JsonProperty("stat_date")
private String statDate;
@JsonProperty("target_user")
private int targetUser;
@JsonProperty("int_page_read_user")
private int intPageReadUser;
@JsonProperty("int_page_read_count")
private int intPageReadCount;
@JsonProperty("ori_page_read_user")
private int oriPageReadUser;
@JsonProperty("ori_page_read_count")
private int oriPageReadCount;
@JsonProperty("share_user")
private int shareUser;
@JsonProperty("share_count")
private int shareCount;
@JsonProperty("add_to_fav_user")
private int addToFavUser;
@JsonProperty("add_to_fav_count")
private int addToFavCount;
/**
*
* @return
*/
public String getStatDate() {
return statDate;
}
/**
*
* @param statDate
*/
public void setStatDate(final String statDate) {
this.statDate = statDate;
}
/**
*
* @return
*/
public int getTargetUser() {
return targetUser;
}
/**
*
* @param targetUser
*/
public void setTargetUser(final int targetUser) {
this.targetUser = targetUser;
}
/**
*
* @return
*/
public int getIntPageReadUser() {
return intPageReadUser;
}
/**
*
* @param intPageReadUser
*/
public void setIntPageReadUser(final int intPageReadUser) {
this.intPageReadUser = intPageReadUser;
}
/**
*
* @return
*/
public int getIntPageReadCount() {
return intPageReadCount;
}
/**
*
* @param intPageReadCount
*/
public void setIntPageReadCount(final int intPageReadCount) {
this.intPageReadCount = intPageReadCount;
}
/**
*
* @return
*/
public int getOriPageReadUser() {
return oriPageReadUser;
}
/**
*
* @param oriPageReadUser
*/
public void setOriPageReadUser(final int oriPageReadUser) {
this.oriPageReadUser = oriPageReadUser;
}
/**
*
* @return
*/
public int getOriPageReadCount() {
return oriPageReadCount;
}
/**
*
* @param oriPageReadCount
*/
public void setOriPageReadCount(final int oriPageReadCount) {
this.oriPageReadCount = oriPageReadCount;
}
/**
*
* @return
*/
public int getShareUser() {
return shareUser;
}
/**
*
* @param shareUser
*/
public void setShareUser(final int shareUser) {
this.shareUser = shareUser;
}
/**
*
* @return
*/
public int getShareCount() {
return shareCount;
}
/**
*
* @param shareCount
*/
public void setShareCount(final int shareCount) {
this.shareCount = shareCount;
}
/**
*
* @return
*/
public int getAddToFavUser() {
return addToFavUser;
}
/**
*
* @param addToFavUser
*/
public void setAddToFavUser(final int addToFavUser) {
this.addToFavUser = addToFavUser;
}
/**
*
* @return
*/
public int getAddToFavCount() {
return addToFavCount;
}
/**
*
* @param addToFavCount
*/
public void setAddToFavCount(final int addToFavCount) {
this.addToFavCount = addToFavCount;
}
}
}
| 14.793651
| 63
| 0.612446
|
9b01a078d31367a7528f5dee9b89a5a587b9825f
| 2,541
|
/*
* 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.axiom.util.xml;
/**
* Contains utility methods to work with XML namespaces.
*/
public final class NSUtils {
private static final char[] prefixChars = new char[62];
static {
for (int i = 0; i < 10; i++) {
prefixChars[i] = (char)('0' + i);
}
for (int i = 0; i < 26; i++) {
prefixChars[i+10] = (char)('a' + i);
}
for (int i = 0; i < 26; i++) {
prefixChars[i+36] = (char)('A' + i);
}
}
private NSUtils() {}
/**
* Generate a namespace prefix for the given namespace URI. The generated prefix is based on a
* hash of the namespace URI. This implies that a given namespace URI is always mapped to the
* same prefix and that there is no guarantee that the generated prefixes are unique. However,
* the likelihood of a (accidental) collisions is very small.
* <p>
* Using hash based prefixes has the advantage of reducing the number of entries created in the
* symbol table of the parser on the receiving side, assuming that the symbol table is reused to
* parse multiple documents (which is a common optimization).
*
* @param namespaceURI
* the namespace URI to generate a prefix for; must not be {@code null}
* @return the generated prefix
*/
public static String generatePrefix(String namespaceURI) {
char[] prefix = new char[7];
prefix[0] = 'n';
prefix[1] = 's';
int hash = namespaceURI.hashCode() & 0x7FFFFFFF;
for (int i = prefix.length-1; i >= 2; i--) {
prefix[i] = prefixChars[hash % 62];
hash /= 62;
}
return new String(prefix);
}
}
| 37.925373
| 100
| 0.637151
|
2ecb8f1f667151644d43c0ef45c6bd3bbd805752
| 8,555
|
/*
* Copyright (c) 2017 Antony Esik
*
* 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.ae.camunda.dispatcher.runtime.test;
import com.ae.camunda.dispatcher.api.annotation.CamundaVar;
import com.ae.camunda.dispatcher.api.manager.ExternalTaskManager;
import com.ae.camunda.dispatcher.model.EntityMetadata;
import com.ae.camunda.dispatcher.runtime.manager.ExternalTaskManagerImpl;
import com.ae.camunda.dispatcher.runtime.test.command.Command;
import com.ae.camunda.dispatcher.runtime.test.command.WrongCommand;
import com.ae.camunda.dispatcher.util.JavaUtils;
import com.google.common.reflect.ClassPath;
import io.github.benas.randombeans.api.EnhancedRandom;
import org.apache.commons.lang3.tuple.Pair;
import org.camunda.bpm.engine.rest.dto.VariableValueDto;
import org.camunda.bpm.engine.rest.dto.externaltask.CompleteExternalTaskDto;
import org.camunda.bpm.engine.rest.dto.externaltask.ExternalTaskFailureDto;
import org.camunda.bpm.engine.rest.dto.externaltask.FetchExternalTasksDto;
import org.camunda.bpm.engine.rest.dto.externaltask.LockedExternalTaskDto;
import org.camunda.bpm.engine.variable.impl.value.PrimitiveTypeValueImpl;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.function.Consumer;
@RunWith(MockitoJUnitRunner.class)
public class ExternalTaskManagerImplTest {
private ExternalTaskManagerImpl manager;
@Before
public void init() {
manager = new ExternalTaskManagerImpl();
JavaUtils.setFieldWithoutCheckedException(
ReflectionUtils.findField(ExternalTaskManagerImpl.class, "packages")
, manager
, Arrays.asList(Command.class.getPackage().getName())
);
}
@Test
public void testInit() {
manager.init();
Assert.assertEquals(18, manager.getExternalTaskFieldAnnotations().size());
Assert.assertEquals(1, manager.getExternalTaskDefinitions().size());
{
EntityMetadata<?> task = manager.getExternalTaskDefinitions().get(Command.TASK_NAME);
Assert.assertNotNull(task);
Assert.assertEquals(Command.TASK_NAME, task.getName());
Assert.assertEquals(20, task.getFields().size());
testFields((key) -> Assert.assertNotNull(task.getFields().get(key)));
}
{
EntityMetadata<?> task = manager.getExternalTaskDefinitions().get(WrongCommand.TASK_NAME);
Assert.assertNull(task);
}
}
@Test
public void testGetExternalTaskTopics() {
Assert.assertTrue(manager.getExternalTaskTopics(1).isEmpty());
manager.init();
long lockTimeuot = 1;
List<FetchExternalTasksDto.FetchExternalTaskTopicDto> topics = manager.getExternalTaskTopics(lockTimeuot);
Assert.assertFalse(topics.isEmpty());
FetchExternalTasksDto.FetchExternalTaskTopicDto topic = topics.get(0);
Assert.assertNotNull(topic);
Assert.assertEquals(lockTimeuot, topic.getLockDuration());
Assert.assertEquals(Command.TASK_NAME, topic.getTopicName());
Assert.assertNotNull(topic.getVariables());
Assert.assertEquals(20, topic.getVariables().size());
testFields((key) -> Assert.assertTrue(topic.getVariables().contains(key)));
}
@Test(expected = NoSuchElementException.class)
public void testToCommandFail() {
manager.toCommand(new LockedExternalTaskDto());
}
@Test
public void testToCommand() {
manager.init();
LockedExternalTaskDto task = EnhancedRandom.random(LockedExternalTaskDto.class);
JavaUtils.setFieldWithoutCheckedException(
ReflectionUtils.findField(LockedExternalTaskDto.class, "topicName")
, task
, Command.TASK_NAME
);
String stringVar = "value";
String otherVar = "other value";
task.getVariables().put("stringVar", VariableValueDto.fromTypedValue(new PrimitiveTypeValueImpl.StringValueImpl(stringVar)));
task.getVariables().put("otherVar", VariableValueDto.fromTypedValue(new PrimitiveTypeValueImpl.StringValueImpl(otherVar)));
Object object = manager.toCommand(task);
Assert.assertNotNull(object);
Assert.assertTrue(object instanceof Command);
Command command = (Command) object;
Assert.assertEquals(stringVar, command.getStringVar());
Assert.assertEquals(otherVar, command.getAnotherStringVar());
ReflectionUtils.doWithFields(LockedExternalTaskDto.class, field -> {
if (field.getName().equals("variables")) {
return;
}
Field commandField = ReflectionUtils.findField(Command.class, field.getName());
Assert.assertNotNull("No field with name: " + field.getName(), commandField);
Assert.assertEquals(
JavaUtils.getFieldWithoutCheckedException(field, task)
, JavaUtils.getFieldWithoutCheckedException(commandField, command)
);
});
}
@Test
public void testToCompleteTask() {
manager.init();
Pair<String, CompleteExternalTaskDto> pair = manager.toCompleteTask(null, new Object());
Assert.assertNull(pair);
pair = manager.toCompleteTask(Command.TASK_NAME, null);
Assert.assertNull(pair);
Command command = EnhancedRandom.random(Command.class);
pair = manager.toCompleteTask(Command.TASK_NAME, command);
Assert.assertNotNull(pair);
Assert.assertNotNull(pair.getKey());
Assert.assertEquals(command.getId(), pair.getKey());
Assert.assertNotNull(pair.getValue());
Assert.assertEquals(command.getWorkerId(), pair.getValue().getWorkerId());
Assert.assertNotNull(pair.getValue().getVariables());
Assert.assertFalse(pair.getValue().getVariables().isEmpty());
final Pair<String, CompleteExternalTaskDto> finalPair = pair;
ReflectionUtils.doWithFields(Command.class, field -> {
CamundaVar camundaVar = field.getAnnotation(CamundaVar.class);
if (camundaVar == null) {
return;
}
Assert.assertTrue(finalPair.getValue().getVariables().containsKey(ExternalTaskManager.getVarName(field, camundaVar)));
});
}
@Test
public void testToFailTask() {
manager.init();
Pair<String, ExternalTaskFailureDto> pair = manager.toFailTask(null, new Object());
Assert.assertNull(pair);
pair = manager.toFailTask(Command.TASK_NAME, null);
Assert.assertNull(pair);
Command command = EnhancedRandom.random(Command.class);
pair = manager.toFailTask(Command.TASK_NAME, command);
Assert.assertNotNull(pair);
Assert.assertNotNull(pair.getKey());
Assert.assertEquals(command.getId(), pair.getKey());
Assert.assertNotNull(pair.getValue());
Assert.assertEquals(command.getWorkerId(), pair.getValue().getWorkerId());
Assert.assertEquals(command.getErrorMessage(), pair.getValue().getErrorMessage());
Assert.assertEquals(command.getRetries().intValue(), pair.getValue().getRetries());
Assert.assertEquals(command.getRetryTimeout(), pair.getValue().getRetryTimeout());
}
private static void testFields(Consumer<String> consumer) {
JavaUtils.callWithoutCheckedException(() -> {
ClassPath.from(ExternalTaskManagerImpl.class.getClassLoader())
.getTopLevelClassesRecursive("com.ae.bpm.dispatcher.api.annotation.task")
.forEach(classInfo -> consumer.accept(StringUtils.uncapitalize(classInfo.getSimpleName())));
return null;
});
}
}
| 39.243119
| 133
| 0.696435
|
5c12ee77ea94968a0dcb6d035e6910d6067ef985
| 2,609
|
package com.langworthytech.simplebillingsystem.account.dto;
import javax.persistence.Column;
public class AccountViewResponse {
private Long id;
private String company;
private String address;
private String city;
private String state;
private String zip;
private String phone;
private String email;
private String website;
public AccountViewResponse() {}
public AccountViewResponse(
Long id,
String company,
String address,
String city,
String state,
String zip,
String phone,
String email,
String website
) {
this.id = id;
this.company = company;
this.address = address;
this.city = city;
this.state = state;
this.zip = zip;
this.phone = phone;
this.email = email;
this.website = website;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
@Override
public String toString() {
return "AccountViewResponse{" +
"id=" + id +
", company='" + company + '\'' +
", address='" + address + '\'' +
", city='" + city + '\'' +
", state='" + state + '\'' +
", zip='" + zip + '\'' +
", phone='" + phone + '\'' +
", email='" + email + '\'' +
", website='" + website + '\'' +
'}';
}
}
| 19.183824
| 59
| 0.517056
|
fedd39bda1b46de93b2f732916fc889725a555c4
| 1,539
|
package gov.nara.nwts.ftappImg.stats;
import gov.nara.nwts.ftapp.stats.Stats;
import gov.nara.nwts.ftappImg.tags.ImageTags.TAGS;
import gov.nara.nwts.ftappImg.tags.ImageTags.TAGLOC;
import gov.nara.nwts.ftappImg.tags.ImageTags.TAGTYPE;
import gov.nara.nwts.ftappImg.tags.ImageTags.NARAREQ;
import gov.nara.nwts.ftappImg.tags.ImageTags.TAGCONTENT;
import gov.nara.nwts.ftappImg.tags.ImageTags.DUP;
/**
* Stats object to report on metadata coming from either a TIF or a JPG using tag definitions
* @author TBrady
*
*/
public class GenericImageStats extends Stats {
public static Object[][] details = {
{String.class,"Key",60, null, false},
{String.class,"File",150},
{String.class,"Name",150, TAGS.values()},
{String.class,"Path",200},
{String.class,"Value",200},
{TAGTYPE.class,"Type",100,TAGTYPE.values()},
{TAGCONTENT.class,"Content",100,TAGCONTENT.values()},
{DUP.class,"Dup Info",100,DUP.values()},
{TAGLOC.class,"Loc",50,TAGLOC.values()},
{NARAREQ.class,"Nara Use",120,NARAREQ.values()},
};
public GenericImageStats(String key) {
this(key,"","","","",TAGLOC.NA,TAGTYPE.TIFF_TAG,NARAREQ.UNDECIDED,TAGCONTENT.UNDECIDED, DUP.NA);
}
public GenericImageStats(String key, String file, String name, String path, String value, TAGLOC tiffloc, TAGTYPE tagtype, NARAREQ narareq, TAGCONTENT tagcontent, DUP dup) {
super(key);
vals.add(file);
vals.add(name);
vals.add(path);
vals.add(value);
vals.add(tagtype);
vals.add(tagcontent);
vals.add(dup);
vals.add(tiffloc);
vals.add(narareq);
}
}
| 32.0625
| 174
| 0.723847
|
dfcaa1117cccfafa6a87c2b57c180959e8964244
| 1,128
|
public class CeaserCipher {
private String text;
private int key;
public CeaserCipher(String text, int key) {
this.text = text;
this.key = key;
}
public String getText() {
return text;
}
public int getKey() {
return key;
}
public static String encrypt(String text, int key){
String encryptedText = "";
if(key>26){
System.err.println("Uknown key! ");
} else if(key <=26){
int textLength = text.length();
for (int i=0; i<textLength; i++){
char index = text.charAt(i);
if (Character.isLetter(index)){
char encryptedChar = (char)(index + key);
if (encryptedChar > 'z'){
encryptedText += (char)(index - (26 - key));
} else {
encryptedText += encryptedChar;
}
}
}
}
return encryptedText;
}
public static String decrypt(String text){
String decryptedText = text;
return decryptedText;
}
}
| 22.117647
| 66
| 0.487589
|
02003e24a2a9e12ee9bd6b82dea9078f4830f492
| 794
|
package gov.nasa.pds.common;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.springframework.beans.factory.config.ListFactoryBean;
import org.springframework.core.io.Resource;
public class ResourceListFactoryBean extends ListFactoryBean {
public ResourceListFactoryBean() {
super();
}
public void setResource(Resource resource) throws IOException {
Scanner scanner = new Scanner(resource.getInputStream());
try {
List<String> source = new ArrayList<String>();
while (scanner.hasNextLine()) {
source.add(scanner.nextLine());
}
super.setSourceList(source);
} finally {
scanner.close();
}
}
}
| 27.37931
| 67
| 0.654912
|
3a994661e8fa610e5b0867c1da5bde1e1864caee
| 2,595
|
package com.example.mongodb.demo.controller;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.springframework.web.bind.annotation.GetMapping;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.mongodb.demo.model.Employee;
import com.example.mongodb.demo.repository.EmployeeRepoImpl;
import com.example.mongodb.demo.repository.EmployeeRepository;
@RestController
@RequestMapping(value = "employee")
public class EmployeeController {
private final EmployeeRepository emprepo;
private final EmployeeRepoImpl emprepoimpl;
public EmployeeController(EmployeeRepository emprep,EmployeeRepoImpl emprepoimp) {
super();
this.emprepo = emprep;
this.emprepoimpl = emprepoimp;
}
@GetMapping("/show")
public List<Employee> getAllBooks()
{
return Arrays.asList(new Employee("Testing employee","Hello There,Welcome to Microservices demo!!!","Sivaram",26));
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public Employee addEmployee(@RequestBody Employee employee) {
System.out.println("Added New Employee"+employee.getName());
return emprepo.insert(employee);
}
@RequestMapping(value = "/update/{empId}", method = RequestMethod.PUT)
public void updateEmployee(@RequestBody Employee employee,@PathVariable String empId) {
Employee employee1 = emprepoimpl.findOne(empId);
if(employee1 !=null)
{
System.out.println("updating employee details ... "+employee1.getName());
employee1.setId(empId);
employee1.setDept(employee.getDept());
employee1.setName(employee.getName());
System.out.println("Updated Employee "+employee.getName());
emprepo.save(employee1);
}
else
{
System.out.println("Created New Employee "+employee.getName());
emprepo.insert(employee);
}
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public List<Employee> getAllEmployees() {
return emprepo.findAll();
}
@RequestMapping(value = "/getDetails/{empId}", method = RequestMethod.GET)
public Optional<Employee> searchEmployeeById(@PathVariable String empId) {
return emprepo.findById(empId);
}
@RequestMapping(value = "/remove/{empId}", method = RequestMethod.GET)
public String removeEmployeeById(@PathVariable String empId) {
emprepo.deleteById(empId);
return "Employee removed";
}
}
| 30.529412
| 117
| 0.764547
|
8da19f4d8e579a2417f860a1bda02d31d8ad665c
| 2,349
|
package org.finos.springbot.teams.templating;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import org.finos.springbot.workflow.templating.AbstractComplexTypeConverter;
import org.finos.springbot.workflow.templating.Rendering;
import org.finos.springbot.workflow.templating.TypeConverter;
import org.finos.springbot.workflow.templating.Variable;
import org.finos.springbot.workflow.templating.WithField;
import org.finos.springbot.workflow.templating.WithType;
import com.fasterxml.jackson.databind.JsonNode;
public class CollectionConverter extends AbstractComplexTypeConverter<JsonNode> {
public CollectionConverter(Rendering<JsonNode> r) {
super(LOW_PRIORITY, r);
}
@Override
public boolean canConvert(Field ctx, Type t) {
if (t instanceof ParameterizedType) {
Type rawType = ((ParameterizedType)t).getRawType();
return (rawType instanceof Class<?>) && Collection.class.isAssignableFrom((Class<?>) rawType);
} else {
return false;
}
}
@Override
public JsonNode apply(Field ctx, WithType<JsonNode> controller, Type t, boolean editMode, Variable variable, WithField<JsonNode> showDetail) {
if (null == showDetail) {
return r.description("...");
} else if (showDetail.expand()) {
Class<?> elementClass = (Class<?>) ((ParameterizedType) t).getActualTypeArguments()[0];
TypeConverter<JsonNode> elementTypeConverter = controller.getConverter(null, elementClass, controller);
Variable child = variable.index();
JsonNode propertyPanel = elementTypeConverter.apply(null, controller, elementClass, false, child, collectionValues());
return r.collection(elementClass, variable, propertyPanel, editMode);
} else {
return r.textField(variable, false);
}
}
protected WithField<JsonNode> collectionValues() {
return new WithField<JsonNode>() {
@Override
public boolean expand() {
return true;
}
@Override
public JsonNode apply(Field f, boolean editMode, Variable variable, WithType<JsonNode> contentHandler) {
Type t = f.getGenericType();
JsonNode out = contentHandler.apply(null, contentHandler, t, editMode, variable, null);
return out;
}
};
}
}
| 34.043478
| 143
| 0.719881
|
12846429287d97b1abe9eaa76ca2c7f0c7e69c65
| 1,304
|
package com.newer.kt.Refactor.ui.Avtivity.Settings;
import android.os.Bundle;
import android.os.Message;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.frame.app.base.activity.BaseActivity;
import com.newer.kt.R;
import butterknife.Bind;
import butterknife.OnClick;
/**
* Created by leo on 16/10/21.
*/
public class MineSchoolInfoActivity extends BaseActivity {
@Bind(R.id.image_head)
ImageView mImage_head;
@Bind(R.id.tv_school_name)
TextView mSchool_name;
@Bind(R.id.tv_studeng_cont)
TextView mCont;
@Bind(R.id.tv_shangji)
TextView mShangji;
@Override
protected void initHandler(Message msg) {
}
@Override
protected void initView(Bundle savedInstanceState) {
setContentView(R.layout.activity_mine_schoolinfo);
}
@Override
protected void setListener() {
}
@Override
protected void initData(Bundle savedInstanceState) {
}
@OnClick(R.id.back)
public void back() {
finish();
}
@OnClick(R.id.linear_head)
public void getHead() {
startActivity(SchoolHeadActivity.class);
}
@OnClick(R.id.linear_school_name)
public void getName() {
startActivity(SchoolNameActivity.class);
}
}
| 19.757576
| 58
| 0.695552
|
805ab3dbbb1b54b446e3d17e064441b6b36bf033
| 6,982
|
/*
* Copyright (c) 2017, 2018, Oracle and/or its affiliates.
* Copyright (c) 2013, Regents of the University of California
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.oracle.graal.python.nodes.statement;
import static com.oracle.graal.python.runtime.PythonOptions.CatchAllExceptions;
import com.oracle.graal.python.PythonLanguage;
import com.oracle.graal.python.builtins.objects.exception.PBaseException;
import com.oracle.graal.python.runtime.PythonOptions;
import com.oracle.graal.python.runtime.exception.ExceptionHandledException;
import com.oracle.graal.python.runtime.exception.PException;
import com.oracle.graal.python.runtime.exception.PythonErrorType;
import com.oracle.truffle.api.Assumption;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.CompilerDirectives.CompilationFinal;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.interop.ForeignAccess;
import com.oracle.truffle.api.interop.TruffleObject;
import com.oracle.truffle.api.nodes.ControlFlowException;
import com.oracle.truffle.api.nodes.ExplodeLoop;
import com.oracle.truffle.api.profiles.ValueProfile;
public class TryExceptNode extends StatementNode implements TruffleObject {
@Child private StatementNode body;
@Children private final ExceptNode[] exceptNodes;
@Child private StatementNode orelse;
@CompilationFinal private TryExceptNodeMessageResolution.CatchesFunction catchesFunction;
@CompilationFinal private ValueProfile exceptionStateProfile;
@CompilationFinal boolean seenException;
private final boolean shouldCatchAll;
private final Assumption singleContextAssumption;
public TryExceptNode(StatementNode body, ExceptNode[] exceptNodes, StatementNode orelse) {
this.body = body;
body.markAsTryBlock();
this.exceptNodes = exceptNodes;
this.orelse = orelse;
this.shouldCatchAll = PythonOptions.getOption(getContext(), CatchAllExceptions);
this.singleContextAssumption = PythonLanguage.getCurrent().singleContextAssumption;
}
@Override
public void executeVoid(VirtualFrame frame) {
// store current exception state for later restore
PException exceptionState = getContext().getCurrentException();
try {
body.executeVoid(frame);
} catch (PException ex) {
catchException(frame, ex, exceptionState);
return;
} catch (Exception e) {
if (!seenException) {
CompilerDirectives.transferToInterpreterAndInvalidate();
seenException = true;
}
if (shouldCatchAll()) {
if (e instanceof ControlFlowException) {
throw e;
} else {
PException pe = PException.fromObject(getBaseException(e), this);
try {
catchException(frame, pe, exceptionState);
} catch (PException pe_thrown) {
if (pe_thrown != pe) {
throw e;
}
}
}
} else {
throw e;
}
}
orelse.executeVoid(frame);
}
private boolean shouldCatchAll() {
if (singleContextAssumption.isValid()) {
return shouldCatchAll;
} else {
return PythonOptions.getOption(getContext(), CatchAllExceptions);
}
}
@TruffleBoundary
private PBaseException getBaseException(Exception t) {
return factory().createBaseException(PythonErrorType.ValueError, t.getMessage(), new Object[0]);
}
@ExplodeLoop
private void catchException(VirtualFrame frame, PException exception, PException exceptionState) {
boolean wasHandled = false;
for (ExceptNode exceptNode : exceptNodes) {
// we want a constant loop iteration count for ExplodeLoop to work,
// so we always run through all except handlers
if (!wasHandled) {
if (exceptNode.matchesException(frame, exception)) {
try {
exceptNode.executeExcept(frame, exception);
} catch (ExceptionHandledException e) {
wasHandled = true;
} catch (ControlFlowException e) {
// restore previous exception state, this won't happen if the except block
// raises an exception
getContext().setCaughtException(exceptionState);
throw e;
}
}
}
}
if (!wasHandled) {
throw exception;
}
// restore previous exception state, this won't happen if the except block
// raises an exception
getContext().setCaughtException(exceptionState);
}
public StatementNode getBody() {
return body;
}
public ExceptNode[] getExceptNodes() {
return exceptNodes;
}
public StatementNode getOrelse() {
return orelse;
}
@Override
public ForeignAccess getForeignAccess() {
return TryExceptNodeMessageResolutionForeign.ACCESS;
}
public TryExceptNodeMessageResolution.CatchesFunction getCatchesFunction() {
return this.catchesFunction;
}
public void setCatchesFunction(TryExceptNodeMessageResolution.CatchesFunction catchesFunction) {
CompilerDirectives.transferToInterpreterAndInvalidate();
this.catchesFunction = catchesFunction;
}
}
| 41.070588
| 104
| 0.675021
|
b99cc4c972c3f5929b9e7b9ba8814c0ca756e88b
| 5,236
|
// Generated from graphql_java_gen gem
package de.florianbeetz.ma.graphql.client;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.shopify.graphql.support.AbstractResponse;
import com.shopify.graphql.support.Arguments;
import com.shopify.graphql.support.Error;
import com.shopify.graphql.support.Query;
import com.shopify.graphql.support.SchemaViolationError;
import com.shopify.graphql.support.TopLevelResponse;
import com.shopify.graphql.support.Input;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Item extends AbstractResponse<Item> {
public Item() {
}
public Item(JsonObject fields) throws SchemaViolationError {
for (Map.Entry<String, JsonElement> field : fields.entrySet()) {
String key = field.getKey();
String fieldName = getFieldName(key);
switch (fieldName) {
case "description": {
String optional1 = null;
if (!field.getValue().isJsonNull()) {
optional1 = jsonAsString(field.getValue(), key);
}
responseData.put(key, optional1);
break;
}
case "id": {
responseData.put(key, Long.parseLong(jsonAsString(field.getValue(), key)));
break;
}
case "price": {
responseData.put(key, jsonAsDouble(field.getValue(), key));
break;
}
case "stock": {
List<ItemStock> optional1 = null;
if (!field.getValue().isJsonNull()) {
List<ItemStock> list1 = new ArrayList<>();
for (JsonElement element1 : jsonAsArray(field.getValue(), key)) {
ItemStock optional2 = null;
if (!element1.isJsonNull()) {
optional2 = new ItemStock(jsonAsObject(element1, key));
}
list1.add(optional2);
}
optional1 = list1;
}
responseData.put(key, optional1);
break;
}
case "title": {
responseData.put(key, jsonAsString(field.getValue(), key));
break;
}
case "totalAvailable": {
responseData.put(key, jsonAsInteger(field.getValue(), key).longValue());
break;
}
case "totalInStock": {
responseData.put(key, jsonAsInteger(field.getValue(), key).longValue());
break;
}
case "__typename": {
responseData.put(key, jsonAsString(field.getValue(), key));
break;
}
default: {
throw new SchemaViolationError(this, key, field.getValue());
}
}
}
}
public String getGraphQlTypeName() {
return "Item";
}
public String getDescription() {
return (String) get("description");
}
public Item setDescription(String arg) {
optimisticData.put(getKey("description"), arg);
return this;
}
public Long getId() {
return (Long) get("id");
}
public Item setId(Long arg) {
optimisticData.put(getKey("id"), arg);
return this;
}
public Double getPrice() {
return (Double) get("price");
}
public Item setPrice(Double arg) {
optimisticData.put(getKey("price"), arg);
return this;
}
public List<ItemStock> getStock() {
return (List<ItemStock>) get("stock");
}
public Item setStock(List<ItemStock> arg) {
optimisticData.put(getKey("stock"), arg);
return this;
}
public String getTitle() {
return (String) get("title");
}
public Item setTitle(String arg) {
optimisticData.put(getKey("title"), arg);
return this;
}
public Long getTotalAvailable() {
return (Long) get("totalAvailable");
}
public Item setTotalAvailable(Long arg) {
optimisticData.put(getKey("totalAvailable"), arg);
return this;
}
public Long getTotalInStock() {
return (Long) get("totalInStock");
}
public Item setTotalInStock(Long arg) {
optimisticData.put(getKey("totalInStock"), arg);
return this;
}
public boolean unwrapsToObject(String key) {
switch (getFieldName(key)) {
case "description": return false;
case "id": return false;
case "price": return false;
case "stock": return true;
case "title": return false;
case "totalAvailable": return false;
case "totalInStock": return false;
default: return false;
}
}
}
| 27.270833
| 95
| 0.526165
|
a4a0f7217391c968204edf7a851102ccb0559173
| 1,595
|
/*******************************************************************************
* Copyright (c) 2000, 2011 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.debug.ui.console;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.ui.console.IHyperlink;
import org.eclipse.ui.console.PatternMatchEvent;
import org.eclipse.ui.console.TextConsole;
/**
* creates JavaExceptionHyperLinks
*
* @since 3.1
*/
public class JavaExceptionConsoleTracker extends JavaConsoleTracker {
/* (non-Javadoc)
* @see org.eclipse.ui.console.IPatternMatchListenerDelegate#matchFound(org.eclipse.ui.console.PatternMatchEvent)
*/
@Override
public void matchFound(PatternMatchEvent event) {
try {
int offset = event.getOffset();
int length = event.getLength();
TextConsole console = getConsole();
String exceptionName;
exceptionName = console.getDocument().get(offset, length - 1);
IHyperlink link = new JavaExceptionHyperLink(console, exceptionName);
getConsole().addHyperlink(link, offset, length - 1);
} catch (BadLocationException e) {
}
}
}
| 37.97619
| 117
| 0.633229
|
31ff2b6579dfa4891879e0de8dce739e936b6de0
| 1,413
|
package com.github.vfyjxf.nee.processor;
import codechicken.nei.PositionedStack;
import codechicken.nei.recipe.IRecipeHandler;
import java.util.*;
/**
* @author vfyjxf
*/
public class BloodMagicRecipeProcessor implements IRecipeProcessor {
@Override
public Set<String> getAllOverlayIdentifier() {
return new HashSet<>(Arrays.asList(
"altarrecipes",
"alchemicalwizardry.alchemy",
"alchemicalwizardry.bindingritual"
));
}
@Override
public String getRecipeProcessorId() {
return "BloodMagic";
}
@Override
public List<PositionedStack> getRecipeInput(IRecipeHandler recipe, int recipeIndex, String identifier) {
for (String ident : getAllOverlayIdentifier()) {
if (ident.equals(identifier)) {
return new ArrayList<>(recipe.getIngredientStacks(recipeIndex));
}
}
return null;
}
@Override
public List<PositionedStack> getRecipeOutput(IRecipeHandler recipe, int recipeIndex, String identifier) {
for (String ident : getAllOverlayIdentifier()) {
if (ident.equals(identifier)) {
List<PositionedStack> recipeOutputs = new ArrayList<>();
recipeOutputs.add(recipe.getResultStack(recipeIndex));
return recipeOutputs;
}
}
return null;
}
}
| 28.836735
| 109
| 0.632696
|
8edc2ded5e338571e79229ccaeda642861455e91
| 12,232
|
/*
* 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.rocketmq.dashboard.controller;
import com.alibaba.fastjson.JSON;
import com.google.common.cache.Cache;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.rocketmq.client.QueryResult;
import org.apache.rocketmq.client.consumer.DefaultMQPullConsumer;
import org.apache.rocketmq.client.consumer.PullResult;
import org.apache.rocketmq.client.consumer.PullStatus;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageClientIDSetter;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.common.protocol.body.CMResult;
import org.apache.rocketmq.common.protocol.body.ConsumeMessageDirectlyResult;
import org.apache.rocketmq.common.protocol.body.ConsumerConnection;
import org.apache.rocketmq.dashboard.model.QueueOffsetInfo;
import org.apache.rocketmq.dashboard.model.request.MessageQuery;
import org.apache.rocketmq.dashboard.service.impl.MessageServiceImpl;
import org.apache.rocketmq.dashboard.util.MockObjectUtil;
import org.apache.rocketmq.tools.admin.api.MessageTrack;
import org.apache.rocketmq.tools.admin.api.TrackType;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
public class MessageControllerTest extends BaseControllerTest {
@InjectMocks
private MessageController messageController;
@Spy
private MessageServiceImpl messageService;
private Set<MessageQueue> messageQueues;
private DefaultMQPullConsumer defaultMQPullConsumer;
@Before
public void init() throws Exception {
super.mockRmqConfigure();
{
List<MessageExt> wrappers = new ArrayList<>(1);
wrappers.add(MockObjectUtil.createMessageExt());
defaultMQPullConsumer = mock(DefaultMQPullConsumer.class);
messageQueues = new HashSet<>(1);
MessageQueue messageQueue = new MessageQueue("topic_test", "broker-a", 0);
messageQueues.add(messageQueue);
when(defaultMQPullConsumer.fetchSubscribeMessageQueues(anyString())).thenReturn(messageQueues);
when(defaultMQPullConsumer.searchOffset(messageQueue, Long.MIN_VALUE)).thenReturn(Long.MIN_VALUE);
when(defaultMQPullConsumer.searchOffset(messageQueue, Long.MAX_VALUE)).thenReturn(Long.MAX_VALUE - 10L);
PullResult pullResult = mock(PullResult.class);
when(defaultMQPullConsumer.pull(any(), anyString(), anyLong(), anyInt())).thenReturn(pullResult);
when(pullResult.getNextBeginOffset()).thenReturn(Long.MAX_VALUE);
when(pullResult.getPullStatus()).thenReturn(PullStatus.FOUND);
when(pullResult.getMsgFoundList()).thenReturn(wrappers);
when(messageService.buildDefaultMQPullConsumer(any(), anyBoolean())).thenReturn(defaultMQPullConsumer);
}
}
@Test
public void testViewMessage() throws Exception {
final String url = "/message/viewMessage.query";
{
MessageExt messageExt = MockObjectUtil.createMessageExt();
when(mqAdminExt.viewMessage(anyString(), anyString()))
.thenThrow(new MQClientException(208, "no message"))
.thenReturn(messageExt);
MessageTrack track = new MessageTrack();
track.setConsumerGroup("group_test");
track.setTrackType(TrackType.CONSUMED);
List<MessageTrack> tracks = new ArrayList<>();
tracks.add(track);
when(mqAdminExt.messageTrackDetail(any()))
.thenThrow(new MQBrokerException(206, "consumer not online"))
.thenReturn(tracks);
}
// no message
requestBuilder = MockMvcRequestBuilders.get(url);
requestBuilder.param("topic", "topic_test");
requestBuilder.param("msgId", "0A9A003F00002A9F0000000000000319");
perform = mockMvc.perform(requestBuilder);
performErrorExpect(perform);
// consumer not online
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data.messageView.msgId").value("0A9A003F00002A9F0000000000000319"))
.andExpect(jsonPath("$.data.messageTrackList", hasSize(0)));
// query message success and has a group consumed.
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data.messageView.msgId").value("0A9A003F00002A9F0000000000000319"))
.andExpect(jsonPath("$.data.messageTrackList", hasSize(1)))
.andExpect(jsonPath("$.data.messageTrackList[0].consumerGroup").value("group_test"))
.andExpect(jsonPath("$.data.messageTrackList[0].trackType").value(TrackType.CONSUMED.name()));
}
@Test
public void testQueryMessagePageByTopic() throws Exception {
final String url = "/message/queryMessagePageByTopic.query";
MessageQuery query = new MessageQuery();
query.setPageNum(1);
query.setPageSize(10);
query.setTopic("topic_test");
query.setTaskId("");
query.setBegin(System.currentTimeMillis() - 3 * 24 * 60 * 60 * 1000);
query.setEnd(System.currentTimeMillis());
// missed cache
requestBuilder = MockMvcRequestBuilders.post(url);
requestBuilder.contentType(MediaType.APPLICATION_JSON_UTF8);
requestBuilder.content(JSON.toJSONString(query));
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data.page.content", hasSize(1)))
.andExpect(jsonPath("$.data.page.content[0].msgId").value("0A9A003F00002A9F0000000000000319"));
String taskId = MessageClientIDSetter.createUniqID();
{
List<QueueOffsetInfo> queueOffsetInfos = new ArrayList<>();
int idx = 0;
for (MessageQueue messageQueue : messageQueues) {
Long minOffset = defaultMQPullConsumer.searchOffset(messageQueue, query.getBegin());
Long maxOffset = defaultMQPullConsumer.searchOffset(messageQueue, query.getEnd()) + 1;
queueOffsetInfos.add(new QueueOffsetInfo(idx++, minOffset, maxOffset, minOffset, minOffset, messageQueue));
}
// Use reflection to add data to the CACHE
Field field = MessageServiceImpl.class.getDeclaredField("CACHE");
field.setAccessible(true);
Cache<String, List<QueueOffsetInfo>> cache = (Cache<String, List<QueueOffsetInfo>>) field.get(messageService);
cache.put(taskId, queueOffsetInfos);
}
// hit cache
query.setTaskId(taskId);
requestBuilder.content(JSON.toJSONString(query));
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data.page.content", hasSize(1)))
.andExpect(jsonPath("$.data.page.content[0].msgId").value("0A9A003F00002A9F0000000000000319"));
}
@Test
public void testQueryMessageByTopicAndKey() throws Exception {
final String url = "/message/queryMessageByTopicAndKey.query";
{
List<MessageExt> messageList = new ArrayList<>(2);
messageList.add(MockObjectUtil.createMessageExt());
QueryResult queryResult = new QueryResult(System.currentTimeMillis(), messageList);
when(mqAdminExt.queryMessage(anyString(), anyString(), anyInt(), anyLong(), anyLong()))
.thenReturn(queryResult);
}
requestBuilder = MockMvcRequestBuilders.get(url);
requestBuilder.param("topic", "topic_test");
requestBuilder.param("key", "KeyA");
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data", hasSize(1)))
.andExpect(jsonPath("$.data[0].msgId").value("0A9A003F00002A9F0000000000000319"));
}
@Test
public void testQueryMessageByTopic() throws Exception {
final String url = "/message/queryMessageByTopic.query";
requestBuilder = MockMvcRequestBuilders.get(url);
requestBuilder.param("topic", "topic_test")
.param("begin", Long.toString(System.currentTimeMillis() - 3 * 24 * 60 * 60 * 1000))
.param("end", Long.toString(System.currentTimeMillis()));
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data", hasSize(1)))
.andExpect(jsonPath("$.data[0].msgId").value("0A9A003F00002A9F0000000000000319"));
}
@Test
public void testConsumeMessageDirectly() throws Exception {
final String url = "/message/consumeMessageDirectly.do";
{
ConsumeMessageDirectlyResult result1 = new ConsumeMessageDirectlyResult();
result1.setConsumeResult(CMResult.CR_SUCCESS);
ConsumeMessageDirectlyResult result2 = new ConsumeMessageDirectlyResult();
result2.setConsumeResult(CMResult.CR_LATER);
when(mqAdminExt.consumeMessageDirectly(anyString(), anyString(), anyString(), anyString()))
.thenReturn(result1).thenReturn(result2);
ConsumerConnection consumerConnection = MockObjectUtil.createConsumerConnection();
when(mqAdminExt.examineConsumerConnectionInfo(anyString()))
.thenReturn(consumerConnection);
}
// clientId is not empty
requestBuilder = MockMvcRequestBuilders.post(url);
requestBuilder.param("topic", "topic_test")
.param("consumerGroup", "group_test")
.param("msgId", "0A9A003F00002A9F0000000000000319")
.param("clientId", "127.0.0.1@37540#2295913058176000");
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data.consumeResult").value(CMResult.CR_SUCCESS.name()));
// clientId is empty
requestBuilder = MockMvcRequestBuilders.post(url);
requestBuilder.param("topic", "topic_test")
.param("consumerGroup", "group_test")
.param("msgId", "0A9A003F00002A9F0000000000000319");
perform = mockMvc.perform(requestBuilder);
perform.andExpect(status().isOk())
.andExpect(jsonPath("$.data.consumeResult").value(CMResult.CR_LATER.name()));
}
@Override protected Object getTestController() {
return messageController;
}
}
| 48.733068
| 123
| 0.697433
|
f64a628ac41c5c8258cf2bcfeaa4241076acd0c3
| 1,600
|
package com.quancheng.saluki.gateway.oauth2.entity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.AbstractPersistable;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.time.ZonedDateTime;
@Data
@EqualsAndHashCode(of = {}, callSuper = false)
@EntityListeners(AuditingEntityListener.class)
@MappedSuperclass
public abstract class AbstractAuditable<PK extends Serializable> extends AbstractPersistable<PK> {
private static final long serialVersionUID = 1L;
@NotNull
@CreatedBy
@Size(max = 50)
@Column(name = "created_by", length = 50, updatable = false, nullable = false)
private String createdBy;
@NotNull
@CreatedDate
@Column(name = "created_date", updatable = false, nullable = false)
private ZonedDateTime createdDate = ZonedDateTime.now();
@Size(max = 50)
@LastModifiedBy
@Column(name = "last_modified_by", length = 50)
private String lastModifiedBy;
@LastModifiedDate
@Column(name = "last_modified_date")
private ZonedDateTime lastModifiedDate = ZonedDateTime.now();
}
| 33.333333
| 98
| 0.78625
|
8a656d1c8f39dea363cd563fff4b9c04bbd8d050
| 751
|
package io.github.talelin.latticy.service.impl;
import io.github.talelin.latticy.common.constant.IdentityConstant;
import io.github.talelin.core.util.EncryptUtil;
import io.github.talelin.latticy.model.UserIdentityDO;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import static org.junit.Assert.*;
public class UserIdentityServiceImplTest {
}
| 34.136364
| 66
| 0.846871
|
991e8293974f128403eccd4995886dfa72fdfac8
| 2,258
|
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.RequestDispatcher;
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;
/**
* Dieses Servlet zeigt, wie die Erzeugung des HTML-Codes an eine Java Server
* Page ausgelagert werden kann.
*/
@WebServlet(urlPatterns = {"/index.html"})
public class HalloServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Zwischenspeichern eines Wertes, den wir in der JSP anzeigen wollen
// Die letzte Zeile ist die wichtige Zeile hier
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Date date = new Date();
String tagesdatum = dateFormat.format(date);
request.setAttribute("tagesdatum", tagesdatum);
// Anfrage an eine JSP weiterleiten, um damit den HTML-Code
// der Seite zu generieren
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/hallo.jsp");
dispatcher.forward(request, response);
// Werte im Session Kontext entfernen, damit wir beim nächsten mal
// wieder von vorne anfangen
HttpSession session = request.getSession();
session.removeAttribute("vorname");
session.removeAttribute("nachname");
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Eingegebene Werte auslesen
String vorname = request.getParameter("vorname");
String nachname = request.getParameter("nachname");
// Werte im Session Kontext ablegen
HttpSession session = request.getSession();
session.setAttribute("vorname", vorname);
session.setAttribute("nachname", nachname);
// Und die Seite nochmal laden lassen
response.sendRedirect(request.getRequestURI());
}
}
| 37.633333
| 90
| 0.705049
|
bc7372f7fd7eb9dd596784d3367898f5ef2ed16c
| 1,365
|
package top.chenqwwq.leetcode.topic.tree._124;
import top.chenqwwq.leetcode.common.TreeNode;
/**
* 124. 二叉树中的最大路径和
* 路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。
* <p>
* 路径和 是路径中各节点值的总和。
* <p>
* 给你一个二叉树的根节点 root ,返回其 最大路径和 。
* <p>
* <p>
* 示例 1:
* <p>
* <p>
* 输入:root = [1,2,3]
* 输出:6
* 解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6
* 示例 2:
* <p>
* <p>
* 输入:root = [-10,9,20,null,null,15,7]
* 输出:42
* 解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42
* <p>
* <p>
* 提示:
* <p>
* 树中节点数目范围是 [1, 3 * 104]
* -1000 <= Node.val <= 1000
*
* @author chen
* @date 2021-05-20
**/
public class Solution {
int ans = Integer.MIN_VALUE;
final int minValue = -Integer.MAX_VALUE / 2 + 20000;
public int maxPathSum(TreeNode root) {
if (root == null) {
return -1;
}
dfs(root);
return ans;
}
/**
* 返回的是带 root 节点的最大路径和
*/
public int dfs(TreeNode root) {
if (root == null) {
return minValue;
}
// 获取 left/right 节点的最大单路径
final int left = dfs(root.left);
final int right = dfs(root.right);
// 不经过父节点
ans = max(ans, left + right + root.val, root.val, root.val + left, root.val + right);
return max(root.val, root.val + left, root.val + right);
}
private int max(int... nums) {
int max = Integer.MIN_VALUE;
for (int i : nums) {
max = Math.max(max, i);
}
return max;
}
}
| 18.958333
| 89
| 0.587546
|
c2d38da590d076a947b1188f3ddc60401926d082
| 4,039
|
/*-
* Copyright (C) 2011, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This file was distributed by Oracle as part of a version of Oracle NoSQL
* Database made available at:
*
* http://www.oracle.com/technetwork/database/database-technologies/nosqldb/downloads/index.html
*
* Please see the LICENSE file included in the top-level directory of the
* appropriate version of Oracle NoSQL Database for a copy of the license and
* additional information.
*/
package oracle.kv.impl.util.sklogger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* A CustomGauge as one kind of {@link Metric} is useful when Gauge value is
* not possible to directly instrument code, as it is not in your control, such
* as gauge System memory value.
* <pre>
* Usage example:
* <code>
* private static class TestCalculator implements GaugeCalculator {
* @Override
* public List<GaugeResult> getValuesList() {
* Map<String, Object> metrics = new HashMap<String, Object>(2);
* metrics.put("free", Runtime.getRuntime().freeMemory());
* metrics.put("total", Runtime.getRuntime().maxMemory());
* return Arrays.asList(new GaugeResult(metrics));
* }
* }
* CustomGauge memory = new CustomGauge("memory", new TestCalculator());
* memory.getValuesList();
* </code>
* </pre>
*/
public class CustomGauge extends Metric<CustomGauge.GaugeCalculator> {
private final static List<String> EMPTY_LABEL_VALUES = Arrays.asList();
private final GaugeCalculator gaugeCalculator;
/**
* @param name is metric name that will be used when metric is registered
* and/or processed.
* @param gaugeCalculator is used to get the current gauge value map.
*/
public CustomGauge(final String name,
GaugeCalculator gaugeCalculator) {
super(name);
this.gaugeCalculator = gaugeCalculator;
}
/**
* Implement the interface to get current GaugeResult list.
*/
public interface GaugeCalculator extends Metric.Element {
/**
* Get current GaugeResult list.
*/
List<GaugeResult> getValuesList();
}
/**
* {@inheritDoc}
*/
@Override
protected GaugeCalculator newElement() {
return gaugeCalculator;
}
// Convenience methods.
/**
* {@link GaugeCalculator#getValuesList}.
*/
public List<GaugeResult> getValuesList() {
try {
return gaugeCalculator.getValuesList();
} catch (Exception e) {
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public MetricFamilySamples<GaugeResult> collect() {
List<GaugeResult> gaugeResultList = null;
try {
gaugeResultList = gaugeCalculator.getValuesList();
} catch (Exception e) {
}
if (gaugeResultList == null) {
return null;
}
final List<MetricFamilySamples.Sample<GaugeResult>> samples =
new ArrayList<MetricFamilySamples.Sample<GaugeResult>>(
gaugeResultList.size());
for (GaugeResult e : gaugeResultList) {
samples.add(
new MetricFamilySamples.Sample<GaugeResult>(
EMPTY_LABEL_VALUES, e));
}
return new MetricFamilySamples<GaugeResult>(statsName,
Type.CUSTOM_GAUGE,
labelNames, samples);
}
/**
* Saving collected {@link CustomGauge} result.
*/
public static class GaugeResult extends Metric.Result {
private static final long serialVersionUID = 1L;
private Map<String, Object> map;
public GaugeResult(Map<String, Object> map) {
this.map = map;
}
/**
* {@inheritDoc}
*/
@Override
public Map<String, Object> toMap() {
return map;
}
}
}
| 29.057554
| 96
| 0.611785
|
5848b823e928cafcef0315f21210412d410a1335
| 823
|
package com.aap.engagingchoice.utility;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* This class is for DateUtils
*/
public class DateUtils {
public static String getDate(String dateInString) {
String newDate = null;
DateFormat format = new SimpleDateFormat("yyyy-MM-d", Locale.getDefault());
DateFormat format1 = new SimpleDateFormat("MMM d, yyyy ", Locale.getDefault());
Date date = null;
try {
date = format.parse(dateInString);
newDate = format1.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(newDate); // Sat Jan 02 00:00:00 GMT 2010
return newDate;
}
}
| 28.37931
| 87
| 0.648846
|
0991d0b083fa739e1747a386ba37341ef40e89d2
| 469
|
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
// Random random=new Random();
// int a=random.nextInt(20);
n = sc.nextInt();
// System.out.println(a);
int[] f1=new int[n+2];
f1[1]=1;
f1[2]=1;
if (n >= 3 && n <= 1000000) {
for(int i=3;i<=n;i++){
f1[i]=(f1[i-1]+f1[i-2])%10007;
}
}
System.out.println(f1[n]);
sc.close();
}
}
| 18.76
| 41
| 0.575693
|
8dc7583397182c734e603bb5b6acedf9148f0360
| 1,526
|
package net.nazarsit;
import javax.annotation.Resource;
import javax.jms.*;
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.ws.rs.core.MediaType;
import java.io.IOException;
@WebServlet("/send")
public class SimpleJMSServlet extends HttpServlet {
@Resource(lookup = "jms/QueueConnectionFactory")
ConnectionFactory jmsConnectionFactory;
@Resource(lookup = "jms/HelloQueue")
Queue helloQueue;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType(MediaType.TEXT_PLAIN);
String msg = "hello";
try {
pushMessageToQueue(msg);
} catch (JMSException e) {
resp.setStatus(502);
resp.getWriter().println("Failed to Push " + msg + " to queue");
resp.getWriter().println(e);
e.printStackTrace();
}
resp.setStatus(200);
resp.getWriter().println("Pushed " + msg + " to queue");
}
private void pushMessageToQueue(String msg) throws JMSException{
Connection con = jmsConnectionFactory.createConnection();
Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
TextMessage message = session.createTextMessage(msg);
session.createProducer(helloQueue).send(message);
}
}
| 31.791667
| 113
| 0.699869
|
42b7a76152303c182f232d005520bafd986c2d7e
| 1,341
|
package com.upgrad.technical.service.common;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.text.MessageFormat;
public class UnexpectedException extends RuntimeException {
private static final long serialVersionUID = 2737472949025937415L;
private final ErrorCode errorCode;
private Throwable cause;
private final Object[] parameters;
public UnexpectedException(final ErrorCode errorCode, final Object... parameters) {
super();
this.errorCode = errorCode;
this.parameters = parameters;
}
public UnexpectedException(final ErrorCode errorCode, final Throwable cause, final Object... parameters) {
super();
this.errorCode = errorCode;
this.cause = cause;
this.parameters = parameters;
}
public ErrorCode getErrorCode() {
return errorCode;
}
@Override
public String getMessage() {
return MessageFormat.format(errorCode.getDefaultMessage(), this.parameters);
}
@Override
public Throwable getCause() {
return cause;
}
@Override
public final void printStackTrace(final PrintStream stream) {
super.printStackTrace(stream);
}
@Override
public final void printStackTrace(final PrintWriter writer) {
super.printStackTrace(writer);
}
}
| 24.833333
| 110
| 0.689784
|
c01d29c032ebdfad501cfc68700a9eb30f2335ef
| 2,875
|
package what.whatandroid.artist;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import api.torrents.artist.Artist;
import what.whatandroid.R;
import what.whatandroid.WhatApplication;
import what.whatandroid.callbacks.LoadingListener;
import what.whatandroid.callbacks.SetTitleCallback;
import what.whatandroid.settings.SettingsActivity;
import what.whatandroid.views.ImageDialog;
/**
* Fragment displaying the artist image and list of releases and requests
*/
public class ArtistReleasesFragment extends Fragment implements LoadingListener<Artist>, View.OnClickListener {
/**
* The artist being shown
*/
private Artist artist;
/**
* Various content views displaying the artist information
*/
private ImageView image;
private ProgressBar spinner;
private View artContainer;
private ExpandableListView torrentList;
public ArtistReleasesFragment(){
//Required empty ctor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.expandable_list_view, container, false);
torrentList = (ExpandableListView)view.findViewById(R.id.exp_list);
View header = inflater.inflate(R.layout.header_image, torrentList, false);
torrentList.addHeaderView(header);
image = (ImageView)header.findViewById(R.id.image);
image.setOnClickListener(this);
spinner = (ProgressBar)header.findViewById(R.id.loading_indicator);
artContainer = header.findViewById(R.id.art_container);
if (artist != null){
populateViews();
}
return view;
}
/**
* Update all the artist information with the loaded api request
*/
private void populateViews(){
((SetTitleCallback)getActivity()).setTitle(artist.getResponse().getName());
String imgUrl = artist.getResponse().getImage();
if (!SettingsActivity.imagesEnabled(getActivity())) {
artContainer.setVisibility(View.GONE);
} else {
artContainer.setVisibility(View.VISIBLE);
WhatApplication.loadImage(getActivity(), imgUrl, image, spinner, null, null);
}
if (torrentList.getAdapter() == null){
ArtistTorrentAdapter adapter = new ArtistTorrentAdapter(getActivity(), artist.getReleases().flatten(),
artist.getResponse().getRequests());
torrentList.setAdapter(adapter);
torrentList.setOnChildClickListener(adapter);
}
}
@Override
public void onClick(View v){
if (v.getId() == R.id.image){
ImageDialog dialog = ImageDialog.newInstance(artist.getResponse().getImage());
dialog.show(getChildFragmentManager(), "image_dialog");
}
}
@Override
public void onLoadingComplete(Artist data){
artist = data;
if (isAdded()){
populateViews();
}
}
}
| 30.913978
| 111
| 0.767652
|
3d8467c2e1bb808015a867b1aaf729ad4c96fd31
| 202
|
package com.volna80.betfair.api.model;
/**
* (c) All rights reserved
*
* @author nikolay.volnov@gmail.com
*/
public class MarketTypes {
public static final String MATCH_ODDS = "MATCH_ODDS";
}
| 16.833333
| 57
| 0.70297
|
28eccaf8ad7e3fa6a12ed0bd6f7eb5143620578a
| 4,510
|
package de.st_ddt.crazyplugin.data;
import java.util.Date;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import de.st_ddt.crazyutil.ChatHeaderProvider;
import de.st_ddt.crazyutil.ChatHelper;
import de.st_ddt.crazyutil.locales.CrazyLocale;
import de.st_ddt.crazyutil.source.Localized;
public abstract class PlayerData<S extends PlayerDataInterface> implements PlayerDataInterface, Comparable<S>
{
protected final String name;
public PlayerData(final String name)
{
super();
this.name = name;
}
protected abstract String getChatHeader();
@Override
public void show(final CommandSender target)
{
show(target, getChatHeader(), true);
}
@Override
@Localized({ "CRAZYPLUGIN.PLAYERINFO.HEAD {DateTime}", "CRAZYPLUGIN.PLAYERINFO.USERNAME {Username}", "CRAZYPLUGIN.PLAYERINFO.DISPLAYNAME {Displayname}", "CRAZYPLUGIN.PLAYERINFO.IPADDRESS {IPAdress}", "CRAZYPLUGIN.PLAYERINFO.CONNECTION {Connection}", "CRAZYPLUGIN.PLAYERINFO.URL {IPAddress}", "CRAZYPLUGIN.PLAYERINFO.FIRSTCONNECT {DateTime}", "CRAZYPLUGIN.PLAYERINFO.LASTCONNECT {DateTime}", "CRAZYPLUGIN.PLAYERINFO.OP {OP}", "CRAZYPLUGIN.PLAYERINFO.WHITELISTED {Whitelisted}", "CRAZYPLUGIN.PLAYERINFO.BANNED {Banned}", "CRAZYPLUGIN.PLAYERINFO.SEPARATOR" })
public void show(final CommandSender target, final String chatHeader, final boolean showDetailed)
{
final CrazyLocale locale = CrazyLocale.getLocaleHead().getSecureLanguageEntry("CRAZYPLUGIN.PLAYERINFO");
final Player player = getPlayer();
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("HEAD"), ChatHeaderProvider.DATETIMEFORMAT.format(new Date()));
if (player == null)
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("USERNAME"), getName());
else
{
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("USERNAME"), player.getName());
if (player.getDisplayName() == null)
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("DISPLAYNAME"), player.getName());
else
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("DISPLAYNAME"), player.getDisplayName());
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("IPADDRESS"), player.getAddress().getAddress().getHostAddress());
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("CONNECTION"), player.getAddress().getHostName());
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("URL"), player.getAddress().getAddress().getHostAddress());
}
final OfflinePlayer plr = getOfflinePlayer();
if (plr != null)
{
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("FIRSTCONNECT"), ChatHeaderProvider.DATETIMEFORMAT.format(new Date(plr.getFirstPlayed())));
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("LASTCONNECT"), ChatHeaderProvider.DATETIMEFORMAT.format(new Date(plr.getLastPlayed())));
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("OP"), plr.isOp() ? "True" : "False");
if (Bukkit.hasWhitelist())
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("WHITELISTED"), plr.isWhitelisted() ? "True" : "False");
if (plr.isBanned())
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("BANNED"), "True");
}
if (showDetailed)
{
ChatHelper.sendMessage(target, chatHeader, locale.getLanguageEntry("SEPARATOR"));
showDetailed(target, chatHeader);
}
}
@Override
public String getShortInfo()
{
return toString();
}
@Override
public Player getPlayer()
{
return Bukkit.getPlayerExact(getName());
}
@Override
public OfflinePlayer getOfflinePlayer()
{
return Bukkit.getOfflinePlayer(getName());
}
@Override
public String getName()
{
return name;
}
@Override
public boolean isOnline()
{
final Player player = getPlayer();
if (player == null)
return false;
return player.isOnline();
}
@Override
public String toString()
{
return "PlayerData " + getName();
}
@Override
public int compareTo(final S o)
{
return name.compareToIgnoreCase(o.getName());
}
@Override
public int hashCode()
{
return name.toLowerCase().hashCode();
}
@Override
public boolean equals(final Object obj)
{
if (obj instanceof PlayerDataInterface)
return equals((PlayerDataInterface) obj);
return false;
}
public boolean equals(final PlayerDataInterface obj)
{
return name.equalsIgnoreCase(obj.getName());
}
}
| 33.161765
| 557
| 0.758315
|
b860df1634244f9fe2cb193620e58d345715663a
| 2,706
|
/* */ package Util;
/* */
/* */ import Entity.UserLog;
/* */ import Entity.Users;
/* */ import java.sql.Timestamp;
/* */ import java.util.Date;
/* */ import java.util.Iterator;
/* */ import java.util.List;
/* */ import org.hibernate.HibernateException;
/* */ import org.hibernate.Query;
/* */ import org.hibernate.Session;
/* */ import org.hibernate.SessionFactory;
/* */ import org.hibernate.Transaction;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class LoginSec
/* */ {
/* */ private static Users LoggedUser;
/* */ SessionFactory sf;
/* */ Session s;
/* */
/* 34 */ public static Users getLoggedUser() { return LoggedUser; }
/* */
/* */
/* */ public String HandleLogin(String uName, String Pass) throws HibernateException {
/* 38 */ String status = "";
/* 39 */ this.sf = HibernateUtil.getSessionFactory();
/* 40 */ this.s = this.sf.openSession();
/* 41 */ Transaction t = this.s.beginTransaction();
/* 42 */ Query query = this.s.createQuery("from Users where U_NAME= :s and PASS= :p");
/* 43 */ query.setParameter("s", uName).setParameter("p", Pass);
/* 44 */ List<Users> users = query.list();
/* 45 */ UserLog ul = new UserLog();
/* 46 */ for (Iterator<Users> iterator = users.iterator(); iterator.hasNext(); ) {
/* 47 */ Users next = (Users)iterator.next();
/* 48 */ LoggedUser = next;
/* 49 */ status = LoggedUser.getStatus();
/* 50 */ ul.setUId(LoggedUser);
/* 51 */ ul.setLogDate(new Timestamp((new Date()).getTime()));
/* 52 */ ul.setLogDESC("User : " + LoggedUser.getUName() + " -- Login");
/* 53 */ this.s.persist(ul);
/* 54 */ t.commit();
/* */ }
/* 56 */ this.s.close();
/* */
/* 58 */ return status;
/* */ }
/* */
/* */ public void HandleLogout() {
/* 62 */ UserLog ul = new UserLog();
/* 63 */ this.sf = HibernateUtil.getSessionFactory();
/* 64 */ this.s = this.sf.openSession();
/* 65 */ Transaction t = this.s.beginTransaction();
/* 66 */ ul.setUId(LoggedUser);
/* 67 */ ul.setLogDate(new Timestamp((new Date()).getTime()));
/* 68 */ ul.setLogDESC("User : " + LoggedUser.getUName() + " -- logout");
/* 69 */ this.s.persist(ul);
/* 70 */ t.commit();
/* 71 */ this.s.close();
/* */ }
/* */ }
/* Location: C:\Users\Abdo\Documents\Amgad-H.jar!\Util\LoginSec.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.0.0
*/
| 34.253165
| 92
| 0.503695
|
ba2860568a28b0e74c38199aa89f0ec8e596ecf5
| 1,399
|
/*
* Copyright 2015 Michael Quigley
*
* 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.quigley.zabbixj.examples;
import com.quigley.zabbixj.agent.ZabbixAgent;
import com.quigley.zabbixj.providers.JVMMetricsProvider;
/**
* A simple passive Zabbix agent implementation.
*
* @author Michael Quigley
*/
public class ExamplePassiveAgent {
public static void main(String[] args) throws Exception {
if(args.length < 1) {
System.out.println("Usage: ExamplePassiveAgent <listenPort>");
return;
}
int listenPort = Integer.parseInt(args[0]);
ZabbixAgent agent = new ZabbixAgent();
agent.setListenPort(listenPort);
agent.addProvider("example", new ExampleMetricsProvider());
agent.addProvider("java", new JVMMetricsProvider());
agent.start();
while(true) {
Thread.sleep(10000);
}
}
}
| 27.98
| 75
| 0.70193
|
4ef34460fca389242c911b379cd777e3477fba36
| 801
|
package com.himanshu.graphqlserver.datastore;
import com.himanshu.graphqlserver.domain.Person;
import com.himanshu.graphqlserver.domain.PersonAddress;
import java.util.ArrayList;
import java.util.List;
public class PersonStore {
static List<Person> personList = new ArrayList<>();
/**
* Method to create dummy data for personList
* @return
*/
public static List<Person> getPersonList () {
if(personList.isEmpty()) {
for(int i=0;i<5;i++) {
PersonAddress personAddress = new PersonAddress("streetName" + i, "houseNumber" + i, "city" + i, "country" + i);
Person person = new Person(i,"personName" + i, personAddress);
personList.add(person);
}
}
return personList;
}
}
| 25.83871
| 128
| 0.621723
|
2a4194e9094a28f71925702107bc899f8fdb13d1
| 3,559
|
package com.wangrollin.leetcode.n0_normal.p900.p990.problem999;
/**
* 可以被一步捕获的棋子数
*
* 在一个 8 x 8 的棋盘上,有一个白色的车(Rook),用字符 'R' 表示。棋盘上还可能存在空方块,白色的象(Bishop)以及黑色的卒(pawn),
* 分别用字符 '.','B' 和 'p' 表示。不难看出,大写字符表示的是白棋,小写字符表示的是黑棋。
* 车按国际象棋中的规则移动。东,西,南,北四个基本方向任选其一,然后一直向选定的方向移动,直到满足下列四个条件之一:
* - 棋手选择主动停下来。
* - 棋子因到达棋盘的边缘而停下。
* - 棋子移动到某一方格来捕获位于该方格上敌方(黑色)的卒,停在该方格内。
* - 车不能进入/越过已经放有其他友方棋子(白色的象)的方格,停在友方棋子前。
* 你现在可以控制车移动一次,请你统计有多少敌方的卒处于你的捕获范围内(即,可以被一步捕获的棋子数)。
*
* 示例 1:
* 输入:[[".",".",".",".",".",".",".","."],
* [".",".",".","p",".",".",".","."],
* [".",".",".","R",".",".",".","p"],
* [".",".",".",".",".",".",".","."],
* [".",".",".",".",".",".",".","."],
* [".",".",".","p",".",".",".","."],
* [".",".",".",".",".",".",".","."],
* [".",".",".",".",".",".",".","."]]
* 输出:3
* 解释:
* 在本例中,车能够捕获所有的卒。
*
* 示例 2:
* 输入:[[".",".",".",".",".",".",".","."],
* [".","p","p","p","p","p",".","."],
* [".","p","p","B","p","p",".","."],
* [".","p","B","R","B","p",".","."],
* [".","p","p","B","p","p",".","."],
* [".","p","p","p","p","p",".","."],
* [".",".",".",".",".",".",".","."],
* [".",".",".",".",".",".",".","."]]
* 输出:0
* 解释:
* 象阻止了车捕获任何卒。
*
* 示例 3:
* 输入:[[".",".",".",".",".",".",".","."],
* [".",".",".","p",".",".",".","."],
* [".",".",".","p",".",".",".","."],
* ["p","p",".","R",".","p","B","."],
* [".",".",".",".",".",".",".","."],
* [".",".",".","B",".",".",".","."],
* [".",".",".","p",".",".",".","."],
* [".",".",".",".",".",".",".","."]]
* 输出:3
* 解释:
* 车可以捕获位置 b5,d6 和 f5 的卒。
*
* 提示:
* board.length == board[i].length == 8
* board[i][j] 可以是'R','.','B'或'p'
* 只有一个格子上存在board[i][j] == 'R'
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/available-captures-for-rook
*
* Solution1
* 先找到车的位置,然后模拟四个方向
*/
public class Solution1 {
public int numRookCaptures(char[][] board) {
int x = 0;
int y = 0;
boolean isFound = false;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
if ('R' == board[i][j]) {
x = i;
y = j;
isFound = true;
break;
}
}
if (isFound) {
break;
}
}
return findInOneDirection(x, y, board, "DOWN")
+ findInOneDirection(x, y, board, "UP")
+ findInOneDirection(x, y, board, "LEFT")
+ findInOneDirection(x, y, board, "RIGHT");
}
private int findInOneDirection(int x, int y, char[][] board, String direction) {
int isDown = 0;
int isUp = 0;
int isLeft = 0;
int isRight = 0;
switch (direction) {
case "DOWN":
isDown = 1;
break;
case "UP":
isUp = -1;
break;
case "LEFT":
isLeft = -1;
break;
case "RIGHT":
isRight = 1;
break;
}
for (int i = 1; i < board.length; i++) {
x += isDown + isUp;
y += isLeft + isRight;
if (x < 0 || x > 7 || y < 0 || y > 7) {
return 0;
}
if (board[x][y] == 'B') {
return 0;
} else if (board[x][y] == 'p') {
return 1;
}
}
return 0;
}
}
| 27.589147
| 84
| 0.33043
|
836fe0131a27af6a3d19996c7a7e4d6029193a04
| 3,562
|
package com.smhu.controller;
import com.smhu.iface.IModeration;
import com.smhu.system.SystemTime;
import com.smhu.web.ModerationController;
import java.sql.Date;
import java.sql.Time;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Component
@CrossOrigin
@RequestMapping("/api")
public class SystemTimeController {
final String DATE_TIME = "datetime";
final String DATE = "date";
final String TIME = "time";
final String MILISECOND = "milisecond";
SystemTimeService service;
@GetMapping("/system/format")
public ResponseEntity getAllTypeSystemTime() {
Map<String, String> map = new HashMap<>();
map.put(DATE_TIME, "Date and Time. Format: yyyy-MM-dd hh:mm:ss");
map.put(DATE, "Date. Format: yyyy-MM-dd");
map.put(TIME, "Time. Format: hh:mm:ss");
map.put(MILISECOND, "Milisecond");
return new ResponseEntity(map, HttpStatus.OK);
}
@GetMapping("/system/time/{type}")
public ResponseEntity getSystemTime(@PathVariable("type") String type) {
switch (type.toLowerCase()) {
case DATE_TIME:
return new ResponseEntity(new Date(SystemTime.SYSTEM_TIME) + " " + new Time(SystemTime.SYSTEM_TIME), HttpStatus.OK);
case DATE:
return new ResponseEntity(new Date(SystemTime.SYSTEM_TIME), HttpStatus.OK);
case TIME:
return new ResponseEntity(new Time(SystemTime.SYSTEM_TIME), HttpStatus.OK);
case MILISECOND:
return new ResponseEntity(SystemTime.SYSTEM_TIME, HttpStatus.OK);
default:
return new ResponseEntity(HttpStatus.METHOD_NOT_ALLOWED.toString(), HttpStatus.METHOD_NOT_ALLOWED);
}
}
@GetMapping("/system/change/{time}")
public ResponseEntity updateSystemTime(@PathVariable("time") String time) {
service = new SystemTimeService();
ZonedDateTime dateTime = ZonedDateTime.now(ZoneId.of("Asia/Ho_Chi_Minh"));
Calendar calendar = Calendar.getInstance();
calendar.set(dateTime.getYear(), dateTime.getMonthValue() - 1, dateTime.getDayOfMonth(),
service.getTime(time, service.HOUR),
service.getTime(time, service.MINUTE),
service.getTime(time, service.SECOND));
SystemTime.SYSTEM_TIME = calendar.getTimeInMillis();
IModeration modListener = new ModerationController();
modListener.reloadCommission();
return new ResponseEntity(HttpStatus.OK);
}
class SystemTimeService {
final int HOUR = 1;
final int MINUTE = 2;
final int SECOND = 3;
int getTime(String time, int type) {
String[] timeArr = time.split(":");
switch (type) {
case HOUR:
return Integer.parseInt(timeArr[0]);
case MINUTE:
return Integer.parseInt(timeArr[1]);
case SECOND:
return Integer.parseInt(timeArr[2]);
default:
return -1;
}
}
}
}
| 36.721649
| 132
| 0.652442
|
87b02c3b638f5ae27addda32ea1cc80985edfe98
| 400
|
package com.delmar.sysSettings.service;
import java.util.List;
import com.delmar.core.service.CoreService;
import com.delmar.sysSettings.model.SysSettingsItemTrl;
public interface SysSettingsItemTrlService extends CoreService<SysSettingsItemTrl>{
public SysSettingsItemTrl saveOrUpdate(SysSettingsItemTrl sysSettingsItemTrl);
public List<SysSettingsItemTrl> getItemTrlList(Integer itemId);
}
| 28.571429
| 83
| 0.8525
|
154dd130ec2aca6b74b100433f5df29a9f12a32f
| 3,434
|
/*package red.jackf.chesttracker.compat;
import me.shedaniel.rei.api.DisplayHelper;
import me.shedaniel.rei.api.EntryStack;
import me.shedaniel.rei.api.OverlayDecider;
import me.shedaniel.rei.api.client.plugins.REIClientPlugin;
import me.shedaniel.rei.api.client.registry.screen.ExclusionZones;
import me.shedaniel.rei.api.client.registry.screen.OverlayDecider;
import me.shedaniel.rei.api.client.registry.screen.ScreenRegistry;
import me.shedaniel.rei.api.plugins.REIPluginV0;
import me.shedaniel.rei.gui.ContainerScreenOverlay;
import me.shedaniel.rei.gui.RecipeScreen;
import me.shedaniel.rei.gui.widget.EntryWidget;
import me.shedaniel.rei.gui.widget.Widget;
import me.shedaniel.rei.impl.ItemEntryStack;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.Element;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Identifier;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import red.jackf.chesttracker.gui.ItemListScreen;
import java.util.List;
import static red.jackf.chesttracker.ChestTracker.id;
@Environment(EnvType.CLIENT)
public class REIPlugin implements REIClientPlugin {
public static @NotNull ItemStack tryFindItem(double mouseX, double mouseY) {
// Big List
ItemStack item = tryFindInList(ContainerScreenOverlay.getEntryListWidget().children(), mouseX, mouseY);
if (item != null) return item;
// Favourites
if (ContainerScreenOverlay.getFavoritesListWidget() != null) {
item = tryFindInList(ContainerScreenOverlay.getFavoritesListWidget().children(), mouseX, mouseY);
if (item != null) return item;
}
if (MinecraftClient.getInstance().currentScreen instanceof RecipeScreen) {
item = tryFindInList((MinecraftClient.getInstance().currentScreen).children(), mouseX, mouseY);
if (item != null) return item;
}
return ItemStack.EMPTY;
}
@Nullable
private static ItemStack tryFindInList(@Nullable List<? extends Element> elements, double mouseX, double mouseY) {
if (elements == null) return null;
for (Element element : elements) {
if (element instanceof Widget) {
Widget widget = (Widget) element;
if (widget instanceof EntryWidget && widget.containsMouse(mouseX, mouseY)) {
EntryWidget entryWidget = (EntryWidget) widget;
for (EntryStack entryStack : entryWidget.getEntries()) {
if (entryStack instanceof ItemEntryStack && !entryStack.getItemStack().isEmpty()) {
return entryStack.getItemStack();
}
}
}
}
}
return null;
}
@Override
public void registerScreens(ScreenRegistry registry) {
registry.registerDecider(new OverlayDecider() {
@Override
public <R extends Screen> boolean isHandingScreen(Class<R> screen) {
return screen == ItemListScreen.class;
}
@Override
public ActionResult shouldScreenBeOverlaid(Class<?> screen) {
return ActionResult.PASS;
}
});
}
}
*/
| 39.022727
| 118
| 0.682003
|
c5246e4beeff818b43b2247df304eec6bc1020b3
| 6,705
|
package uk.co.optimisticpanda.atom;
import static java.util.Collections.sort;
import static org.junit.Assert.assertEquals;
import static uk.co.optimisticpanda.atom.EntryFunctions.contentHasMediaType;
import static uk.co.optimisticpanda.atom.EntryFunctions.dontHaveCategory;
import static uk.co.optimisticpanda.atom.EntryFunctions.earliestToLatest;
import static uk.co.optimisticpanda.atom.EntryFunctions.haveACategoryOf;
import static uk.co.optimisticpanda.atom.EntryFunctions.idEquals;
import static uk.co.optimisticpanda.atom.EntryFunctions.latestToEarliest;
import static uk.co.optimisticpanda.atom.TestEntryBuilder.create;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import javax.ws.rs.core.MediaType;
import org.apache.abdera.model.Entry;
import org.junit.Test;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
public class EntryFunctionsTest {
@Test
public void checkLatestToEarliestComparing(){
Entry entry1 = create("1").updatedOn("2013-03-10T00:00:00.001Z").instance();
Entry entry2 = create("2").updatedOn("2013-03-10T00:00:00.002Z").instance();
Entry entry3 = create("3").updatedOn("2013-03-10T00:00:00.003Z").instance();
assertEquals("3,2,1", titlesOf(sortBy(latestToEarliest(), entry1, entry2, entry3)));
assertEquals("3,2,1", titlesOf(sortBy(latestToEarliest(), entry1, entry3, entry2)));
assertEquals("3,2,1", titlesOf(sortBy(latestToEarliest(), entry3, entry1, entry2)));
assertEquals("3,2,1", titlesOf(sortBy(latestToEarliest(), entry3, entry2, entry1)));
assertEquals("3,2,1", titlesOf(sortBy(latestToEarliest(), entry2, entry1, entry3)));
assertEquals("3,2,1", titlesOf(sortBy(latestToEarliest(), entry2, entry3, entry1)));
}
@Test
public void checkEarliestToLatestComparing(){
Entry entry1 = create("1").updatedOn("2013-03-10T00:00:00.001Z").instance();
Entry entry2 = create("2").updatedOn("2013-03-10T00:00:00.002Z").instance();
Entry entry3 = create("3").updatedOn("2013-03-10T00:00:00.003Z").instance();
assertEquals("1,2,3", titlesOf(sortBy(earliestToLatest(), entry1, entry2, entry3)));
assertEquals("1,2,3", titlesOf(sortBy(earliestToLatest(), entry1, entry3, entry2)));
assertEquals("1,2,3", titlesOf(sortBy(earliestToLatest(), entry3, entry1, entry2)));
assertEquals("1,2,3", titlesOf(sortBy(earliestToLatest(), entry3, entry2, entry1)));
assertEquals("1,2,3", titlesOf(sortBy(earliestToLatest(), entry2, entry1, entry3)));
assertEquals("1,2,3", titlesOf(sortBy(earliestToLatest(), entry2, entry3, entry1)));
}
@Test
public void checkNullsDontKillDateComparison(){
Entry entry1 = create("1").updatedOn(null).instance();
Entry entry2 = create("2").updatedOn("2013-03-10T00:00:00.002Z").instance();
assertEquals("2,1", titlesOf(sortBy(earliestToLatest(), entry2, entry1)));
assertEquals("1,2", titlesOf(sortBy(latestToEarliest(), entry2, entry1)));
}
@Test
public void checkIdEqualsPredicate(){
Entry entry1 = create("1").withId("1").instance();
Entry entry2 = create("2").withId("2").instance();
Entry entry3 = create("3").withId("3").instance();
assertEquals("1", titlesOf(filterBy(idEquals("1"), entry1, entry2, entry3)));
assertEquals("2", titlesOf(filterBy(idEquals("2"), entry1, entry2, entry3)));
assertEquals("3", titlesOf(filterBy(idEquals("3"), entry1, entry2, entry3)));
}
@Test
public void checkHasCategoryPredicate(){
Entry entry1 = create("1").withCategories("A", "B").instance();
Entry entry2 = create("2").withCategory("B").instance();
Entry entry3 = create("3").withCategories("A", "B", "C").instance();
assertEquals("1,3", titlesOf(filterBy(haveACategoryOf("A"), entry1, entry2, entry3)));
assertEquals("1,2,3", titlesOf(filterBy(haveACategoryOf("B"), entry1, entry2, entry3)));
assertEquals("3", titlesOf(filterBy(haveACategoryOf("C"), entry1, entry2, entry3)));
assertEquals("1,2,3", titlesOf(filterBy(haveACategoryOf("B","C"), entry1, entry2, entry3)));
assertEquals("1,2,3", titlesOf(filterBy(haveACategoryOf("A", "B","C"), entry1, entry2, entry3)));
}
@Test
public void checkDontHaveCategoryPredicate(){
Entry entry1 = create("1").withCategories("A", "B").instance();
Entry entry2 = create("2").withCategory("B").instance();
Entry entry3 = create("3").withCategories("A", "B", "C").instance();
assertEquals("2", titlesOf(filterBy(dontHaveCategory("A"), entry1, entry2, entry3)));
assertEquals("", titlesOf(filterBy(dontHaveCategory("B"), entry1, entry2, entry3)));
assertEquals("1,2", titlesOf(filterBy(dontHaveCategory("C"), entry1, entry2, entry3)));
assertEquals("", titlesOf(filterBy(dontHaveCategory("B","C"), entry1, entry2, entry3)));
assertEquals("", titlesOf(filterBy(dontHaveCategory("A", "B","C"), entry1, entry2, entry3)));
}
@Test
public void checkContentHasMediaTypePredicate(){
Entry entry1 = create("1").withMediaType(MediaType.TEXT_HTML).instance();
Entry entry2 = create("2").withMediaType(MediaType.APPLICATION_JSON).instance();
Entry entry3 = create("3").withMediaType(MediaType.TEXT_HTML).instance();
assertEquals("2", titlesOf(filterBy(contentHasMediaType(MediaType.APPLICATION_JSON_TYPE), entry1, entry2, entry3)));
assertEquals("1,3", titlesOf(filterBy(contentHasMediaType(MediaType.TEXT_HTML_TYPE), entry1, entry2, entry3)));
assertEquals("", titlesOf(filterBy(contentHasMediaType(MediaType.APPLICATION_SVG_XML_TYPE), entry1, entry2, entry3)));
}
private static <D> List<D> sortBy(Comparator<? super D> comparator, D... entries){
List<D> list = Lists.newArrayList(entries);
sort(list, comparator);
return list;
}
private static <D> Collection<D> filterBy(Predicate<? super D> predicate, D... entries){
List<D> list = Lists.newArrayList(entries);
return Collections2.filter(list, predicate);
}
private static String titlesOf(Collection<Entry> entries){
Collection<String> titles = Collections2.transform(entries, new Function<Entry, String>() {
public String apply(Entry input) {
return input.getTitle();
}
});
return Joiner.on(",").join(titles);
}
}
| 50.413534
| 126
| 0.677256
|
895ae64b0ad751545972b81faf0a77a942d43597
| 1,689
|
package com.gikk.twirk.types.cheer;
import java.util.Objects;
/**
*
* @author Gikkman
*/
public class CheerImpl implements Cheer{
private final static String ROOT_URL = "static-cdn.jtvnw.net/bits/<theme>/<type>/<color>/<size>";
private final int bits;
private final String message;
public CheerImpl(int bits, String message) {
this.bits = bits;
this.message = message;
}
@Override
public int getBits() {
return bits;
}
@Override
public String getMessage() {
return message;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Cheer)) {
return false;
}
Cheer other = (Cheer) obj;
return bits == other.getBits() && message.equals(other.getMessage());
}
@Override
public int hashCode() {
int hash = 5;
hash = 17 * hash + this.bits;
hash = 17 * hash + Objects.hashCode(this.message);
return hash;
}
@Override
public String getImageURL(CheerTheme theme, CheerType type, CheerSize size) {
String color;
if(bits < 100){
color = "gray";
}
else if( bits < 1000) {
color = "purple";
} else if( bits < 5000) {
color = "green";
} else if( bits < 10000) {
color = "blue";
} else {
color = "red";
}
StringBuilder b = new StringBuilder(ROOT_URL);
b.append("/").append(theme.getValue())
.append("/").append(type.getValue())
.append("/").append(color)
.append("/").append(size.getValue());
return b.toString();
}
}
| 24.128571
| 101
| 0.542925
|
435d102cc10cc631a901b4b36d0682a02ea6f6fe
| 1,693
|
package blackbird.core.network;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import blackbird.core.Connection;
/**
* Connection implementation for communication via network sockets.
*/
public class NetworkConnection extends Connection {
private Socket socket;
/**
* Creates a connection using a connected socket
*
* @param socket the socket this connection is based on
* @throws IOException if the socket is either closed, unbound or not connected.
*/
public NetworkConnection(Socket socket) throws IOException {
if (socket.isClosed() || !socket.isBound() || !socket.isConnected())
throw new IOException("NetworkConnection expects a not closed, bound and connected socket");
this.socket = socket;
}
@Override
public void close() throws IOException {
socket.close();
}
@Override
public InputStream getInputStream() throws IOException {
return socket.getInputStream();
}
@Override
public OutputStream getOutputStream() throws IOException {
return socket.getOutputStream();
}
public Socket getSocket() {
return socket;
}
public String getSocketRemoteAddress() {
return socket.getRemoteSocketAddress().toString().substring(1);
}
@Override
public String toString() {
return "NETCON_" + hashCode() + "[" + getSocketRemoteAddress() + "]";
}
public static String getSocketText(Socket socket) {
return socket.getRemoteSocketAddress().toString().substring(1);
}
}
| 26.873016
| 105
| 0.652097
|
7ea1656ef9161b82641ed387faa5bd1cce768430
| 6,759
|
/*******************************************************************************
* 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 reciter.xml.retriever.pubmed;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import org.apache.commons.lang3.StringUtils;
import reciter.model.identity.AuthorName;
import reciter.pubmed.retriever.PubMedQuery;
public class PubMedQueryType {
// Query that tends to return more results than the strict query.
private PubMedQueryResult lenientQuery;
// QUery that tends to return less results than the lenient query.
private PubMedQueryResult strictQuery;
private PubMedQueryResult lenientCountQuery;
private PubMedQueryResult strictCountQuery;
public PubMedQueryResult getLenientQuery() {
return lenientQuery;
}
public void setLenientQuery(PubMedQueryResult lenientQuery) {
this.lenientQuery = lenientQuery;
}
public PubMedQueryResult getStrictQuery() {
return strictQuery;
}
public void setStrictQuery(PubMedQueryResult strictQuery) {
this.strictQuery = strictQuery;
}
public PubMedQueryResult getLenientCountQuery() {
return lenientCountQuery;
}
public void setLenientCountQuery(PubMedQueryResult lenientCountQuery) {
this.lenientCountQuery = lenientCountQuery;
}
public PubMedQueryResult getStrictCountQuery() {
return strictCountQuery;
}
public void setStrictCountQuery(PubMedQueryResult strictCountQuery) {
this.strictCountQuery = strictCountQuery;
}
@Override
public String toString() {
return "PubMedQueryType [lenientQuery=" + lenientQuery + ", strictQuery=" + strictQuery + ", lenientCountQuery=" + lenientCountQuery + ", strictCountQuery=" + strictCountQuery + "]";
}
/**
* PubMed Query builder class for constructing a PubMed query.
*/
public static class PubMedQueryBuilder {
private String lastName;
private String firstName;
private Set<AuthorName> identityAuthorNames;
private boolean isAuthorRequired;
private boolean isAuthorFullNameRequired;
// TODO update to LocalDate
private Date startDate;
private Date endDate;
private boolean isDateRangeRequired;
private String strategyQuery;
private List<Long> pmids;
public PubMedQueryBuilder() {}
public PubMedQueryBuilder(String strategyQuery) {
this.strategyQuery = strategyQuery;
}
public PubMedQueryBuilder(List<Long> pmids) {
this.pmids = pmids;
}
public PubMedQueryBuilder author(boolean isAuthorRequired, boolean isAuthorFullNameRequired, Set<AuthorName> authorNames) {
this.isAuthorRequired = isAuthorRequired;
this.isAuthorFullNameRequired = isAuthorFullNameRequired;
//this.lastName = lastName;
//this.firstName = firstName;
this.identityAuthorNames = authorNames;
return this;
}
public PubMedQueryBuilder dateRange(boolean isDateRangeRequired, Date startDate, Date endDate) {
this.isDateRangeRequired = isDateRangeRequired;
this.startDate = startDate;
this.endDate = endDate;
return this;
}
public PubMedQuery build() {
PubMedQuery p = PubMedQuery.builder().build();
if (isAuthorRequired) {
//p.setAuthor(lastName + " " + firstName);
p.setAuthor(contsructAuthorQuery());
}
if (isDateRangeRequired) {
p.setStart(startDate);
p.setEnd(endDate);
}
if (strategyQuery != null && !strategyQuery.isEmpty()) {
p.setStrategyQuery(strategyQuery);
}
return p;
}
public PubMedQuery buildPmids(List<Long> pmids) {
List<String> pmidsUid = new ArrayList<>();
for (long pmid : pmids) {
//Commented using of OR with [uid] since it was causing issue with GoldStandardRetreivalStrategy if number of pmid used was bigger than 100
//pmidsUid.add(pmid + "[uid]");
pmidsUid.add( Long.toString(pmid));
}
PubMedQuery p = PubMedQuery.builder().strategyQuery(StringUtils.join(pmidsUid, ",")).build();
//PubMedQuery p = PubMedQuery.builder().strategyQuery(pmidsUid.toString()).build();
return p;
}
public String contsructAuthorQuery() {
if (this.identityAuthorNames != null && this.identityAuthorNames.size() > 0) {
// Below is code from Apache's StringUtils class, modified to remove null checks.
Iterator<AuthorName> iterator = this.identityAuthorNames.iterator();
final AuthorName first = iterator.next();
String firstName = first.getLastName() + " " + first.getFirstInitial() + "[au]";
if(this.isAuthorFullNameRequired) {
firstName = first.getLastName() + " " + first.getFirstName() + "[au]";
}
if (!iterator.hasNext()) {
return firstName;
}
// two or more elements
final StringBuilder buf = new StringBuilder();
if (first != null) {
buf.append("(" + firstName);
}
while (iterator.hasNext()) {
buf.append(" OR ");
final AuthorName obj = iterator.next();
if(this.isAuthorFullNameRequired) { //For FullName Strict retrieval strategy
buf.append(obj.getLastName() + " " + obj.getFirstName() + "[au]");
} else {
buf.append(obj.getLastName() + " " + obj.getFirstInitial() + "[au]");
}
}
buf.append(")");
return buf.toString();
} else {
return null;
}
}
// private static final int THRESHOLD = 25;
//
// public Map<String, Integer> buildPmids() {
// if (pmids.size() == 1) {
// Map<String, Integer> map = new HashMap<>();
// map.put(pmids.get(0) + "[uid]", 1);
// return map;
// }
// Map<String, Integer> map = new HashMap<>();
// List<Long> partPmids = new ArrayList<>();
// int i = 1;
// Iterator<Long> itr = pmids.iterator();
// while (itr.hasNext()) {
// long pmid = itr.next();
// partPmids.add(pmid);
// if (i % THRESHOLD == 0) {
// map.put(buildPmid(partPmids), THRESHOLD);
// partPmids.clear();
// }
// i++;
// }
// if (!partPmids.isEmpty()) {
// map.put(buildPmid(partPmids), partPmids.size());
// }
// return map;
// }
}
}
| 30.863014
| 184
| 0.684273
|
9167af14ac39e42698511cf51e7a7bfbfefd3004
| 510
|
package com.osrsstreamers.handler;
import lombok.*;
import java.time.ZonedDateTime;
@Data
public class NearbyPlayer {
ZonedDateTime lastSeen;
StreamStatus status;
String twitchName;
public NearbyPlayer(String twitchName) {
this.status = StreamStatus.STREAMER;
this.twitchName = twitchName;
this.lastSeen = ZonedDateTime.now();
}
public NearbyPlayer() {
this.status = StreamStatus.NOT_STREAMER;
this.lastSeen = ZonedDateTime.now();
}
}
| 19.615385
| 48
| 0.680392
|
4d73feb14cdfb935ac230ebc90173a740ebd92fa
| 209
|
package lodVader.mongodb.collections.toplinks;
public class TopValidLinks extends SuperTop {
public static String COLLECTION_NAME = "TopValidLinks";
public TopValidLinks() {
super(COLLECTION_NAME);
}
}
| 20.9
| 56
| 0.789474
|
760ed8b5124701391af901711e051e9d9c9bb771
| 1,035
|
/*
* Copyright (c) 2016 PrivatBank IT <acsk@privatbank.ua>. All rights reserved.
* Redistribution and modifications are permitted subject to BSD license.
*/
package ua.privatbank.cryptonite.jnr.pkix;
import jnr.ffi.Pointer;
import jnr.ffi.mapper.FromNativeContext;
import jnr.ffi.mapper.FromNativeConverter;
import jnr.ffi.mapper.ToNativeContext;
import jnr.ffi.mapper.ToNativeConverter;
public final class OcspResponseEnginePointer {
private final Pointer pointer;
public OcspResponseEnginePointer(Pointer pointer) {
this.pointer = pointer;
}
@ToNativeConverter.ToNative(nativeType = Pointer.class)
public static Pointer toNative(OcspResponseEnginePointer value, ToNativeContext context) {
return value != null ? value.pointer : null;
}
@FromNativeConverter.FromNative(nativeType = Pointer.class)
public static OcspResponseEnginePointer fromNative(Pointer value, FromNativeContext context) {
return value != null ? new OcspResponseEnginePointer(value) : null;
}
}
| 32.34375
| 98
| 0.761353
|
d863896c9617d8631bad1146a3cae5f42d8833b9
| 3,632
|
package cn.fulushan.fuhttp.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.fulushan.fuhttp.R;
import cn.fulushan.fuhttp.activity.ReTrofitActivity;
import cn.fulushan.fuhttp.activity.ReTrofitRxJavaActivity;
import cn.fulushan.fuhttp.fragment.base.BaseFragment;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link HomeFragment} interface
* to handle interaction events.
* Use the {@link HomeFragment#} factory method to
* create an instance of this fragment.
*/
public class HomeFragment extends BaseFragment {
Unbinder unbinder;
@BindView(R.id.listView)
ListView listView;
public static final String[] datas = new String[]{
"ReTrofit基本使用","ReTrofit+Rxjava"};
@BindView(R.id.toolbar_title)
TextView toolbarTitle;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
unbinder = ButterKnife.bind(this, view);
toolbarTitle.setText(R.string.app_name);
listView.setAdapter(new MainAdapter());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
doClick(position);
}
});
return view;
}
private void doClick(int position) {
switch (position) {
/* Fragment fuHttp */
case 0:// 项目中请使用常量替代
startActivity(new Intent(getActivity(), ReTrofitActivity.class));
break;
case 1:// 项目中请使用常量替代
startActivity(new Intent(getActivity(), ReTrofitRxJavaActivity.class));
break;
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
public class MainAdapter extends BaseAdapter {
@Override
public int getCount() {
return datas.length;
}
@Override
public Object getItem(int position) {
return datas[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder mViewHolder;
if (convertView == null) {
mViewHolder = new ViewHolder();
View mView = getLayoutInflater().inflate(R.layout.listview_main, parent, false);
mViewHolder.mTextView = (TextView) mView.findViewById(R.id.content);
mView.setTag(mViewHolder);
convertView = mView;
} else {
mViewHolder = (ViewHolder) convertView.getTag();
}
mViewHolder.mTextView.setText(datas[position]);
return convertView;
}
}
class ViewHolder {
TextView mTextView;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
| 26.903704
| 96
| 0.633535
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.