text stringlengths 10 2.72M |
|---|
package Templates;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class LimitDocument extends PlainDocument {
/**
*
*/
private static final long serialVersionUID = 1L;
private int limit;
private boolean isNumerical = false;
public LimitDocument(int limit) {
super();
this.limit = limit;
}
public void insertString( int offset, String str, AttributeSet attr ) throws BadLocationException {
if (str == null) return;
if (isNumerical) {
try {
Integer.parseInt(str);
}
catch (Exception e) {
return;
}
}
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
public void setNumerical(boolean isNumber) {
isNumerical = isNumber;
}
} |
package state;
import java.awt.Color;
/**
* Абстрактен клас, който дефинира интерфейса за поведението на
* конкретно състояние на Context.
*/
public abstract class State {
public abstract void handlePush(Context c);
public abstract void handlePull(Context c);
public abstract Color getColor();
}
|
package com.tony.service;
import java.util.List;
import com.tony.model.ColorModel;
public interface ColorService {
public List<ColorModel> queryAllColor();
public int updateColor(ColorModel colorModel);
public List<ColorModel> queryColorBySampleid(int sampleid);
}
|
package com.example.km.genericapp.viewholders;
import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.km.genericapp.R;
import com.example.km.genericapp.models.navigation.NavigationDrawerItem;
/**
* NavigationViewHolder Class.
*/
public class NavigationViewHolder {
private Context context;
private ImageView imageView;
private TextView textView;
public NavigationViewHolder(final Context context, View view) {
this.context = context;
initialiseView(view);
}
public void bindView(final NavigationDrawerItem navigationDrawerItem) {
imageView.setImageResource(navigationDrawerItem.icon);
textView.setText(navigationDrawerItem.name);
}
private void initialiseView(View view) {
imageView = (ImageView) view.findViewById(R.id.imageViewIcon);
textView = (TextView) view.findViewById(R.id.textViewName);
}
}
|
/**
*
*/
package com.oriaxx77.javaplay.algorythms.search;
/**
* QucikSearch algorythm implementation.
* @author BagyuraI
*
*/
public class RecursiveQuickSearch
{
/*
Pseudocode>
search( array, startIdx, endIdx, el)
{
1) Nothing to search in
if ( endInx < startIdx )
return -1 or insertion point. return with -(low+1)
2) Choose a pivot
pivot <- Choolse a pivot. e.g. start + (end-start)/2
3) examine the element at pivot
if ( el < array[pivot] )
return search( array, startIdx, pivot-1 )
else ( el > array[pivot] )
return search( array, pivot+1, endIdx )
else
return array[pivot]
}
*/
/**
* Number array to search in.
*/
private int[] numbers;
/**
* Creates a QuickSearch that can search in the provided numbers param.
* @param numbers Number array to search in.
*/
public RecursiveQuickSearch( int[] numbers )
{
this.numbers = numbers;
}
/**
* Search for the given number and returns with the position in the {@link #numbers}
* array or with -1 if it is not found.
* @param number Number to search for.
* @return the position of the provided number in teh {@link #numbers} array or -1 if not found.
*/
public int find( int number )
{
return find( number, 0, numbers.length- 1);
}
/**
* Search in a subset of the {@link #numbers}
* @param number umber Number to search for.
* @param from start index of the {@link #numbers} subset.
* @param to end index of the {@link #numbers} subset.
* @return
*/
private int find( int number, int from , int to )
{
if ( to < from )
return -(from+1);
int mid = from + (to - from) /2;
if ( number < numbers[mid] )
{
return find( number, from, mid-1 );
}
else if ( numbers[mid] < number )
{
return find( number, mid+1, to );
}
else
{
return mid;
}
}
/**
* Runs the quicksearch example.
* @param args
*/
public static void main(String[] args)
{
int[] numbers = new int[]{ 2,3,4,5,11,48,119 };
int [] numbersToFind = new int[]{ 5, 6 };
for ( int numberToFind : numbersToFind )
{
int idx = new RecursiveQuickSearch( numbers ).find( numberToFind );
System.out.println( "Numbers: " + intArrayToString( numbers ) ); // Note: use the Arrays.toString( int[] );
System.out.println( "Searching for: " + numberToFind );
System.out.println( "Index: " + idx );
}
}
/**
* Returns the string representation of an integer array.
* @param array int array to convert
* @return The string representation of an integer array.
*/
private static String intArrayToString(int[] array )
{
StringBuilder sb = new StringBuilder();
for ( int i: array )
sb.append( i ).append( ", " );
return sb.toString();
}
}
|
package com.adventurpriseme.castme.CustomGridView;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.adventurpriseme.castme.R;
/**
* Created by Timothy on 12/27/2014.
* Copyright 12/27/2014 adventurpriseme.com
*/
public class CustomGridAdapter
extends BaseAdapter
{
private final String[] gridValues;
private Context context;
//Constructor to initialize values
public CustomGridAdapter (Context context, String[] gridValues)
{
this.context = context;
this.gridValues = gridValues;
}
@Override
public int getCount ()
{
// Number of times getView method call depends upon gridValues.length
return gridValues.length;
}
@Override
public Object getItem (int i)
{
return null;
}
@Override
public long getItemId (int i)
{
return 0;
}
@Override
// Number of times getView method call depends upon gridValues.length
public View getView (int position, View convertView, ViewGroup parent)
{
// LayoutInflator to call external grid_item.xml file
LayoutInflater inflater = (LayoutInflater) context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null)
{
gridView = new View (context);
// get layout from grid_item.xml ( Defined Below )
gridView = inflater.inflate (R.layout.grid_item, null);
// set value into textview
TextView textView = (TextView) gridView.findViewById (R.id.grid_item_label);
textView.setText (gridValues[position]);
// set image based on selected text
ImageView imageView = (ImageView) gridView.findViewById (R.id.grid_item_image);
String arrLabel = gridValues[position];
if (arrLabel.equals ("Trivia"))
{
imageView.setImageResource (R.drawable.logo_triviacast);
}
else
{
imageView.setImageResource (R.drawable.ic_castme_logo); // FIXME: Make a better resource
}
}
else
{
gridView = (View) convertView;
}
return gridView;
}
}
|
package com.guang.bishe.domain;
import java.util.ArrayList;
import java.util.List;
public class UserExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public UserExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andUserIdIsNull() {
addCriterion("user_id is null");
return (Criteria) this;
}
public Criteria andUserIdIsNotNull() {
addCriterion("user_id is not null");
return (Criteria) this;
}
public Criteria andUserIdEqualTo(Long value) {
addCriterion("user_id =", value, "userId");
return (Criteria) this;
}
public Criteria andUserIdNotEqualTo(Long value) {
addCriterion("user_id <>", value, "userId");
return (Criteria) this;
}
public Criteria andUserIdGreaterThan(Long value) {
addCriterion("user_id >", value, "userId");
return (Criteria) this;
}
public Criteria andUserIdGreaterThanOrEqualTo(Long value) {
addCriterion("user_id >=", value, "userId");
return (Criteria) this;
}
public Criteria andUserIdLessThan(Long value) {
addCriterion("user_id <", value, "userId");
return (Criteria) this;
}
public Criteria andUserIdLessThanOrEqualTo(Long value) {
addCriterion("user_id <=", value, "userId");
return (Criteria) this;
}
public Criteria andUserIdIn(List<Long> values) {
addCriterion("user_id in", values, "userId");
return (Criteria) this;
}
public Criteria andUserIdNotIn(List<Long> values) {
addCriterion("user_id not in", values, "userId");
return (Criteria) this;
}
public Criteria andUserIdBetween(Long value1, Long value2) {
addCriterion("user_id between", value1, value2, "userId");
return (Criteria) this;
}
public Criteria andUserIdNotBetween(Long value1, Long value2) {
addCriterion("user_id not between", value1, value2, "userId");
return (Criteria) this;
}
public Criteria andUserEmailIsNull() {
addCriterion("user_email is null");
return (Criteria) this;
}
public Criteria andUserEmailIsNotNull() {
addCriterion("user_email is not null");
return (Criteria) this;
}
public Criteria andUserEmailEqualTo(String value) {
addCriterion("user_email =", value, "userEmail");
return (Criteria) this;
}
public Criteria andUserEmailNotEqualTo(String value) {
addCriterion("user_email <>", value, "userEmail");
return (Criteria) this;
}
public Criteria andUserEmailGreaterThan(String value) {
addCriterion("user_email >", value, "userEmail");
return (Criteria) this;
}
public Criteria andUserEmailGreaterThanOrEqualTo(String value) {
addCriterion("user_email >=", value, "userEmail");
return (Criteria) this;
}
public Criteria andUserEmailLessThan(String value) {
addCriterion("user_email <", value, "userEmail");
return (Criteria) this;
}
public Criteria andUserEmailLessThanOrEqualTo(String value) {
addCriterion("user_email <=", value, "userEmail");
return (Criteria) this;
}
public Criteria andUserEmailLike(String value) {
addCriterion("user_email like", value, "userEmail");
return (Criteria) this;
}
public Criteria andUserEmailNotLike(String value) {
addCriterion("user_email not like", value, "userEmail");
return (Criteria) this;
}
public Criteria andUserEmailIn(List<String> values) {
addCriterion("user_email in", values, "userEmail");
return (Criteria) this;
}
public Criteria andUserEmailNotIn(List<String> values) {
addCriterion("user_email not in", values, "userEmail");
return (Criteria) this;
}
public Criteria andUserEmailBetween(String value1, String value2) {
addCriterion("user_email between", value1, value2, "userEmail");
return (Criteria) this;
}
public Criteria andUserEmailNotBetween(String value1, String value2) {
addCriterion("user_email not between", value1, value2, "userEmail");
return (Criteria) this;
}
public Criteria andUserPasswordIsNull() {
addCriterion("user_password is null");
return (Criteria) this;
}
public Criteria andUserPasswordIsNotNull() {
addCriterion("user_password is not null");
return (Criteria) this;
}
public Criteria andUserPasswordEqualTo(String value) {
addCriterion("user_password =", value, "userPassword");
return (Criteria) this;
}
public Criteria andUserPasswordNotEqualTo(String value) {
addCriterion("user_password <>", value, "userPassword");
return (Criteria) this;
}
public Criteria andUserPasswordGreaterThan(String value) {
addCriterion("user_password >", value, "userPassword");
return (Criteria) this;
}
public Criteria andUserPasswordGreaterThanOrEqualTo(String value) {
addCriterion("user_password >=", value, "userPassword");
return (Criteria) this;
}
public Criteria andUserPasswordLessThan(String value) {
addCriterion("user_password <", value, "userPassword");
return (Criteria) this;
}
public Criteria andUserPasswordLessThanOrEqualTo(String value) {
addCriterion("user_password <=", value, "userPassword");
return (Criteria) this;
}
public Criteria andUserPasswordLike(String value) {
addCriterion("user_password like", value, "userPassword");
return (Criteria) this;
}
public Criteria andUserPasswordNotLike(String value) {
addCriterion("user_password not like", value, "userPassword");
return (Criteria) this;
}
public Criteria andUserPasswordIn(List<String> values) {
addCriterion("user_password in", values, "userPassword");
return (Criteria) this;
}
public Criteria andUserPasswordNotIn(List<String> values) {
addCriterion("user_password not in", values, "userPassword");
return (Criteria) this;
}
public Criteria andUserPasswordBetween(String value1, String value2) {
addCriterion("user_password between", value1, value2, "userPassword");
return (Criteria) this;
}
public Criteria andUserPasswordNotBetween(String value1, String value2) {
addCriterion("user_password not between", value1, value2, "userPassword");
return (Criteria) this;
}
public Criteria andUserNicknameIsNull() {
addCriterion("user_nickname is null");
return (Criteria) this;
}
public Criteria andUserNicknameIsNotNull() {
addCriterion("user_nickname is not null");
return (Criteria) this;
}
public Criteria andUserNicknameEqualTo(String value) {
addCriterion("user_nickname =", value, "userNickname");
return (Criteria) this;
}
public Criteria andUserNicknameNotEqualTo(String value) {
addCriterion("user_nickname <>", value, "userNickname");
return (Criteria) this;
}
public Criteria andUserNicknameGreaterThan(String value) {
addCriterion("user_nickname >", value, "userNickname");
return (Criteria) this;
}
public Criteria andUserNicknameGreaterThanOrEqualTo(String value) {
addCriterion("user_nickname >=", value, "userNickname");
return (Criteria) this;
}
public Criteria andUserNicknameLessThan(String value) {
addCriterion("user_nickname <", value, "userNickname");
return (Criteria) this;
}
public Criteria andUserNicknameLessThanOrEqualTo(String value) {
addCriterion("user_nickname <=", value, "userNickname");
return (Criteria) this;
}
public Criteria andUserNicknameLike(String value) {
addCriterion("user_nickname like", value, "userNickname");
return (Criteria) this;
}
public Criteria andUserNicknameNotLike(String value) {
addCriterion("user_nickname not like", value, "userNickname");
return (Criteria) this;
}
public Criteria andUserNicknameIn(List<String> values) {
addCriterion("user_nickname in", values, "userNickname");
return (Criteria) this;
}
public Criteria andUserNicknameNotIn(List<String> values) {
addCriterion("user_nickname not in", values, "userNickname");
return (Criteria) this;
}
public Criteria andUserNicknameBetween(String value1, String value2) {
addCriterion("user_nickname between", value1, value2, "userNickname");
return (Criteria) this;
}
public Criteria andUserNicknameNotBetween(String value1, String value2) {
addCriterion("user_nickname not between", value1, value2, "userNickname");
return (Criteria) this;
}
public Criteria andUserRealnameIsNull() {
addCriterion("user_realname is null");
return (Criteria) this;
}
public Criteria andUserRealnameIsNotNull() {
addCriterion("user_realname is not null");
return (Criteria) this;
}
public Criteria andUserRealnameEqualTo(String value) {
addCriterion("user_realname =", value, "userRealname");
return (Criteria) this;
}
public Criteria andUserRealnameNotEqualTo(String value) {
addCriterion("user_realname <>", value, "userRealname");
return (Criteria) this;
}
public Criteria andUserRealnameGreaterThan(String value) {
addCriterion("user_realname >", value, "userRealname");
return (Criteria) this;
}
public Criteria andUserRealnameGreaterThanOrEqualTo(String value) {
addCriterion("user_realname >=", value, "userRealname");
return (Criteria) this;
}
public Criteria andUserRealnameLessThan(String value) {
addCriterion("user_realname <", value, "userRealname");
return (Criteria) this;
}
public Criteria andUserRealnameLessThanOrEqualTo(String value) {
addCriterion("user_realname <=", value, "userRealname");
return (Criteria) this;
}
public Criteria andUserRealnameLike(String value) {
addCriterion("user_realname like", value, "userRealname");
return (Criteria) this;
}
public Criteria andUserRealnameNotLike(String value) {
addCriterion("user_realname not like", value, "userRealname");
return (Criteria) this;
}
public Criteria andUserRealnameIn(List<String> values) {
addCriterion("user_realname in", values, "userRealname");
return (Criteria) this;
}
public Criteria andUserRealnameNotIn(List<String> values) {
addCriterion("user_realname not in", values, "userRealname");
return (Criteria) this;
}
public Criteria andUserRealnameBetween(String value1, String value2) {
addCriterion("user_realname between", value1, value2, "userRealname");
return (Criteria) this;
}
public Criteria andUserRealnameNotBetween(String value1, String value2) {
addCriterion("user_realname not between", value1, value2, "userRealname");
return (Criteria) this;
}
public Criteria andUserPhoneIsNull() {
addCriterion("user_phone is null");
return (Criteria) this;
}
public Criteria andUserPhoneIsNotNull() {
addCriterion("user_phone is not null");
return (Criteria) this;
}
public Criteria andUserPhoneEqualTo(String value) {
addCriterion("user_phone =", value, "userPhone");
return (Criteria) this;
}
public Criteria andUserPhoneNotEqualTo(String value) {
addCriterion("user_phone <>", value, "userPhone");
return (Criteria) this;
}
public Criteria andUserPhoneGreaterThan(String value) {
addCriterion("user_phone >", value, "userPhone");
return (Criteria) this;
}
public Criteria andUserPhoneGreaterThanOrEqualTo(String value) {
addCriterion("user_phone >=", value, "userPhone");
return (Criteria) this;
}
public Criteria andUserPhoneLessThan(String value) {
addCriterion("user_phone <", value, "userPhone");
return (Criteria) this;
}
public Criteria andUserPhoneLessThanOrEqualTo(String value) {
addCriterion("user_phone <=", value, "userPhone");
return (Criteria) this;
}
public Criteria andUserPhoneLike(String value) {
addCriterion("user_phone like", value, "userPhone");
return (Criteria) this;
}
public Criteria andUserPhoneNotLike(String value) {
addCriterion("user_phone not like", value, "userPhone");
return (Criteria) this;
}
public Criteria andUserPhoneIn(List<String> values) {
addCriterion("user_phone in", values, "userPhone");
return (Criteria) this;
}
public Criteria andUserPhoneNotIn(List<String> values) {
addCriterion("user_phone not in", values, "userPhone");
return (Criteria) this;
}
public Criteria andUserPhoneBetween(String value1, String value2) {
addCriterion("user_phone between", value1, value2, "userPhone");
return (Criteria) this;
}
public Criteria andUserPhoneNotBetween(String value1, String value2) {
addCriterion("user_phone not between", value1, value2, "userPhone");
return (Criteria) this;
}
public Criteria andUserRolIsNull() {
addCriterion("user_rol is null");
return (Criteria) this;
}
public Criteria andUserRolIsNotNull() {
addCriterion("user_rol is not null");
return (Criteria) this;
}
public Criteria andUserRolEqualTo(String value) {
addCriterion("user_rol =", value, "userRol");
return (Criteria) this;
}
public Criteria andUserRolNotEqualTo(String value) {
addCriterion("user_rol <>", value, "userRol");
return (Criteria) this;
}
public Criteria andUserRolGreaterThan(String value) {
addCriterion("user_rol >", value, "userRol");
return (Criteria) this;
}
public Criteria andUserRolGreaterThanOrEqualTo(String value) {
addCriterion("user_rol >=", value, "userRol");
return (Criteria) this;
}
public Criteria andUserRolLessThan(String value) {
addCriterion("user_rol <", value, "userRol");
return (Criteria) this;
}
public Criteria andUserRolLessThanOrEqualTo(String value) {
addCriterion("user_rol <=", value, "userRol");
return (Criteria) this;
}
public Criteria andUserRolLike(String value) {
addCriterion("user_rol like", value, "userRol");
return (Criteria) this;
}
public Criteria andUserRolNotLike(String value) {
addCriterion("user_rol not like", value, "userRol");
return (Criteria) this;
}
public Criteria andUserRolIn(List<String> values) {
addCriterion("user_rol in", values, "userRol");
return (Criteria) this;
}
public Criteria andUserRolNotIn(List<String> values) {
addCriterion("user_rol not in", values, "userRol");
return (Criteria) this;
}
public Criteria andUserRolBetween(String value1, String value2) {
addCriterion("user_rol between", value1, value2, "userRol");
return (Criteria) this;
}
public Criteria andUserRolNotBetween(String value1, String value2) {
addCriterion("user_rol not between", value1, value2, "userRol");
return (Criteria) this;
}
public Criteria andUserSexIsNull() {
addCriterion("user_sex is null");
return (Criteria) this;
}
public Criteria andUserSexIsNotNull() {
addCriterion("user_sex is not null");
return (Criteria) this;
}
public Criteria andUserSexEqualTo(String value) {
addCriterion("user_sex =", value, "userSex");
return (Criteria) this;
}
public Criteria andUserSexNotEqualTo(String value) {
addCriterion("user_sex <>", value, "userSex");
return (Criteria) this;
}
public Criteria andUserSexGreaterThan(String value) {
addCriterion("user_sex >", value, "userSex");
return (Criteria) this;
}
public Criteria andUserSexGreaterThanOrEqualTo(String value) {
addCriterion("user_sex >=", value, "userSex");
return (Criteria) this;
}
public Criteria andUserSexLessThan(String value) {
addCriterion("user_sex <", value, "userSex");
return (Criteria) this;
}
public Criteria andUserSexLessThanOrEqualTo(String value) {
addCriterion("user_sex <=", value, "userSex");
return (Criteria) this;
}
public Criteria andUserSexLike(String value) {
addCriterion("user_sex like", value, "userSex");
return (Criteria) this;
}
public Criteria andUserSexNotLike(String value) {
addCriterion("user_sex not like", value, "userSex");
return (Criteria) this;
}
public Criteria andUserSexIn(List<String> values) {
addCriterion("user_sex in", values, "userSex");
return (Criteria) this;
}
public Criteria andUserSexNotIn(List<String> values) {
addCriterion("user_sex not in", values, "userSex");
return (Criteria) this;
}
public Criteria andUserSexBetween(String value1, String value2) {
addCriterion("user_sex between", value1, value2, "userSex");
return (Criteria) this;
}
public Criteria andUserSexNotBetween(String value1, String value2) {
addCriterion("user_sex not between", value1, value2, "userSex");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} |
package com.daikit.graphql.meta;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Annotation for a GraphQL method parameter within a {@link GQLController}
*
* @author Thibaut Caselli
*/
@Target({ElementType.PARAMETER})
@Retention(RUNTIME)
public @interface GQLParam {
/**
* Name of the parameter. In case this annotation is not added the default
* parameter name value is the actual parameter name. If debug is not
* enabled during compilation, default parameter names will be arg0, arg1,
* arg2 etc.
*
* @return a the parameter name
*/
String value();
}
|
package slimeknights.tconstruct.tools.ranged.item;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.List;
import slimeknights.tconstruct.library.client.crosshair.Crosshairs;
import slimeknights.tconstruct.library.client.crosshair.ICrosshair;
import slimeknights.tconstruct.library.client.crosshair.ICustomCrosshairUser;
import slimeknights.tconstruct.library.materials.BowMaterialStats;
import slimeknights.tconstruct.library.materials.BowStringMaterialStats;
import slimeknights.tconstruct.library.materials.HeadMaterialStats;
import slimeknights.tconstruct.library.materials.Material;
import slimeknights.tconstruct.library.materials.MaterialTypes;
import slimeknights.tconstruct.library.tinkering.PartMaterialType;
import slimeknights.tconstruct.library.tools.ProjectileLauncherNBT;
import slimeknights.tconstruct.library.tools.ranged.BowCore;
import slimeknights.tconstruct.tools.TinkerMaterials;
import slimeknights.tconstruct.tools.TinkerTools;
import slimeknights.tconstruct.tools.ranged.TinkerRangedWeapons;
public class ShortBow extends BowCore implements ICustomCrosshairUser {
public ShortBow() {
this(PartMaterialType.bow(TinkerTools.bowLimb),
PartMaterialType.bow(TinkerTools.bowLimb),
PartMaterialType.bowstring(TinkerTools.bowString));
}
public ShortBow(PartMaterialType... requiredComponents) {
super(requiredComponents);
this.addPropertyOverride(PROPERTY_PULL_PROGRESS, pullProgressPropertyGetter);
this.addPropertyOverride(PROPERTY_IS_PULLING, isPullingPropertyGetter);
}
@Override
public int[] getRepairParts() {
return new int[] { 0, 1 };
}
@Override
public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> subItems) {
if(this.isInCreativeTab(tab)) {
addDefaultSubItems(subItems, null, null, TinkerMaterials.string);
}
}
/* Tic Tool Stuff */
@Override
public float baseProjectileDamage() {
return 0f;
}
@Override
public float damagePotential() {
return 0.7f;
}
@Override
public double attackSpeed() {
return 1.5;
}
@Override
protected float baseInaccuracy() {
return 1f;
}
@Override
public float projectileDamageModifier() {
return 0.8f;
}
@Override
public int getDrawTime() {
return 12;
}
@Override
protected List<Item> getAmmoItems() {
return TinkerRangedWeapons.getDiscoveredArrows();
}
@Override
public void onUpdate(ItemStack stack, World worldIn, Entity entityIn, int itemSlot, boolean isSelected) {
// has to be done in onUpdate because onTickUsing is too early and gets overwritten. bleh.
// shortbows are more mobile than other bows
preventSlowDown(entityIn, 0.5f);
super.onUpdate(stack, worldIn, entityIn, itemSlot, isSelected);
}
/* Data Stuff */
@Override
public ProjectileLauncherNBT buildTagData(List<Material> materials) {
ProjectileLauncherNBT data = new ProjectileLauncherNBT();
HeadMaterialStats head1 = materials.get(0).getStatsOrUnknown(MaterialTypes.HEAD);
HeadMaterialStats head2 = materials.get(1).getStatsOrUnknown(MaterialTypes.HEAD);
BowMaterialStats limb1 = materials.get(0).getStatsOrUnknown(MaterialTypes.BOW);
BowMaterialStats limb2 = materials.get(1).getStatsOrUnknown(MaterialTypes.BOW);
BowStringMaterialStats bowstring = materials.get(2).getStatsOrUnknown(MaterialTypes.BOWSTRING);
data.head(head1, head2);
data.limb(limb1, limb2);
data.bowstring(bowstring);
return data;
}
@SideOnly(Side.CLIENT)
@Override
public ICrosshair getCrosshair(ItemStack itemStack, EntityPlayer player) {
return Crosshairs.SQUARE;
}
@SideOnly(Side.CLIENT)
@Override
public float getCrosshairState(ItemStack itemStack, EntityPlayer player) {
return getDrawbackProgress(itemStack, player);
}
}
|
package obj;
/**
* Extended class of Review. Represents a Review object created for a MealPlan.
* @author KFed
*
*/
public class MealPlanReview extends Review{
/**
* The mealplan in which the Review was created for.
*/
MealPlan mp;
/**
* Constructor
* @param mp
* @param u
*/
public MealPlanReview(MealPlan mp, User u){
super(u);
this.mp = mp;
}
/**
* Returns the reviewed MealPlan.
* @return
*/
public MealPlan getMealPlan(){
return this.mp;
}
}
|
package com.example.buildpc.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.buildpc.ActivityListItem.BuildPCListMainActivity;
import com.example.buildpc.Dialog.DialogInfo;
import com.example.buildpc.Main.MainBuild;
import com.example.buildpc.Model.Model_Main;
import com.example.buildpc.R;
import com.squareup.picasso.Picasso;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class Main_Adapter extends ArrayAdapter<Model_Main> {
private Context context;
private int resource;
private ArrayList<Model_Main> model_mainsArrayList;
ImageButton icon_info_main;
DialogInfo dialogInfo;
public Main_Adapter(@NonNull Context context, int resource, @NonNull ArrayList<Model_Main> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.model_mainsArrayList = objects;
}
private String urlApi = "http://android-api.thaolx.com";
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
convertView = LayoutInflater.from(context).inflate(R.layout.buildpc_layout_main,parent,false);
ImageView imageView_main = convertView.findViewById(R.id.image_main);
TextView textView_name_main = convertView.findViewById(R.id.textView_name_main);
TextView textView_brand_main = convertView.findViewById(R.id.textView_brand_main);
TextView textView_memoryType_main = convertView.findViewById(R.id.textView_memoryType_main);
TextView textView_socket_main = convertView.findViewById(R.id.textView_socket_main);
TextView textView_price_main = convertView.findViewById(R.id.textView_price_main);
icon_info_main = convertView.findViewById(R.id.icon_info_main);
final Model_Main model_main = model_mainsArrayList.get(position);
Picasso.with(context).load(urlApi+model_main.getImageMain()).into(imageView_main);
textView_name_main.setText(model_main.getModel());
textView_brand_main.setText(model_main.getBrand());
textView_memoryType_main.setText("Support " + model_main.getMemoryType());
textView_socket_main.setText(model_main.getSocket());
String s = (new DecimalFormat("#,###.##"+" VNĐ")).format(model_main.getPrice());
textView_price_main.setText(s);
icon_info_main.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialogInfo.showDialog(context, BuildPCListMainActivity.getInstance(), urlApi,
model_main.getImageMain(),
model_main.getModel(),
"Hỗ trợ Socket " + model_main.getSocket(),
"Hỗ trợ RAM " + model_main.getMemoryType(),
model_main.getBrand(),
model_main.getDescription(),
model_main.getPrice());
}
});
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainBuild.cart.setMainID(model_main.getID());
BuildPCListMainActivity.getInstance().finish();
}
});
convertView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
dialogInfo.showDialog(context, BuildPCListMainActivity.getInstance(), urlApi,
model_main.getImageMain(),
model_main.getModel(),
"Hỗ trợ Socket " + model_main.getSocket(),
"Hỗ trợ RAM " + model_main.getMemoryType(),
model_main.getBrand(),
model_main.getDescription(),
model_main.getPrice());
return false;
}
});
return convertView;
}
}
|
import java.util.AbstractList;
public class ArrayList61B<E> extends AbstractList<E> {
private int size;
private E[] array;
private int numberOfElements;
public ArrayList61B(int initialCapacity) {
if (initialCapacity < 1) {
throw new IllegalArgumentException();
} else {
array = (E[]) new Object[initialCapacity];
size = initialCapacity;
numberOfElements = 0;
}
}
public ArrayList61B() {
this(1);
}
public E get(int i) {
if (i < 0 || i >= numberOfElements) {
throw new IllegalArgumentException();
} else {
return array[i];
}
}
@Override
public boolean add(E item) {
if (numberOfElements == size) {
E[] placeHolderArray = array;
array = (E[]) new Object[size*2];
for (int i = 0; i < size; i++) {
array[i] = placeHolderArray[i];
}
size = size*2;
}
array[numberOfElements] = item;
numberOfElements += 1;
return true;
}
public int size() {
return numberOfElements;
}
}
|
package style.gui;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.effect.DropShadow;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import core.Main;
public class Login {
private GridPane grid;
private Label welcome;
private Label logIn;
private Label userName;
private Label password;
private TextField user;
private PasswordField pass;
private Button login;
private Label signUp;
public Login(){
setup();
}
public GridPane setup(){
grid = new GridPane();
logIn = CreateNodes.createHeader("Log in");
welcome = CreateNodes.createLabel("Welcome");
userName = CreateNodes.createLabel("Email:");
password= CreateNodes.createLabel("Password:");
signUp = CreateNodes.createLabel("Register");
user = CreateNodes.createText();
user.setPromptText("Username");
pass = new PasswordField();
pass.setId("input");
pass.setPromptText("Password");
login = new Button("Log in");
login.setMinWidth(200);
login.setId("button");
signUp.setOnMouseClicked(e-> Main.getGUI().registerScreen());
login.setOnAction(e -> {
String uName = user.getText();
String uPass = pass.getText();
Main.getConnection().write("LOGIN#" + uName + "#" + uPass);
});
user.setText("mackan@bbb.se");
pass.setText("1234");
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(0, 10, 5, 10));
grid.add(logIn,0,0);
grid.add(userName,0,2);
grid.add(user,0,3);
grid.add(password,0,4);
grid.add(pass,0,5);
grid.add(login,0,6);
grid.add(signUp,0,7);
grid.setId("loginStyle");
grid.setMaxWidth(300);
grid.setMaxHeight(300);
DropShadow drop = new DropShadow(50, Color.GRAY);
grid.setEffect(drop);
return grid;
}
public GridPane getRoot(){
return grid;
}
} |
package tcss450.uw.edu.huskylist;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
import tcss450.uw.edu.huskylist.model.ItemContent;
/**
* Created by vsmirnov on 4/26/16.z
*/
public class ItemDB {
public static final int DB_VERSION = 4;
public static String DB_NAME;
public static String mName;
public static int ID_count;
private ItemDBHelper mItemDBHelper;
private SQLiteDatabase mSQLiteDatabase;
private static String DB_TABLE;
public ItemDB(Context context, String name) {
DB_TABLE = name;
DB_NAME = name + ".db";
mName = name;
ID_count = 0;
mItemDBHelper = new ItemDBHelper(
context, DB_NAME, null, DB_VERSION, name);
System.out.println("Name: " + mName);
switch(mName) {
case "Books":
SQLiteDatabase mBookDatabase = mItemDBHelper.getWritableDatabase();
mSQLiteDatabase = mBookDatabase;
break;
case "CellPhones":
SQLiteDatabase mCellphoneDatabase = mItemDBHelper.getWritableDatabase();
mSQLiteDatabase = mCellphoneDatabase;
break;
case "VideoGames":
SQLiteDatabase mVideoGameDatabase = mItemDBHelper.getWritableDatabase();
mSQLiteDatabase = mVideoGameDatabase;
break;
case "HouseHoldItems":
SQLiteDatabase mHouseHoldDatabase = mItemDBHelper.getWritableDatabase();
mSQLiteDatabase = mHouseHoldDatabase;
break;
case "Vehicles":
SQLiteDatabase mVehicleDatabase = mItemDBHelper.getWritableDatabase();
mSQLiteDatabase = mVehicleDatabase;
break;
case "Computers":
SQLiteDatabase mComputerDatabase = mItemDBHelper.getWritableDatabase();
mSQLiteDatabase = mComputerDatabase;
break;
}
}
public void deleteItems() {
mSQLiteDatabase.delete(DB_TABLE, null, null);
}
public List<ItemContent> getItems() {
String[] columns = {
"ItemID", "SellerUserName", "ItemTitle", "ItemPrice", "ItemCond", "ItemDesc", "SellerLocation", "SellerContact"
};
Cursor c = mSQLiteDatabase.query(
DB_TABLE, // The table to query
columns, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
);
c.moveToFirst();
List<ItemContent> list = new ArrayList<ItemContent>();
for (int i=0; i<c.getCount(); i++) {
int ItemID = c.getInt(0);
String SellerUserName = c.getString(1);
String ItemTitle = c.getString(2);
String ItemPrice = c.getString(3);
String ItemCond = c.getString(4);
String ItemDesc = c.getString(5);
String SellerLocation = c.getString(6);
String SellerContact = c.getString(7);
ItemContent item = new ItemContent(SellerUserName, ItemTitle, ItemPrice, ItemCond, ItemDesc, SellerLocation, SellerContact);
item.setItemId(ItemID);
list.add(item);
c.moveToNext();
}
// System.out.println(mName + " " + c.getCount());
return list;
}
public boolean insertItem(int ItemID, String SellerUserName, String ItemTitle, String ItemPrice, String ItemCond, String ItemDesc, String SellerLocation, String SellerContact) {
ContentValues contentValues = new ContentValues();
contentValues.put("ItemID", ItemID);
contentValues.put("SellerUserName", SellerUserName);
contentValues.put("ItemTitle", ItemTitle);
contentValues.put("ItemPrice", ItemPrice);
contentValues.put("ItemCond", ItemCond);
contentValues.put("ItemDesc", ItemDesc);
contentValues.put("SellerLocation", SellerLocation);
contentValues.put("SellerContact", SellerContact);
long rowId = mSQLiteDatabase.insert(DB_TABLE, null, contentValues);
return rowId != -1;
}
public void closeDB() {
mSQLiteDatabase.close();
}
public class ItemDBHelper extends SQLiteOpenHelper {
private String CREATE_ITEM_SQL;
private String DROP_ITEM_SQL;
public ItemDBHelper(Context context, String DBname, SQLiteDatabase.CursorFactory factory, int version, String name) {
super(context, DBname, factory, version);
CREATE_ITEM_SQL = "CREATE TABLE IF NOT EXISTS " + name
+ " (ItemID INTEGER PRIMARY KEY, SellerUserName TEXT, ItemTitle TEXT, ItemPrice TEXT, ItemCond TEXT, ItemDesc TEXT, SellerLocation TEXT, SellerContact TEXT)";
DROP_ITEM_SQL = "DROP TABLE IF EXISTS " + name;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_ITEM_SQL);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL(DROP_ITEM_SQL);
onCreate(sqLiteDatabase);
}
}
}
|
package com.alibaba.druid.bvt.bug;
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import junit.framework.TestCase;
public class Issue4071 extends TestCase {
public void test_for_issue() throws Exception {
assertEquals("", new SQLSelectStatement().toString());
}
}
|
package com.project.springboot.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.project.springboot.entity.Customer;
public interface CustomerRepository extends JpaRepository<Customer, Integer>{
}
|
package Bai2;
import java.util.Scanner;
public class NhanVien {
public String chucVu;
public String caTruc;
String hoTen;
double luong;
int namSinh;
Scanner scanner = new Scanner(System.in);
private Scanner sc;
private int tuoi;
public NhanVien(){
}
public NhanVien(String hoTen, double luong, int namSinh) {
super();
this.hoTen = hoTen;
this.luong = luong;
this.namSinh = namSinh;
}
public String gethoTen()
{
return hoTen;
}
public void sethoTen(String hoTen) {
this.hoTen = hoTen;
}
public int getnamSinh()
{
return namSinh;
}
public double getluong()
{
return luong;
}
public void nhap()
{
sc = new Scanner(System.in);
System.out.print("Nhập họ tên: ");
hoTen = sc.nextLine();
System.out.print("Nhập lương: ");
luong = sc.nextDouble();
do
{
System.out.print("Nhập năm sinh (Phải sinh trước năm 2001(Đủ 18 tuổi mới cho làm =)))) \n ");
namSinh = sc.nextInt();
}while(namSinh>2001);
}
public int tinhtuoi(int tuoi) {
tuoi = 2019 - namSinh;
return tuoi;
}
public void xuat()
{
System.out.println("Họ tên: \t" + hoTen);
System.out.println("lương: \t" + luong);
System.out.println("Năm sinh: \t" + namSinh);
System.out.println("Tuổi: \t" + tinhtuoi(tuoi));
}
public String setchucVu() {
return chucVu = "quanly";
}
}
|
package ma.adria.banque.service;
import java.util.List;
import ma.adria.banque.dto.VirementMultipleDTO;
import ma.adria.banque.dto.VirementMultipleSearchDTO;
import ma.adria.banque.entities.VirementMultiple;
public interface VirementMultipleService {
public VirementMultiple save(VirementMultiple virementMultiple );
public List<VirementMultiple> findAllVirements();
public List <VirementMultipleDTO> findAllVirementMultiple(Long abonneId );
public List<VirementMultiple> findVirementsBySearch(Long idAbonne,VirementMultipleSearchDTO VMsearch);
public void signeVirement(Long idVirment);
}
|
package br.com.branquinho.jpa.pessoa.model;
public enum TipoDocumento {
CPF, RG, PASSAPORTE
}
|
package com.sap.als.persistence;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
@Entity
@NamedQueries({
@NamedQuery(name = "AllBreathTests", query = "select s from BreathTest s"),
@NamedQuery(name = "BreathTestById", query = "select s from BreathTest s where s.id = :id"),
@NamedQuery(name = "LastBreathTestByPatientId", query = "select s from BreathTest s where s.created = (select max(s1.created) from BreathTest s1 where s1.patientId = s.patientId and s.patientId = :patientId)"),
@NamedQuery(name = "SubmittedBreathCountByPatinetId", query = "select count (q) from BreathTest q where q.patientId = :patientId "),
@NamedQuery(name = "BreathTestsByPatientId", query = "select s from BreathTest s where s.patientId = :patientId")})
public class BreathTest implements Serializable , ITest {
private static final long serialVersionUID = 1L;
public BreathTest() {
}
@Id
@GeneratedValue
private long id;
private long patientId;
private Timestamp created;
@OneToMany(cascade = CascadeType.ALL)
private List<BreathTestRecording> recordings;
@OneToOne(optional=false, fetch=FetchType.EAGER)
@JoinColumn(name="PATIENTID",referencedColumnName="ID",updatable=false,insertable=false)
private Patient patientDetails;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getPatientId() {
return patientId;
}
public void setPatientId(long patientId) {
this.patientId = patientId;
}
public Timestamp getCreated() {
return created;
}
public void setCreated(Timestamp created) {
this.created = created;
}
public void setCreated(long created) {
this.created = new Timestamp( created);
}
public List<BreathTestRecording> getRecordings() {
return recordings;
}
public void setRecordings(List<BreathTestRecording> recordings) {
this.recordings = recordings;
}
public Patient getPatientDetails() {
return patientDetails;
}
public void setPatientDetails(Patient patientDetails) {
this.patientDetails = patientDetails;
}
} |
package com.pdd.pop.sdk.http.api.request;
import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty;
import com.pdd.pop.sdk.http.api.response.PddGoodsCountryGetResponse;
import com.pdd.pop.sdk.http.HttpMethod;
import com.pdd.pop.sdk.http.PopBaseHttpRequest;
import com.pdd.pop.sdk.common.util.JsonUtil;
import java.util.Map;
import java.util.TreeMap;
public class PddGoodsCountryGetRequest extends PopBaseHttpRequest<PddGoodsCountryGetResponse>{
@Override
public String getVersion() {
return "V1";
}
@Override
public String getDataType() {
return "JSON";
}
@Override
public String getType() {
return "pdd.goods.country.get";
}
@Override
public HttpMethod getHttpMethod() {
return HttpMethod.POST;
}
@Override
public Class<PddGoodsCountryGetResponse> getResponseClass() {
return PddGoodsCountryGetResponse.class;
}
@Override
public Map<String, String> getParamsMap() {
Map<String, String> paramsMap = new TreeMap<String, String>();
paramsMap.put("version", getVersion());
paramsMap.put("data_type", getDataType());
paramsMap.put("type", getType());
paramsMap.put("timestamp", getTimestamp().toString());
return paramsMap;
}
} |
package model.entities;
import java.io.Serializable;
import java.util.Objects;
public class Tipo implements Serializable {
private Integer id;
private String nome;
public Tipo() {
}
public Tipo(Integer id, String nome) {
this.id = id;
this.nome = nome;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Tipo)) return false;
Tipo tipo = (Tipo) o;
return Objects.equals(id, tipo.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "tipo{" +
"id=" + id +
", nome='" + nome + '\'' +
'}';
}
}
|
package com.beike.util.lucene;
public class LuceneUtil {
public static final double RATE_MILE_TO_KM = 1.609344; // 英里和公里的比率
private static final double MAX_RANGE = 15.0; // 索引支持的最大范围,单位是千米
private static final double MIN_RANGE = 3.0; // 索引支持的最小范围,单位是千米
public static int mile2Meter(double miles) {
double dMeter = miles * RATE_MILE_TO_KM * 1000;
return (int) dMeter;
}
public static double km2Mile(double km) {
return km / RATE_MILE_TO_KM;
}
public static double mile2KM(double miles){
return miles * RATE_MILE_TO_KM;
}
}
|
package KittyEngine.Graphics;
import android.content.Context;
import android.opengl.GLES31;
import android.opengl.GLSurfaceView;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import KittyEngine.Math.KMat4;
import KittyEngine.Math.KVec2;
public class KRenderer implements GLSurfaceView.Renderer {
KRenderer(Context context) {
m_context = context;
}
private Context m_context;
private KVec2 m_screenDimension = new KVec2(); // or resolution
private KMat4 m_screenProjection = new KMat4();
private KCamera m_camera;
private KSpriteRenderer m_SpriteRenderer;
private KHUDRenderer m_HUDRenderer;
AtomicBoolean m_bDrawFrameFinished = new AtomicBoolean(false);
public KVec2 getScreenDimension() {
return new KVec2(m_screenDimension);
}
public KMat4 getScreenProjection() {
return new KMat4(m_screenProjection);
}
public KCamera getCamera() {
return m_camera;
}
public KSpriteRenderer getSpriteRenderer() {
return m_SpriteRenderer;
}
public KHUDRenderer getHUDRenderer() {
return m_HUDRenderer;
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
m_camera = new KCamera(this);
KTexture.loadKittyTextures(m_context);
m_SpriteRenderer = new KSpriteRenderer(this);
m_HUDRenderer = new KHUDRenderer(this);
// Set the background frame color
GLES31.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
}
@Override
public void onDrawFrame(GL10 gl) {
//Redraw background color
GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
m_SpriteRenderer.render();
// hud is rendered last so it is always on top
m_HUDRenderer.render();
m_bDrawFrameFinished.set(true);
}
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
GLES31.glViewport(0, 0, width, height);
m_screenDimension.x = width;
m_screenDimension.y = height;
float[] screenProjectionArr = m_screenProjection.getArray();
screenProjectionArr[0 * 4 + 0] = 2.f / width; // scale x
screenProjectionArr[1 * 4 + 1] = 2.f / -height; // scale y
screenProjectionArr[3 * 4 + 0] = -1.f; // origin x
screenProjectionArr[3 * 4 + 1] = 1.f; // origin y
screenProjectionArr[2 * 4 + 2] = -1.f; // far
screenProjectionArr[3 * 4 + 3] = 1.f; // near
}
}
|
//accept two number from web page and display sum and average
import java.awt.*;
import java.applet.*;
public class sum_avg extends Applet
{
float sum,avg,a,b;
public void init()
{
a=Float.valueOf(getParameter("num1"));
b=Float.valueOf(getParameter("num2"));
}//close of init()
public void start()
{
sum=a+b;
avg=sum/2;
}//close of strat()
public void paint(Graphics g)
{
g.drawString("Sum of two number="+String.valueOf(sum),40,50);
g.drawString("Average value of two number="+String.valueOf(avg),40,60);
}//close of paint()
}//close of class
|
package com.git.cloud.handler.automation.os.impl;
import com.git.cloud.handler.automation.os.GetServerHandler;
/**
* 验证计算实例状态,是否已确认规格
* @author SunHailong
* @version 版本号 2017-4-3
*/
public class CheckServerConfirmResizeStatusHandler extends GetServerHandler {
protected void commonInitParam() {
}
protected boolean isOperateVmSuccess(String status) {
return status.equals("ACTIVE");
}
}
|
package com.gadget_badget.research.service;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.parser.Parser;
import com.gadget_badget.research.model.ResearchServlet;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
@Path("/Research")
public class ResearchService
{
ResearchServlet researchObj = new ResearchServlet();
@GET
@Path("/")
@Produces(MediaType.TEXT_HTML)
public String readResearch()
{
return researchObj.readResearch();
}
@POST
@Path("/")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_PLAIN)
public String insertResearch(
@FormParam("postID") String postID,
@FormParam("postTitle") String postTitle,
@FormParam("postContent") String postContent)
{
String output = researchObj.insertResearch(postID, postTitle, postContent);
return output;
}
@PUT
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public String updateResearch(String researchData)
{
//Convert the input string to a JSON object
JsonObject researchObject = new JsonParser().parse(researchData).getAsJsonObject();
//Read the values from the JSON object
String postID = researchObject.get("postID").getAsString();
String postTitle = researchObject.get("postTitle").getAsString();
String postContent = researchObject.get("postContent").getAsString();
String output = researchObj.updateResearch(postID, postTitle, postContent);
return output;
}
@DELETE
@Path("/")
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.TEXT_PLAIN)
public String deleteResearch(String researchData)
{
//Convert the input string to an XML document
Document doc = Jsoup.parse(researchData, "", Parser.xmlParser());
//Read the value from the element <itemID>
String postID = doc.select("postID").text();
String output = researchObj.deleteResearch(postID);
return output;
}
} |
package com.codekarma.repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import com.codekarma.domain.Category;
public interface CategoryRepository extends CrudRepository<Category, Integer> {
@Query("SELECT c FROM Category c WHERE name = :name")
Category getCategoryByName(@Param("name") String name);
}
|
package by.training.epam.lab8.parser;
import by.training.epam.lab8.entity.impl.Dish;
import by.training.epam.lab8.parser.exception.ParseException;
import java.util.List;
public interface IParser {
List<Dish> parse(String filePath) throws ParseException;
}
|
package main.java.handler;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import main.java.constant.ErrorConstants;
import main.java.main.Language;
public class LogHandler
{
// Writes an error message to the log file so that developers can fix the
// problem
public static void WriteErrorToLogFile(Exception e, String message)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = new Date();
try
{
File file = new File("Logs");
if (!file.exists())
{
file.mkdirs();
}
PrintWriter writer = new PrintWriter(
new FileOutputStream(new File(ErrorConstants.GetErrorLogFile()), true));
writer.println("=============================================================================");
writer.println(dateFormat.format(date));
writer.println(message);
writer.println("");
for (StackTraceElement ste : e.getStackTrace())
{
if (ste.getClassName().startsWith("main.java."))
{
writer.println(
ste.getClassName() + ", " + ste.getMethodName() + " on line :" + ste.getLineNumber());
}
}
writer.close();
}
catch (IOException ex)
{
LogHandler.WriteErrorToLogFile(ex, "IOException");
}
}
// Write the next action done to the action log file to see what the user
// has done
public static void WriteToActionLogFile()
{
// TODO
}
/**
* Shows a general warning
*
* @param warning
*/
public static void ShowWarning(String warning)
{
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Warning!");
alert.setHeaderText(warning);
}
/**
* Shows a waning screen with two buttons, cancel and another provided one
*
* @param warning
* The warning text
* @param action
* The text for the other button
* @return boolean, true if the user pressed the action button
*/
public static boolean ShowWarning(String warning, String action)
{
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Warning!");
alert.setHeaderText(warning);
ButtonType buttonTypeAction = new ButtonType(action);
ButtonType buttonTypeConfirmation = new ButtonType(Language.getTranslation("btn.cancel"));
alert.getButtonTypes().setAll(buttonTypeConfirmation, buttonTypeAction);
Optional<ButtonType> result = alert.showAndWait();
return result.get() == buttonTypeAction;
}
}
|
package learn.java.fundamentals.optional;
import java.util.Random;
import java.util.Scanner;
class SecondOptionalTask {
private static int[][] matrix;
public static void main(String[] args) {
createMatrix();
}
public static void createMatrix() {
System.out.println("Type a number to define amount of rows: ");
int rows = checkIfInputIsANumber();
System.out.println("Type a number to define amount of columns: ");
int columns = checkIfInputIsANumber();
int[][] tempMatrix = fillMatrixWithNumbers(new int[rows][columns]);
matrix = tempMatrix;
printMatrix(tempMatrix);
collectInput();
}
private static void sortRowOrColumnInMatrix(int[][] matrixToSort) {
System.out.println("What do you want to sort? Type 0 for row and 1 for column");
int input = checkIfInputIsANumber();
switch (input) {
case 0:
sortRow(matrixToSort);
break;
case 1:
sortColumn(matrixToSort);
break;
default:
System.out.println("Wrong input. Try again");
sortRowOrColumnInMatrix(matrixToSort);
break;
}
matrix = matrixToSort;
printMatrix(matrix, "This is matrix after sorting");
collectInput();
}
private static int[][] sortRow(int[][] matrix) {
int amountOfRows = matrix.length;
try {
System.out.println("Enter a number from 1 to " + amountOfRows + " to define a row you want to sort");
int rowToCheck = checkIfInputIsANumber() - 1;
int[][] matrixWithRowSorted = matrix;
int len = matrixWithRowSorted[0].length;
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - i - 1; j++) {
int firstNum = matrixWithRowSorted[rowToCheck][j];
int secondNum = matrixWithRowSorted[rowToCheck][j + 1];
if (firstNum > secondNum) {
int temporaryInteger = firstNum;
matrixWithRowSorted[rowToCheck][j] = secondNum;
matrixWithRowSorted[rowToCheck][j + 1] = temporaryInteger;
}
}
}
return matrixWithRowSorted;
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
System.out.println("Input is out of matrix's bounds. Returning original matrix");
}
return matrix;
}
private static int[][] sortColumn(int[][] matrix) {
int amountOfColumns = matrix[0].length;
try {
System.out.println("Enter a number from 1 to " + amountOfColumns + " to define a col you want to sort");
int columnWithColumnSorted = checkIfInputIsANumber() - 1;
int[][] matrixWithColumnSorted = matrix;
int len = matrixWithColumnSorted.length;
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - i - 1; j++) {
int firstNum = matrixWithColumnSorted[j][columnWithColumnSorted];
int secondNum = matrixWithColumnSorted[j + 1][columnWithColumnSorted];
if (firstNum > secondNum) {
int temporaryInteger = firstNum;
matrixWithColumnSorted[j][columnWithColumnSorted] = secondNum;
matrixWithColumnSorted[j + 1][columnWithColumnSorted] = temporaryInteger;
}
}
}
return matrixWithColumnSorted;
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
System.out.println("Input is out of matrix's bounds. Returning original matrix");
}
return matrix;
}
private static void collectInput() {
System.out.println(
"What's next?\n" +
"0. Create new matrix\n" +
"1. Sort row or col of the matrix\n" +
"Enter something but number to stop."
);
Scanner input = new Scanner(System.in);
if (input.hasNextInt()) {
switch (input.nextInt()) {
case 0 -> createMatrix();
case 1 -> sortRowOrColumnInMatrix(matrix);
case 2 -> findBiggestRowOfAscendingElements(matrix);
default -> collectInput();
}
} else {
System.out.println("End");
}
}
public static int checkIfInputIsANumber() {
Scanner scanner = new Scanner(System.in);
return scanner.hasNextInt() ? scanner.nextInt() : checkIfInputIsANumber();
}
public static String checkInputString() {
return new Scanner(System.in).nextLine();
}
public static int[][] fillMatrixWithNumbers(int[][] matrix) {
Random random = new Random();
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[0].length; column++) {
matrix[row][column] = random.nextInt();
}
}
return matrix;
}
public static void printMatrix(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[0].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println("");
}
}
public static void printMatrix(int[][] matrix, String additionalMessage) {
System.out.println(additionalMessage + "\n");
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[0].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println("");
}
}
public static void findBiggestRowOfAscendingElements(int[][] matrix) {
int maxElement;
int longestSerie = 0;
int serieToCompareWithTheLongest = 0;
for (int row = 0; row < matrix.length; row++) {
maxElement = matrix[row][0];
for (int column = 0; column < matrix[0].length; column++) {
if (matrix[row][column] > maxElement) {
maxElement = matrix[row][column];
System.out.print(maxElement + " ");
serieToCompareWithTheLongest++;
}
}
System.out.print(serieToCompareWithTheLongest);
if (longestSerie < serieToCompareWithTheLongest)
longestSerie = serieToCompareWithTheLongest;
serieToCompareWithTheLongest = 0;
System.out.println("");
}
System.out.println(longestSerie + " is the biggest amount of numbers in ascending order in rows");
collectInput();
}
}
|
package com.atlassian.theplugin.idea.autoupdate;
import com.atlassian.theplugin.commons.configuration.GeneralConfigurationBean;
import com.atlassian.theplugin.commons.util.Version;
import com.atlassian.theplugin.idea.GenericHyperlinkListener;
import com.atlassian.theplugin.util.InfoServer;
import com.atlassian.theplugin.util.PluginUtil;
import com.intellij.ide.BrowserUtil;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.ui.HyperlinkLabel;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.awt.*;
public class NewVersionInfoForm extends DialogWrapper {
private static final String DOWNLOAD_TITLE = "Downloading new version of " + PluginUtil.getInstance().getName();
private JPanel rootPane;
private JLabel versionInfoLabel;
private JPanel footerPanel;
private JEditorPane releaseNotesLabel;
private final Project project;
private final GeneralConfigurationBean updateConfiguration;
private final InfoServer.VersionInfo versionInfo;
private boolean showConfigPath;
public NewVersionInfoForm(final Project project, final GeneralConfigurationBean updateConfiguration,
final InfoServer.VersionInfo versionInfo, boolean showConfigPath) {
super(project, false);
this.updateConfiguration = updateConfiguration;
this.versionInfo = versionInfo;
this.project = project;
this.showConfigPath = showConfigPath;
initialize();
}
public NewVersionInfoForm(final Component parent, final GeneralConfigurationBean updateConfiguration,
final InfoServer.VersionInfo versionInfo, boolean showConfigPath) {
super(parent, false);
this.updateConfiguration = updateConfiguration;
this.versionInfo = versionInfo;
this.project = null;
this.showConfigPath = showConfigPath;
initialize();
}
private void initialize() {
$$$setupUI$$$();
createUIComponents();
Version aVersion = versionInfo.getVersion();
String versionInfoUpgrade = "<html>Do you want to upgrade from <b>" + PluginUtil.getInstance().getVersion() + " to <i>"
+ aVersion + "</i></b>< ?<br></html>";
setTitle("New Atlassian Connector version " + aVersion + " is available.");
setOKButtonText("Install");
versionInfoLabel.setText(versionInfoUpgrade);
StringBuilder sb = new StringBuilder();
//releaseNotesUrl.setText("<html><a href=\"" + versionInfo.getReleaseNotesUrl() + "\">Release Notes</a><br></html>");
sb.append(versionInfo.getReleaseNotes());
releaseNotesLabel.setEditable(false);
releaseNotesLabel.setContentType("text/html");
releaseNotesLabel.addHyperlinkListener(new GenericHyperlinkListener());
releaseNotesLabel.setText(sb.toString());
releaseNotesLabel.setCaretPosition(0);
init();
}
@Override
protected void doOKAction() {
Task.Backgroundable downloader = new Task.Backgroundable(project, DOWNLOAD_TITLE, false) {
public void run(@NotNull ProgressIndicator indicator) {
new PluginDownloader(versionInfo, updateConfiguration).run();
}
};
ProgressManager.getInstance().run(downloader);
dispose();
super.doOKAction();
}
@Override
public void doCancelAction() {
if (showConfigPath) {
Messages.showMessageDialog("You can always install " + versionInfo.getVersion() + " version through " + PluginUtil.getInstance().getName()
+ " configuration panel (Preferences | IDE Settings | " + PluginUtil.getInstance().getName() + " | General | Auto update | Check now)", "Information",
Messages.getInformationIcon());
}
dispose();
super.doCancelAction();
}
@Override
@Nullable
protected JComponent createCenterPanel() {
return $$$getRootComponent$$$();
}
@Override
public void dispose() {
// so or so we mark this version so no more popups will appear
updateConfiguration.setRejectedUpgrade(versionInfo.getVersion());
super.dispose();
}
private void createUIComponents() {
HyperlinkLabel label = new HyperlinkLabel("Release Notes");
label.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
BrowserUtil.launchBrowser(versionInfo.getReleaseNotesUrl());
}
});
footerPanel.setLayout(new GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
footerPanel.add(label, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
final Spacer spacer1 = new Spacer();
footerPanel.add(spacer1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL,
GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
rootPane = new JPanel();
rootPane.setLayout(new GridLayoutManager(2, 1, new Insets(10, 10, 10, 10), -1, -1));
rootPane.setMaximumSize(new Dimension(580, 466));
rootPane.setMinimumSize(new Dimension(580, 466));
rootPane.setPreferredSize(new Dimension(580, 466));
final JPanel panel1 = new JPanel();
panel1.setLayout(new FormLayout("fill:d:grow", "center:max(d;4px):noGrow,top:3dlu:noGrow,center:d:grow"));
rootPane.add(panel1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, true));
final JScrollPane scrollPane1 = new JScrollPane();
scrollPane1.setBackground(new Color(-1118482));
scrollPane1.setMinimumSize(new Dimension(-1, -1));
CellConstraints cc = new CellConstraints();
panel1.add(scrollPane1, new CellConstraints(1, 3, 1, 1, CellConstraints.FILL, CellConstraints.FILL, new Insets(5, 5, 5, 5)));
scrollPane1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), null));
releaseNotesLabel = new JEditorPane();
releaseNotesLabel.setText("");
scrollPane1.setViewportView(releaseNotesLabel);
versionInfoLabel = new JLabel();
versionInfoLabel.setText("Do you want to upgrade to the newest version?");
panel1.add(versionInfoLabel, cc.xy(1, 1));
footerPanel = new JPanel();
footerPanel.setLayout(new GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
rootPane.add(footerPanel, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return rootPane;
}
}
|
package com.lenovohit.ssm.treat.transfer.dao;
import com.alibaba.fastjson.annotation.JSONField;
import com.lenovohit.core.utils.StringUtils;
public class RestResponse {
@JSONField(name="RESULTCODE")
private String resultcode;
@JSONField(name="RESULT")
private String result;
@JSONField(name="CONTENT")
private String content;
public String getResultcode() {
return resultcode;
}
public void setResultcode(String resultcode) {
this.resultcode = resultcode;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public boolean isSuccess(){
return StringUtils.isNotBlank(resultcode)
&& StringUtils.equals("1", resultcode);
}
}
|
/*
* Ara - Capture Species and Specimen Data
*
* Copyright © 2009 INBio (Instituto Nacional de Biodiversidad).
* Heredia, Costa Rica.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.inbio.ara.facade.search;
import java.util.*;
import javax.ejb.Remote;
import org.inbio.ara.dto.gis.SiteDTO;
import org.inbio.ara.dto.inventory.GatheringObservationDTO;
import org.inbio.ara.dto.inventory.IdentificationDTO;
import org.inbio.ara.dto.inventory.SpecimenDTO;
import org.inbio.ara.dto.transaction.TransactedSpecimenDTO;
import org.inbio.ara.dto.transaction.TransactionDTO;
import org.inbio.ara.util.QueryNode;
/**
*
* @author herson
*/
@Remote
public interface SearchFacadeRemote {
public List<SpecimenDTO> test();
/***************************************************************************
*********************** ========SITE======== ******************************
**************************************************************************/
public List<SiteDTO> searchSiteByCriteria(String query, int base, int offset);
public List<SiteDTO> searchSiteByCriteria(SiteDTO inputDTO, int base, int offset);
public Long countSitesByCriteria(String query);
public Long countSitesByCriteria(SiteDTO inputDTO);
/***************************************************************************
************************* ===SPECIMEN=== **********************************
**************************************************************************/
/**
* @param query String unstructured query
* @param base
* @param offset
* @return List<SpecimenDTO>
* @deprecated Use instead searchSpecimenByCriteria(String query,
* Long collectionId, int base, int offset)
*/
public List<SpecimenDTO> searchSpecimenByCriteria(String query, int base,
int offset);
/**
*
* @param query String unstructured query
* @param collectionId
* @param base
* @param offset
* @return List<SpecimenDTO>
*/
public List<SpecimenDTO> searchSpecimenByCriteria(String query,
Long collectionId, int base, int offset);
public List<SpecimenDTO> searchSpecimenByCriteria(SpecimenDTO inputDTO,
int base, int offset);
/**
*
* @param query
* @return Count about how many results will be returned in a simple query
* @deprecated Use instead: countSpecimensByCriteria(String query,
* <b>Long collectionId</b>)
*/
public Long countSpecimensByCriteria(String query);
/**
*
* @param query
* @param collectionId
* @return Count about how many results will be returned in a simple query,
* filtered by collection
*/
public Long countSpecimensByCriteria(String query, Long collectionId);
public Long countSpecimensByCriteria(SpecimenDTO inputDTO);
public Long countSpecimensByCriteria(SpecimenDTO inputDTO,String taxonLevel, String catalogEnd,Long initialGathObserDetail,
Long finalGathObserDetail,Long initialGathObser, Long finalGathObser,
Calendar initialDate, Calendar finalDate, Long identicatorId);
public List<SpecimenDTO> searchSpecimenByCriteria(SpecimenDTO inputDTO, String taxonomyLevel,String catalogEnd,
Long initialGathObserDetail, Long finalGathObserDetail, Long initialGathObser, Long finalGathObser,
Calendar initialDate, Calendar finalDate, Long identicatorId, int base, int offset);
/***************************************************************************
*********************** ===IDENTIFICATION=== ******************************
**************************************************************************/
public List<IdentificationDTO> searchIdentificationByCriteria(
IdentificationDTO inputDTO, int base, int offset, Set<Long> identIds);
/**
*
* @param query String unstructured query
* @param base
* @param offset
* @return
* @deprecated Use instead: searchIdentificationByCriteria(String query,
* <b>Long collectionId</b>, int base, int offset)
*/
public List<IdentificationDTO> searchIdentificationByCriteria(String query,
int base, int offset);
public List<IdentificationDTO> searchIdentificationByCriteria(String query,
Long collectionId, int base, int offset);
/**
*
* @param query
* @return
* @deprecated Use instead: countIdentificationByCriteria(String query,
* <b>Long collectionId</b>)
*/
public Long countIdentificationByCriteria(String query);
public Long countIdentificationByCriteria(String query, Long collectionId);
public Long countIdentificationByCriteria(IdentificationDTO inputDTO);
/***************************************************************************
************************ ===GATHERING=== **********************************
**************************************************************************/
/**
* @param query String unstructured query
* @param base
* @param offset
* @return
* @deprecated
*/
public List<GatheringObservationDTO> searchGathObsByCriteria(String query,
int base, int offset);
public List<GatheringObservationDTO> searchGathObsByCriteria(String query,
Long collectionId, int base, int offset);
/**
*
* @param query
* @return
* @deprecated
*/
public Long countGathObsByCriteria(String query);
public Long countGathObsByCriteria(String query, Long collectionId);
public List<GatheringObservationDTO>
searchGathObsByCriteria(GatheringObservationDTO inputDTO,
int base, int offset);
public Long countGathObsByCriteria(GatheringObservationDTO inputDTO);
public Long countQueryElements(LinkedList<QueryNode> sll);
public List findAllDwCPaginated(int first, int amount);
public List makePaginatedQuery
(LinkedList<QueryNode> sll, int first, int amount);
public Long countAllDwC();
/***************************************************************************
********************** === TRANSACTION === ********************************
**************************************************************************/
public List<TransactionDTO> searchTransactionsByCriteria(TransactionDTO inputTransactionDTO,
TransactedSpecimenDTO inputTransactedSpecimenDTO, int base, int offset);
public List<TransactionDTO> searchTransactionsByCriteria(String query,
Long collectionId, int base, int offset);
public Long countTransactionsByCriteria(TransactionDTO inputTransactionDTO,
TransactedSpecimenDTO inputTransactedSpecimenDTO);
public Long countTransactionsByCriteria(String query, Long collectionId);
public java.util.Set<java.lang.Long> getIdentificationIds(org.inbio.ara.dto.inventory.IdentificationDTO inputDTO);
}
|
package com.example.myapplication.circle;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.myapplication.R;
import com.example.myapplication.SqlHelper;
import java.text.SimpleDateFormat;
import java.util.Date;
public class WriteCircleActivity extends AppCompatActivity {
private EditText input_comment;
private Button btn_add;
private int Id;
private String LoginUserName, reply_people_name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//窗口对齐屏幕宽度
Window win = this.getWindow();
win.getDecorView().setPadding(80, 0, 80, 0);
WindowManager.LayoutParams lp = win.getAttributes();
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
win.setAttributes(lp);
setFinishOnTouchOutside(true);
setContentView(R.layout.activity_write_circle);
SharedPreferences sp = getSharedPreferences("CurrentLogin", MODE_PRIVATE);
LoginUserName = sp.getString("username", "none");
input_comment = findViewById(R.id.input_comment);
btn_add = findViewById(R.id.btn_add);
btn_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String comment = input_comment.getText().toString().trim();
if (comment.length() == 0)
Toast.makeText(getApplicationContext(), "内容不能为空", Toast.LENGTH_LONG).show();
else {
//塞数据
SqlHelper sqlHelper = new SqlHelper(getApplicationContext());
SQLiteDatabase db = sqlHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("username", LoginUserName);
values.put("time", LongToString(System.currentTimeMillis()));
values.put("content", comment);
values.put("discuss_number", 0);
db.insert("comment", null, values);
Toast.makeText(getApplicationContext(), "发表成功!", Toast.LENGTH_LONG).show();
//发送广播,更新成绩单数据
Intent intent = new Intent();
intent.setAction("AddComment");
sendBroadcast(intent);
db.close();
finish();
}
}
});
}
private String LongToString(long data) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
Date date = new Date(data);
return simpleDateFormat.format(date);
}
}
|
package com.weiziplus.springboot.pc.system.service;
import com.github.pagehelper.PageHelper;
import com.weiziplus.springboot.common.models.SysFunction;
import com.weiziplus.springboot.common.utils.PageBean;
import com.weiziplus.springboot.common.utils.ResponseBean;
import com.weiziplus.springboot.common.utils.ValidateUtil;
import com.weiziplus.springboot.pc.system.mapper.SysFunctionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author wanglongwei
* @data 2019/5/9 15:18
*/
@Service
public class SysFunctionService {
@Autowired
SysFunctionMapper mapper;
/**
* 根据角色id获取功能树形列表
*
* @param roleId
* @return
*/
public List<SysFunction> getMenuTreeByRoleId(Long roleId) {
List<SysFunction> resultList = new ArrayList<>();
SysFunction sysFunction = mapper.getMinParentIdMenuFunInfoByRoleId(roleId);
if (null == sysFunction) {
return resultList;
}
List<SysFunction> menuList = mapper.getMenuListByRoleIdAndParentId(roleId, sysFunction.getParentId());
for (SysFunction sysFun : menuList) {
sysFun.setChildren(findMenuChildren(roleId, sysFun));
resultList.add(sysFun);
}
return resultList;
}
/**
* 根据角色id递归子级菜单树形列表
*
* @param roleId
* @param sysFunction
* @return
*/
private List<SysFunction> findMenuChildren(Long roleId, SysFunction sysFunction) {
List<SysFunction> childrenList = new ArrayList<>();
List<SysFunction> menuList = mapper.getMenuListByRoleIdAndParentId(roleId, sysFunction.getId());
for (SysFunction sysFun : menuList) {
sysFun.setChildren(findMenuChildren(roleId, sysFun));
childrenList.add(sysFun);
}
return childrenList;
}
/**
* 获取所有功能列表树形结构
*
* @return
*/
public List<SysFunction> getFunTree() {
List<SysFunction> resultList = new ArrayList<>();
SysFunction sysFunction = mapper.getMinParentIdFunInfo();
List<SysFunction> menuList = mapper.getFunListByParentId(sysFunction.getParentId());
for (SysFunction sysFun : menuList) {
sysFun.setChildren(findChildren(sysFun));
resultList.add(sysFun);
}
return resultList;
}
/**
* 获取子级功能列表
*
* @param sysFunction
* @return
*/
private List<SysFunction> findChildren(SysFunction sysFunction) {
List<SysFunction> childrenList = new ArrayList<>();
List<SysFunction> menuList = mapper.getFunListByParentId(sysFunction.getId());
for (SysFunction sysFun : menuList) {
sysFun.setChildren(findChildren(sysFun));
childrenList.add(sysFun);
}
return childrenList;
}
/**
* 根据父级id获取子级列表
*
* @param parentId
* @param pageNum
* @param pageSize
* @return
*/
public Map<String, Object> getFunctionListByParentId(Long parentId, Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
return PageBean.pageInfo(mapper.getFunListByParentId(parentId));
}
/**
* 新增功能
*
* @param sysFunction
* @return
*/
public Map<String, Object> addFunction(SysFunction sysFunction) {
if (ValidateUtil.notEnglishNumberUnderLine(sysFunction.getName())) {
return ResponseBean.error("name为英文开头,英文、数字和下划线");
}
if (null == sysFunction.getParentId() || 0 > sysFunction.getParentId()) {
return ResponseBean.error("parentId不能为空");
}
SysFunction sysFun = mapper.getFunInfoByName(sysFunction.getName());
if (null != sysFun) {
return ResponseBean.error("name已存在");
}
return ResponseBean.success(mapper.addFunction(sysFunction));
}
/**
* 修改功能
*
* @param sysFunction
* @return
*/
public Map<String, Object> updateFunction(SysFunction sysFunction) {
return ResponseBean.success(mapper.updateFunction(sysFunction));
}
/**
* 根据ids删除功能
*
* @param ids
* @return
*/
public Map<String, Object> deleteFunction(Long[] ids) {
for (Long id : ids) {
List<SysFunction> list = mapper.getFunListByParentId(id);
if (null != list && 0 < list.size()) {
return ResponseBean.error("目录下面含有子级目录");
}
}
return ResponseBean.success(mapper.deleteFunctionByIds(ids));
}
}
|
package algorithm;
import algorithm.constants.Direction;
import algorithm.constants.RobotSensorPlacement;
import algorithm.contracts.AlgorithmContract;
import algorithm.models.ArenaCellCoordinate;
import algorithm.models.RobotModel;
import exception.OutOfGridException;
public class ExplorationAlgorithm implements AlgorithmContract {
RobotModel robotModel;
ArenaMemory arenaMemory;
boolean resume;
boolean wallOnRight = false;
boolean subGoalAchieved = false;
ArenaCellCoordinate goal;
ArenaCellCoordinate subgoal;
ArenaCellCoordinate start;
private boolean rightWallEmptyFlag;
private ArenaCellCoordinate imageGrid;
public ExplorationAlgorithm(RobotModel robotModel, ArenaMemory arenaMemory){
this.robotModel = robotModel;
this.arenaMemory = arenaMemory;
this.resume = true;
arenaMemory.setStartZoneAsExplored();
start = new ArenaCellCoordinate(1, 1);
subgoal = new ArenaCellCoordinate(13, 18);
goal = new ArenaCellCoordinate(1, 1);
}
public boolean isRightWallEmptyFlag() {
return rightWallEmptyFlag;
}
public ArenaCellCoordinate getImageGrid() {
return imageGrid;
}
@Override
public void run() {
robotModel.startRobot();
robotModel.waitForReadyState();
while (!isGoalAchieved() && canPlay()){
if(!subGoalAchieved){
//use to detect if robot has passed the goal zone
subGoalAchieved = robotModel.getRobotCenter().equals(subgoal);
}
boolean frontEmpty = robotModel.robotFrontSideEmpty();
boolean rightEmpty = robotModel.robotRightSideEmpty();
this.rightWallEmptyFlag = robotModel.rightMiddleEmpty();
if(!this.rightWallEmptyFlag){
try{
this.imageGrid = robotModel.getCoordinateOfCurrentDetection(RobotSensorPlacement.RIGHT_MIDDLE);
}
catch (OutOfGridException e){
this.imageGrid = null;
}
}
// if(robotModel.calibrationCondtion()){
// robotModel.callibrate();
// robotModel.waitForReadyState();
// }
if(rightEmpty){
if(wallOnRight){
robotModel.turnRightMoveOneAtomic();
}
else{
robotModel.turnRight();
}
}
else{
wallOnRight = true;
if(frontEmpty){
robotModel.moveFrontOneStep();
}
else{
wallOnRight = false;
robotModel.turnLeft();
}
}
robotModel.waitForReadyState();
}
setBackToNorth();
System.out.println("Goal achieved!");
}
public void setBackToNorth(){
while(robotModel.getCurrentDirection() != Direction.NORTH){
if(robotModel.getCurrentDirection().getValue() > 2){
robotModel.turnRight();
}
else{
robotModel.turnLeft();
}
robotModel.waitForReadyState();
}
}
/**
* Check if robot has achieved subgoal and return back to original starting position
* @return
*/
public boolean isGoalAchieved(){
return robotModel.getRobotCenter().equals(goal) && subGoalAchieved;
}
public synchronized void pauseAlgorithm(){
this.resume = false;
notifyAll();
}
synchronized public boolean canPlay(){
while(!resume){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
notifyAll();
return resume;
}
synchronized public void resumeAlgorithm(){
this.resume = true;
notifyAll();
}
}
|
package com.beike.common.exception;
/**
* @Title: AuthorizeException.java
* @Package com.beike.common.exception
* @Description: 扣款授权异常
* @author wh.cheng@sinobogroup.com
* @date May 4, 2011 3:44:51 PM
* @version V1.0
*/
public class AuthorizeException extends BaseException{
/**
*
*/
private static final long serialVersionUID = 4569136195531085067L;
public AuthorizeException(){
super();
}
public AuthorizeException(int code){
this.code=code;
}
}
|
package com.appunite.rx.example.model.dao;
import com.appunite.gson.AndroidUnderscoreNamingStrategy;
import com.appunite.gson.ImmutableListDeserializer;
import com.appunite.rx.ResponseOrError;
import com.appunite.rx.example.model.api.GuestbookService;
import com.appunite.rx.example.model.model.Post;
import com.appunite.rx.example.model.model.PostId;
import com.appunite.rx.example.model.model.PostWithBody;
import com.appunite.rx.example.model.model.PostsIdsResponse;
import com.appunite.rx.example.model.model.PostsResponse;
import com.appunite.rx.operators.MoreOperators;
import com.appunite.rx.operators.OperatorMergeNextToken;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.okhttp.Cache;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Response;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Singleton;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.android.AndroidLog;
import retrofit.client.OkClient;
import retrofit.converter.GsonConverter;
import rx.Observable;
import rx.Observer;
import rx.Scheduler;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.subjects.PublishSubject;
@Singleton
public class PostsDao {
@Nonnull
private final Observable<ResponseOrError<PostsResponse>> posts;
@Nonnull
private final Observable<ResponseOrError<PostsIdsResponse>> postsIds;
@Nonnull
private final PublishSubject<Object> refreshSubject = PublishSubject.create();
@Nonnull
private final LoadingCache<String, PostDao> cache;
/*
Normally we rather use dagger instead of static, but for testing purposes is ok
*/
private static final Object LOCK = new Object();
private static PostsDao postsDao;
@Nonnull
private final Scheduler networkScheduler;
@Nonnull
private final Scheduler uiScheduler;
@Nonnull
private final GuestbookService guestbookService;
@Nonnull
private final PublishSubject<Object> loadMoreSubject = PublishSubject.create();
private static class SyncExecutor implements Executor {
@Override
public void execute(@Nonnull final Runnable command) {
command.run();
}
}
public static PostsDao getInstance(@Nonnull File cacheDirectory, @Nonnull Scheduler networkScheduler, @Nonnull Scheduler uiScheduler) {
synchronized (LOCK) {
if (postsDao != null) {
return postsDao;
}
final Gson gson = new GsonBuilder()
.registerTypeAdapter(ImmutableList.class, new ImmutableListDeserializer())
.setFieldNamingStrategy(new AndroidUnderscoreNamingStrategy())
.create();
final OkHttpClient client = new OkHttpClient();
client.setCache(getCacheOrNull(cacheDirectory));
final RestAdapter restAdapter = new RestAdapter.Builder()
.setClient(new OkClient(client))
.setEndpoint("https://atlantean-field-90117.appspot.com/_ah/api/guestbook/")
.setExecutors(new SyncExecutor(), new SyncExecutor())
.setConverter(new GsonConverter(gson))
.setLogLevel(RestAdapter.LogLevel.FULL)
.setLog(new AndroidLog("Retrofit"))
.build();
final GuestbookService guestbookService = restAdapter.create(GuestbookService.class);
postsDao = new PostsDao(networkScheduler, uiScheduler, guestbookService);
return postsDao;
}
}
@Nullable
private static Cache getCacheOrNull(@Nonnull File cacheDirectory) {
int cacheSize = 10 * 1024 * 1024; // 10 MiB
try {
return new Cache(cacheDirectory, cacheSize);
} catch (IOException e) {
return null;
}
}
public PostsDao(@Nonnull final Scheduler networkScheduler,
@Nonnull final Scheduler uiScheduler,
@Nonnull final GuestbookService guestbookService) {
this.networkScheduler = networkScheduler;
this.uiScheduler = uiScheduler;
this.guestbookService = guestbookService;
final OperatorMergeNextToken<PostsResponse, Object> mergePostsNextToken =
OperatorMergeNextToken
.create(new Func1<PostsResponse, Observable<PostsResponse>>() {
@Override
public Observable<PostsResponse> call(@Nullable final PostsResponse response) {
if (response == null) {
return guestbookService.listPosts(null)
.subscribeOn(networkScheduler);
} else {
final String nextToken = response.nextToken();
if (nextToken == null) {
return Observable.never();
}
final Observable<PostsResponse> apiRequest = guestbookService
.listPosts(nextToken)
.subscribeOn(networkScheduler);
return Observable.just(response)
.zipWith(apiRequest,
new MergeTwoResponses());
}
}
});
posts = loadMoreSubject.startWith((Object) null)
.lift(mergePostsNextToken)
.compose(ResponseOrError.<PostsResponse>toResponseOrErrorObservable())
.compose(MoreOperators.<PostsResponse>repeatOnError(networkScheduler))
.compose(MoreOperators.<ResponseOrError<PostsResponse>>refresh(refreshSubject))
.subscribeOn(networkScheduler)
.observeOn(uiScheduler)
.compose(MoreOperators.<ResponseOrError<PostsResponse>>cacheWithTimeout(uiScheduler));
final OperatorMergeNextToken<PostsIdsResponse, Object> mergePostsIdsNextToken = OperatorMergeNextToken
.create(new Func1<PostsIdsResponse, Observable<PostsIdsResponse>>() {
@Override
public Observable<PostsIdsResponse> call(@Nullable final PostsIdsResponse response) {
if (response == null) {
return guestbookService.listPostsIds(null)
.subscribeOn(networkScheduler);
} else {
final String nextToken = response.nextToken();
if (nextToken == null) {
return Observable.never();
}
final Observable<PostsIdsResponse> apiRequest = guestbookService.listPostsIds(nextToken)
.subscribeOn(networkScheduler);
return Observable.just(response).zipWith(apiRequest, new MergeTwoPostsIdsResponses());
}
}
});
postsIds = loadMoreSubject.startWith((Object) null)
.lift(mergePostsIdsNextToken)
.compose(ResponseOrError.<PostsIdsResponse>toResponseOrErrorObservable())
.compose(MoreOperators.<PostsIdsResponse>repeatOnError(networkScheduler))
.compose(MoreOperators.<ResponseOrError<PostsIdsResponse>>refresh(refreshSubject))
.subscribeOn(networkScheduler)
.observeOn(uiScheduler)
.compose(MoreOperators.<ResponseOrError<PostsIdsResponse>>cacheWithTimeout(uiScheduler));
cache = CacheBuilder.newBuilder()
.build(new CacheLoader<String, PostDao>() {
@Override
public PostDao load(@Nonnull final String id) throws Exception {
return new PostDao(id);
}
});
}
@Nonnull
public PostDao postDao(@Nonnull final String id) {
return cache.getUnchecked(id);
}
@Nonnull
public Observer<Object> loadMoreObserver() {
return loadMoreSubject;
}
@Nonnull
public Observable<ResponseOrError<PostsResponse>> postsObservable() {
return posts;
}
@Nonnull
public Observable<ResponseOrError<PostsIdsResponse>> postsIdsObservable() {
return postsIds;
}
@Nonnull
public Observer<Object> refreshObserver() {
return refreshSubject;
}
public class PostDao {
@Nonnull
private final PublishSubject<Object> refreshSubject = PublishSubject.create();
@Nonnull
private final Observable<ResponseOrError<PostWithBody>> postWithBodyObservable;
public PostDao(@Nonnull String id) {
postWithBodyObservable = guestbookService.getPost(id)
.compose(ResponseOrError.<PostWithBody>toResponseOrErrorObservable())
.compose(MoreOperators.<PostWithBody>repeatOnError(networkScheduler))
.compose(MoreOperators.<ResponseOrError<PostWithBody>>refresh(refreshSubject))
.subscribeOn(networkScheduler)
.observeOn(uiScheduler)
.compose(MoreOperators.<ResponseOrError<PostWithBody>>cacheWithTimeout(uiScheduler));
}
@Nonnull
public Observable<ResponseOrError<PostWithBody>> postWithBodyObservable() {
return postWithBodyObservable;
}
@Nonnull
public Observable<ResponseOrError<Post>> postObservable() {
return postWithBodyObservable
.compose(ResponseOrError.map(new Func1<PostWithBody, Post>() {
@Override
public Post call(PostWithBody o) {
return o;
}
}));
}
@Nonnull
public Observer<Object> refreshObserver() {
return refreshSubject;
}
}
private static class MergeTwoResponses implements rx.functions.Func2<PostsResponse, PostsResponse, PostsResponse> {
@Override
public PostsResponse call(PostsResponse previous, PostsResponse moreData) {
final ImmutableList<Post> posts = ImmutableList.<Post>builder()
.addAll(previous.items())
.addAll(moreData.items())
.build();
return new PostsResponse(moreData.title(), posts, moreData.nextToken());
}
}
private class MergeTwoPostsIdsResponses implements rx.functions.Func2<PostsIdsResponse, PostsIdsResponse, PostsIdsResponse> {
@Override
public PostsIdsResponse call(PostsIdsResponse previous, PostsIdsResponse moreData) {
final ImmutableList<PostId> posts = ImmutableList.<PostId>builder()
.addAll(previous.items())
.addAll(moreData.items())
.build();
return new PostsIdsResponse(moreData.title(), posts, moreData.nextToken());
}
}
}
|
package com.oa.role.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.oa.page.form.Page;
import com.oa.role.dao.RoleInfoDao;
import com.oa.role.form.RoleInfo;
import com.oa.user.dao.UserInfoDao;
@Service
public class RoleInfoServiceImpl implements RoleInfoService {
@Autowired
private RoleInfoDao roleInfoDao;
@Override
public void addRoleInfo(RoleInfo roleInfo) {
roleInfoDao.addRoleInfo(roleInfo);
}
@Override
public List<RoleInfo> selectAllRoleInfo() {
return roleInfoDao.selectAllRoleInfo();
}
@Override
public RoleInfo selectRoleInfoByName(String roleName) {
return roleInfoDao.selectRoleInfoByName(roleName);
}
@Override
public RoleInfo selectRoleInfoById(int roleId) {
return roleInfoDao.selectRoleInfoById(roleId);
}
@Override
public void updateRoleInfo(RoleInfo roleInfo) {
roleInfoDao.updateRoleInfo(roleInfo);
}
@Override
public void deleteRoleInfo(Integer roleId) {
roleInfoDao.deleteRoleInfo(roleId);
}
@Override
public List<RoleInfo> selectRoleInfoByPage(final Page page) {
return roleInfoDao.selectRoleInfoByPage(page);
}
}
|
package com.product.model;
import java.util.*;
import java.sql.*;
public class ProductJDBCDAO implements ProductDAO_interface{
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@localhost:1521:XE";
String userid = "DA104_G6";
String passwd = "123456";
private static final String INSERT_STMT =
"INSERT INTO PRODUCT (PRO_NO,PRODUCT,PRICE,PIC,MESSAGE,STATUS,SCORE,SCORE_PEO,CATEGORY_NO) VALUES ('P'||TO_CHAR(PRODUCT_SEQ.NEXTVAL,'FM0000'),?,?,?,?,1,0,0,?)";
private static final String UPDATE =
"UPDATE PRODUCT SET PRODUCT=?, PRICE=?, PIC=?, MESSAGE=?, STATUS=?, SCORE=?, SCORE_PEO=? where PRO_NO=?";
private static final String DELETE =
"DELETE FROM PRODUCT WHERE PRO_NO =?";
private static final String GET_ONE_STMT =
"SELECT PRO_NO,PRODUCT,PRICE,PIC,MESSAGE,STATUS,SCORE,SCORE_PEO,CATEGORY_NO from PRODUCT where PRO_NO = ?";
private static final String GET_CATEGORY_STMT =
"SELECT PRO_NO,PRODUCT,PRICE,PIC,MESSAGE,STATUS,SCORE,SCORE_PEO,CATEGORY_NO from PRODUCT where CATEGORY_NO = ?";
private static final String GET_ALL_STMT =
"SELECT PRO_NO,PRODUCT,PRICE,PIC,MESSAGE,STATUS,SCORE,SCORE_PEO,CATEGORY_NO from PRODUCT order by PRO_NO";
private static final String GET_PRODUCT_STMT =
"SELECT PRO_NO,PRODUCT,PRICE,PIC,MESSAGE,STATUS,SCORE,SCORE_PEO,CATEGORY_NO from PRODUCT where PRODUCT LIKE '%'|| ? ||'%' AND CATEGORY_NO LIKE '%'|| ? ||'%' AND STATUS=2";
private static final String GET_STATUS_STMT =
"SELECT PRO_NO,PRODUCT,PRICE,PIC,MESSAGE,STATUS,SCORE,SCORE_PEO,CATEGORY_NO from PRODUCT where STATUS = ?";
private static final String UPDATE_SCORE=
"UPDATE PRODUCT SET SCORE=?, SCORE_PEO=? where PRO_NO=?";
@Override
public void insert(ProductVO productVO) {
Connection con = null;
PreparedStatement pstmt = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, userid, passwd);
pstmt = con.prepareStatement(INSERT_STMT);
pstmt.setString(1, productVO.getProduct());
pstmt.setInt(2, productVO.getPrice());
pstmt.setBytes(3, productVO.getPic());
pstmt.setString(4, productVO.getMessage());
pstmt.setString(5, productVO.getCategory_no());
pstmt.executeUpdate();
}catch(ClassNotFoundException e) {
throw new RuntimeException("Couldn't load database driver. "
+ e.getMessage());
}catch(SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
}finally {
if(pstmt != null) {
try {
pstmt.close();
}catch(SQLException se) {
se.printStackTrace(System.err);
}
}
if(con != null) {
try {
con.close();
}catch(Exception e) {
e.printStackTrace(System.err);
}
}
}
}
@Override
public void update(ProductVO productVO) {
Connection con = null;
PreparedStatement pstmt = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, userid, passwd);
pstmt = con.prepareStatement(UPDATE);
pstmt.setString(1, productVO.getProduct());
pstmt.setInt(2, productVO.getPrice());
pstmt.setBytes(3, productVO.getPic());
pstmt.setString(4, productVO.getMessage());
pstmt.setInt(5, productVO.getStatus());
pstmt.setInt(6, productVO.getScore());
pstmt.setInt(7, productVO.getScore_peo());
pstmt.setString(8, productVO.getPro_no());
pstmt.executeUpdate();
}catch(ClassNotFoundException e) {
throw new RuntimeException("Couldn't load database driver. "
+ e.getMessage());
}catch(SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
}finally {
if(pstmt != null) {
try {
pstmt.close();
}catch(SQLException se) {
se.printStackTrace(System.err);
}
}
if(con != null) {
try {
con.close();
}catch(Exception e) {
e.printStackTrace(System.err);
}
}
}
}
@Override
public void delete(String pro_no) {
Connection con = null;
PreparedStatement pstmt = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, userid, passwd);
pstmt = con.prepareStatement(DELETE);
pstmt.setString(1, pro_no);
pstmt.executeQuery();
}catch(ClassNotFoundException e) {
throw new RuntimeException("Couldn't load database driver. "
+ e.getMessage());
}catch(SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
}finally {
if(pstmt != null) {
try {
pstmt.close();
}catch(SQLException se) {
se.printStackTrace(System.err);
}
}
if(con != null) {
try {
con.close();
}catch(Exception e) {
e.printStackTrace(System.err);
}
}
}
}
@Override
public ProductVO findByPrimaryKey(String pro_no) {
ProductVO productVO = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, userid, passwd);
pstmt = con.prepareStatement(GET_ONE_STMT);
pstmt.setString(1, pro_no);
rs = pstmt.executeQuery();
while(rs.next()) {
productVO = new ProductVO();
productVO.setPro_no(rs.getString("pro_no"));
productVO.setProduct(rs.getString("product"));
productVO.setPrice(rs.getInt("price"));
productVO.setPic(rs.getBytes("pic"));
productVO.setMessage(rs.getString("message"));
productVO.setStatus(rs.getInt("status"));
productVO.setScore(rs.getInt("score"));
productVO.setScore_peo(rs.getInt("score_peo"));
productVO.setCategory_no(rs.getString("category_no"));
}
}catch(ClassNotFoundException e) {
throw new RuntimeException("Couldn't load database driver. "
+ e.getMessage());
}catch(SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
}finally {
if(rs != null) {
try {
rs.close();
}catch(SQLException se) {
se.printStackTrace(System.err);
}
}
if(pstmt != null) {
try {
pstmt.close();
}catch(SQLException se) {
se.printStackTrace(System.err);
}
}
if(con != null) {
try {
con.close();
}catch(SQLException se) {
se.printStackTrace(System.err);
}
}
}
return productVO;
}
@Override
public List<ProductVO> findByCategory(String category_no) {
List<ProductVO> list = new ArrayList<ProductVO>();
ProductVO productVO = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, userid, passwd);
pstmt = con.prepareStatement(GET_CATEGORY_STMT);
pstmt.setString(1, category_no);
rs = pstmt.executeQuery();
while(rs.next()) {
productVO = new ProductVO();
productVO.setPro_no(rs.getString("pro_no"));
productVO.setProduct(rs.getString("product"));
productVO.setPrice(rs.getInt("price"));
productVO.setPic(rs.getBytes("pic"));
productVO.setMessage(rs.getString("message"));
productVO.setStatus(rs.getInt("status"));
productVO.setScore(rs.getInt("score"));
productVO.setScore_peo(rs.getInt("score_peo"));
productVO.setCategory_no(rs.getString("category_no"));
list.add(productVO);
}
}catch(ClassNotFoundException e) {
throw new RuntimeException("Couldn't load database driver. "
+ e.getMessage());
}catch(SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
}finally {
if(rs != null) {
try {
rs.close();
}catch(SQLException se) {
se.printStackTrace(System.err);
}
}
if(pstmt != null) {
try {
pstmt.close();
}catch(SQLException se) {
se.printStackTrace(System.err);
}
}
if(con != null) {
try {
con.close();
}catch(Exception e) {
e.printStackTrace(System.err);
}
}
}
return list;
}
@Override
public List<ProductVO> getAll() {
List<ProductVO> list = new ArrayList<ProductVO>();
ProductVO productVO = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, userid, passwd);
pstmt = con.prepareStatement(GET_ALL_STMT);
rs = pstmt.executeQuery();
while(rs.next()) {
productVO = new ProductVO();
productVO.setPro_no(rs.getString("pro_no"));
productVO.setProduct(rs.getString("product"));
productVO.setPrice(rs.getInt("price"));
productVO.setPic(rs.getBytes("pic"));
productVO.setMessage(rs.getString("message"));
productVO.setStatus(rs.getInt("status"));
productVO.setScore(rs.getInt("score"));
productVO.setScore_peo(rs.getInt("score_peo"));
productVO.setCategory_no(rs.getString("category_no"));
list.add(productVO);
}
}catch(ClassNotFoundException e) {
throw new RuntimeException("Couldn't load database driver. "
+ e.getMessage());
}catch(SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
}finally {
if(rs != null) {
try {
rs.close();
}catch(SQLException se) {
se.printStackTrace(System.err);
}
}
if(pstmt != null) {
try {
pstmt.close();
}catch(SQLException se) {
se.printStackTrace(System.err);
}
}
if(con != null) {
try {
con.close();
}catch(Exception e) {
e.printStackTrace(System.err);
}
}
}
return list;
}
@Override
public List<ProductVO> findByCompositeQuery(String product, String category_no) {
List<ProductVO> list = new ArrayList<ProductVO>();
ProductVO productVO = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, userid, passwd);
pstmt = con.prepareStatement(GET_PRODUCT_STMT);
pstmt.setString(1, product);
pstmt.setString(2, category_no);
rs = pstmt.executeQuery();
while(rs.next()) {
productVO = new ProductVO();
productVO.setPro_no(rs.getString("pro_no"));
productVO.setProduct(rs.getString("product"));
productVO.setPrice(rs.getInt("price"));
productVO.setPic(rs.getBytes("pic"));
productVO.setMessage(rs.getString("message"));
productVO.setStatus(rs.getInt("status"));
productVO.setScore(rs.getInt("score"));
productVO.setScore_peo(rs.getInt("score_peo"));
productVO.setCategory_no(rs.getString("category_no"));
list.add(productVO);
}
}catch(ClassNotFoundException e) {
throw new RuntimeException("Couldn't load database driver. "
+ e.getMessage());
}catch(SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
}finally {
if(rs != null) {
try {
rs.close();
}catch(SQLException se) {
se.printStackTrace(System.err);
}
}
if(pstmt != null) {
try {
pstmt.close();
}catch(SQLException se) {
se.printStackTrace(System.err);
}
}
if(con != null) {
try {
con.close();
}catch(Exception e) {
e.printStackTrace(System.err);
}
}
}
return list;
}
@Override
public List<ProductVO> getStatus(Integer status) {
List<ProductVO> list = new ArrayList<ProductVO>();
ProductVO productVO = null;
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, userid, passwd);
pstmt = con.prepareStatement(GET_STATUS_STMT);
pstmt.setInt(1, status);
rs = pstmt.executeQuery();
while(rs.next()) {
productVO = new ProductVO();
productVO.setPro_no(rs.getString("pro_no"));
productVO.setProduct(rs.getString("product"));
productVO.setPrice(rs.getInt("price"));
productVO.setPic(rs.getBytes("pic"));
productVO.setMessage(rs.getString("message"));
productVO.setStatus(rs.getInt("status"));
productVO.setScore(rs.getInt("score"));
productVO.setScore_peo(rs.getInt("score_peo"));
productVO.setCategory_no(rs.getString("category_no"));
list.add(productVO);
}
}catch(ClassNotFoundException e) {
throw new RuntimeException("Couldn't load database driver. "
+ e.getMessage());
}catch(SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
}finally {
if(rs != null) {
try {
rs.close();
}catch(SQLException se) {
se.printStackTrace(System.err);
}
}
if(pstmt != null) {
try {
pstmt.close();
}catch(SQLException se) {
se.printStackTrace(System.err);
}
}
if(con != null) {
try {
con.close();
}catch(Exception e) {
e.printStackTrace(System.err);
}
}
}
return list;
}
@Override
public void updateScore(ProductVO productVO) {
Connection con = null;
PreparedStatement pstmt = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, userid, passwd);
pstmt = con.prepareStatement(UPDATE_SCORE);
pstmt.setInt(1, productVO.getScore());
pstmt.setInt(2, productVO.getScore_peo());
pstmt.setString(3, productVO.getPro_no());
pstmt.executeUpdate();
}catch(ClassNotFoundException e) {
throw new RuntimeException("Couldn't load database driver. "
+ e.getMessage());
}catch(SQLException se) {
throw new RuntimeException("A database error occured. "
+ se.getMessage());
}finally {
if(pstmt != null) {
try {
pstmt.close();
}catch(SQLException se) {
se.printStackTrace(System.err);
}
}
if(con != null) {
try {
con.close();
}catch(Exception e) {
e.printStackTrace(System.err);
}
}
}
}
public static void main(String[] args) {
ProductJDBCDAO dao = new ProductJDBCDAO();
// ProductVO productVO1 = new ProductVO();
// productVO1.setProduct("腳踏車");
// productVO1.setPrice(66666);
// productVO1.setMessage("111111111");
// productVO1.setScore(100);
// productVO1.setScore_peo(1);
// productVO1.setCategory_no("C0001");
// dao.insert(productVO1);
// //�ק�
// ProductVO productVO2 = new ProductVO();
// productVO2.setPro_no("P0021");
// productVO2.setProduct("����");
// productVO2.setPrice(77777);
// productVO2.setMessage("���P");
// productVO2.setStatus(2);
// productVO2.setScore(10000);
// productVO2.setScore_peo(100);
// dao.update(productVO2);
// //�R��
// dao.delete("P0022");
// //��@�d��
// ProductVO productVO3 = dao.findByPrimaryKey("P0004");
// System.out.print(productVO3.getPro_no()+",");
// System.out.print(productVO3.getProduct()+",");
// System.out.print(productVO3.getPrice()+",");
// System.out.print(productVO3.getMessage()+",");
// System.out.print(productVO3.getStatus()+",");
// System.out.print(productVO3.getScore()+",");
// System.out.print(productVO3.getScore_peo()+",");
// System.out.println(productVO3.getCategory_no());
// List<ProductVO> list = dao.findByCategory("C0001");
// for(ProductVO aProductVO : list) {
// System.out.print(aProductVO.getPro_no()+",");
// System.out.print(aProductVO.getProduct()+",");
// System.out.print(aProductVO.getPrice()+",");
// System.out.print(aProductVO.getMessage()+",");
// System.out.print(aProductVO.getStatus()+",");
// System.out.print(aProductVO.getScore()+",");
// System.out.print(aProductVO.getScore_peo()+",");
// System.out.println(aProductVO.getCategory_no());
// System.out.println();
//
// }
// List<ProductVO> list = dao.getAll();
// for(ProductVO aProductVO : list) {
// System.out.print(aProductVO.getPro_no()+",");
// System.out.print(aProductVO.getProduct()+",");
// System.out.print(aProductVO.getPrice()+",");
// System.out.print(aProductVO.getMessage()+",");
// System.out.print(aProductVO.getStatus()+",");
// System.out.print(aProductVO.getScore()+",");
// System.out.print(aProductVO.getScore_peo()+",");
// System.out.println(aProductVO.getCategory_no());
// System.out.println();
//
// }
// List<ProductVO> list = dao.findByCompositeQuery("","C0001");
// for(ProductVO aProductVO : list) {
// System.out.print(aProductVO.getPro_no()+",");
// System.out.print(aProductVO.getProduct()+",");
// System.out.print(aProductVO.getPrice()+",");
// System.out.print(aProductVO.getMessage()+",");
// System.out.print(aProductVO.getStatus()+",");
// System.out.print(aProductVO.getScore()+",");
// System.out.print(aProductVO.getScore_peo()+",");
// System.out.println(aProductVO.getCategory_no());
// System.out.println();
//
// }
// List<ProductVO> list = dao.getStatus(2);
// for(ProductVO aProductVO : list) {
// System.out.print(aProductVO.getPro_no()+",");
// System.out.print(aProductVO.getProduct()+",");
// System.out.print(aProductVO.getPrice()+",");
// System.out.print(aProductVO.getMessage()+",");
// System.out.print(aProductVO.getStatus()+",");
// System.out.print(aProductVO.getScore()+",");
// System.out.print(aProductVO.getScore_peo()+",");
// System.out.println(aProductVO.getCategory_no());
// System.out.println();
//
// }
ProductVO productVO2 = new ProductVO();
productVO2.setPro_no("P0001");
productVO2.setScore(10000);
productVO2.setScore_peo(100);
dao.updateScore(productVO2);
}
}
|
package com.polarb.android;
import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.os.Build;
import android.util.Log;
import android.util.Pair;
import android.view.Display;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Util {
public static Point getScreenSize(Activity activity) {
Point size = new Point();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
Display display = activity.getWindowManager().getDefaultDisplay();
display.getSize(size);
} else{
size.x = activity.getWindowManager().getDefaultDisplay().getWidth();
size.y = activity.getWindowManager().getDefaultDisplay().getHeight();
}
return size;
}
public static Pair<Integer, Integer> getPollImageSize(Activity activity){
int imageWidth = Util.getScreenSize(activity).x * 90 / 100;
int imageHeight = imageWidth * 67 / 100;
return new Pair<Integer, Integer>(imageWidth, imageHeight);
}
public static String getStringFromInputStream(InputStream inputStream) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
inputStream.close();
} catch (IOException e) {
}
return outputStream.toString();
}
}
|
package ur.api_ur;
import ur.api_ur.api_data_obj.URLBSDataObj;
import ur.ur_flow.managers.URLBSDataSetter;
/**
* Created by redjack on 15/11/4.
*/
public class LBSInfo {
public enum LBSType
{
GeoFence,
Beacon;
public static String TABLE_NAME = "push";
private String[] KEYS = {
"geofence",
"beacon"
};
public String getKey() {
return KEYS[this.ordinal()];
}
}
private String uniqueID;
public LBSType lbsType;
public URLBSDataObj.DataType dataType;
public URLBSDataObj dataObj;
public LBSInfo(LBSType lbsType, URLBSDataObj.DataType dataType, String id)
{
this.lbsType = lbsType;
this.dataType = dataType;
this.uniqueID = id;
}
}
|
package com.softserveinc.uschedule.entity;
import com.softserveinc.uschedule.entity.util.LocalDatePersistenceConverter;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "schedule")
public class Schedule {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(name = "start_date")
@Convert(converter = LocalDatePersistenceConverter.class)
private LocalDate startDate;
@Column(name = "end_date")
@Convert(converter = LocalDatePersistenceConverter.class)
private LocalDate endDate;
@OneToMany(mappedBy = "schedule", fetch = FetchType.LAZY)
private Set<Event> events = new HashSet<Event>();
@ManyToOne
@JoinColumn(name = "group_id")
private Group group;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public LocalDate getStartDate() {
return startDate;
}
public void setStartDate(LocalDate startDate) {
this.startDate = startDate;
}
public LocalDate getEndDate() {
return endDate;
}
public void setEndDate(LocalDate endDate) {
this.endDate = endDate;
}
public Set<Event> getEvents() {
return events;
}
public void setEvents(Set<Event> events) {
this.events = events;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
}
|
package com.example.ufmealmeter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class CaloriesSummaryActivity extends Activity {
int position;
int totalCalories = 0;
float totalCarbs = 0;
float totalFat = 0;
float remainingCalories = 0;
float budgetBalance = 0;
public final String PREF_NAME = "threshold";
public final String userHistory = "history.txt";
ArrayList<String> selectedFoodItems;
ArrayList<String> selectedCal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calories_summary);
// Show the Up button in the action bar.
setupActionBar();
// Select position from previous activity and bring that menu here
position = this.getIntent().getExtras().getInt("position");
selectedCal = this.getIntent().getExtras().getStringArrayList("indvCalorie");
totalCalories = this.getIntent().getExtras().getInt("totalCal");
totalCarbs = this.getIntent().getExtras().getFloat("totalCarbs");
totalFat = this.getIntent().getExtras().getFloat("totalFat");
remainingCalories = this.getIntent().getExtras().getFloat("calBalance");
budgetBalance = this.getIntent().getExtras().getFloat("budgetBalance");
selectedFoodItems = this.getIntent().getExtras().getStringArrayList("foodNames");
FoodNameAdapter adapter = new FoodNameAdapter(getApplicationContext(), selectedFoodItems);
ListView food_list = (ListView) findViewById(R.id.selected_fooditem);
food_list.setAdapter(adapter);
TextView cal = (TextView) findViewById(R.id.total_calories);
cal.setText("Total Calories : " + String.valueOf(totalCalories) + "\n");
TextView carbs = (TextView) findViewById(R.id.total_carbs);
carbs.setText("Total Carbs : " + String.valueOf(totalCarbs) + "\n");
TextView fat = (TextView) findViewById(R.id.total_fat);
fat.setText("Total Fat : " + String.valueOf(totalFat) + "\n");
TextView remaining_calories = (TextView) findViewById(R.id.remaining_calories);
remaining_calories.setText("Remaining Calories : " + String.valueOf(remainingCalories) + "\n");
TextView remaining_budget = (TextView) findViewById(R.id.remaining_budget);
remaining_budget.setText("Remaining Budget (Excluding this meal): " + String.valueOf(budgetBalance) + "\n");
}
/**
* Set up the {@link android.app.ActionBar}.
*/
private void setupActionBar() {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.calories_summary, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(CaloriesSummaryActivity.this, FoodItemActivity.class);
intent.putExtra("position", position);
NavUtils.navigateUpTo(this, intent);
return true;
case R.id.menu_save:
Intent intent1 = new Intent(CaloriesSummaryActivity.this, RestaurantActivity.class);
writeToFile();
startActivity(intent1);
return true;
}
return super.onOptionsItemSelected(item);
}
// Tue, Mar 19 2013 (Date), 6 (Total Calorie), 4.2 (Total price)
private String getDisplaySummary() {
StringBuilder temp = new StringBuilder();
temp.append(getTodaysDate());
temp.append(",");
temp.append(totalCalories);
temp.append(",");
EditText price = (EditText) findViewById(R.id.price);
if (null != price.getText().toString() && !"".equalsIgnoreCase(price.getText().toString()))
temp.append(price.getText().toString());
else
temp.append("0");
return temp.toString();
}
private void writeToFile() {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput(userHistory, Context.MODE_PRIVATE | Context.MODE_APPEND));
BufferedWriter bwriter = new BufferedWriter(outputStreamWriter);
bwriter.write(getDisplaySummary());
bwriter.newLine();
// Item name 1, Calorie 1
// Item name 2, Calorie 2
// *
int i = 0;
StringBuilder temp;
while (i < selectedFoodItems.size()) {
temp = new StringBuilder();
temp = temp.append(selectedFoodItems.get(i));
temp = temp.append(",");
temp = temp.append(selectedCal.get(i));
i++;
bwriter.write(temp.toString());
bwriter.newLine();
}
bwriter.write("*");
bwriter.newLine();
bwriter.close();
} catch (IOException e) {
}
}
@SuppressLint("SimpleDateFormat")
private String getTodaysDate() {
SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy");
Date now = new Date();
return formatter.format(now);
}
}
|
package com.lojaDeComputadorV3.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.lojaDeComputadorV3.domain.EntidadeDominio;
import com.lojaDeComputadorV3.domain.Funcionario;
import com.lojaDeComputadorV3.util.HibernateUtil;
public class FuncionarioDAO extends AbstractDAO{
@Override
public void salvar(EntidadeDominio entidade) {
Session sessao = HibernateUtil.getSessionFactory().openSession();
Transaction transacao = null;
try {
transacao = sessao.beginTransaction();
sessao.save(entidade);
transacao.commit();
} catch (RuntimeException ex) {
if (transacao != null)
transacao.rollback();
throw ex;
} finally {
sessao.close();
}
}
@SuppressWarnings("unchecked")
@Override
public List<EntidadeDominio> listar() {
Session sessao = HibernateUtil.getSessionFactory().openSession();
List<EntidadeDominio> funcionarios = null;
try {
Query consulta = sessao.getNamedQuery("Funcionario.listar");
funcionarios = consulta.list();
} catch (RuntimeException ex) {
throw ex;
} finally {
sessao.close();
}
return funcionarios;
}
@Override
public EntidadeDominio buscarPorCodigo(Long codigo) {
Session sessao = HibernateUtil.getSessionFactory().openSession();
Funcionario funcionario = null;
try {
Query consulta = sessao.getNamedQuery("Funcionario.buscarPorCodigo");
consulta.setLong("codigo", codigo);
funcionario = (Funcionario) consulta.uniqueResult();
} catch (RuntimeException ex) {
throw ex;
} finally {
sessao.close();
}
return funcionario;
}
@Override
public void excluir(EntidadeDominio entidade) {
Session sessao = HibernateUtil.getSessionFactory().openSession();
Transaction transacao = null;
try {
transacao = sessao.beginTransaction();
sessao.delete(entidade);
transacao.commit();
} catch (RuntimeException ex) {
if (transacao != null) {
transacao.rollback();
}
throw ex;
} finally {
sessao.close();
}
}
@Override
public void editar(EntidadeDominio entidade) {
Session sessao = HibernateUtil.getSessionFactory().openSession();
Transaction transacao = null;
try {
transacao = sessao.beginTransaction();
sessao.update(entidade);
transacao.commit();
} catch (RuntimeException ex) {
if (transacao != null) {
transacao.rollback();
}
throw ex;
} finally {
sessao.close();
}
}
public Funcionario autenticar(String email, String senha) {
Session sessao = HibernateUtil.getSessionFactory().openSession();
Funcionario funcionario = null;
try {
Query consulta = sessao.getNamedQuery("Funcionario.autenticar");
consulta.setString("email", email);
consulta.setString("senha", senha);
funcionario = (Funcionario) consulta.uniqueResult();
} catch (RuntimeException ex) {
throw ex;
} finally {
sessao.close();
}
return funcionario;
}
}
|
package com.dromedicas.dto;
// Generated 1/04/2017 11:59:12 AM by Hibernate Tools 5.1.2.Final
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* Sucursales generated by hbm2java
*/
public class Sucursales implements java.io.Serializable {
private Integer sucursalid;
private String version;
private String codigo;
private String descripcion;
private String zona;
private String direccion;
private Long ciudadcodigo;
private String telefono;
private String telefono2;
private String celular;
private String email;
private Double totventas;
private String diaoperativo;
private String ultcierre;
private String ultrecepcion;
private String utlrecepauto;
private Date ultrecekardex;
private String activa;
private String esdrogueria;
private String rutaweb;
private String lispre1;
private String lispre2;
private String lispre3;
private String lispre4;
private String lispre5;
private Date dctodesde;
private Date dctohasta;
private double porcen;
private String horacierre;
private String direccionip;
private Date horaperturagen;
private Date horacierregen;
private Date horaperturaes;
private Date horacierrees;
private String es24horas;
private String latitud;
private String longitud;
private String direccion2;
private String pervenregu;
private Set bodegases = new HashSet(0);
public Sucursales() {
}
public Sucursales(String codigo, String descripcion, String zona, String direccion, String telefono, String email,
String diaoperativo, String ultcierre, Date ultrecekardex, String activa, String esdrogueria,
Date dctodesde, Date dctohasta, double porcen, String horacierre) {
this.codigo = codigo;
this.descripcion = descripcion;
this.zona = zona;
this.direccion = direccion;
this.telefono = telefono;
this.email = email;
this.diaoperativo = diaoperativo;
this.ultcierre = ultcierre;
this.ultrecekardex = ultrecekardex;
this.activa = activa;
this.esdrogueria = esdrogueria;
this.dctodesde = dctodesde;
this.dctohasta = dctohasta;
this.porcen = porcen;
this.horacierre = horacierre;
}
public Sucursales(String codigo, String descripcion, String zona, String direccion, Long ciudadcodigo,
String telefono, String telefono2, String celular, String email, Double totventas, String diaoperativo,
String ultcierre, String ultrecepcion, String utlrecepauto, Date ultrecekardex, String activa,
String esdrogueria, String rutaweb, String lispre1, String lispre2, String lispre3, String lispre4,
String lispre5, Date dctodesde, Date dctohasta, double porcen, String horacierre, String direccionip,
Date horaperturagen, Date horacierregen, Date horaperturaes, Date horacierrees, String es24horas,
String latitud, String longitud, String direccion2, String pervenregu, Set bodegases) {
this.codigo = codigo;
this.descripcion = descripcion;
this.zona = zona;
this.direccion = direccion;
this.ciudadcodigo = ciudadcodigo;
this.telefono = telefono;
this.telefono2 = telefono2;
this.celular = celular;
this.email = email;
this.totventas = totventas;
this.diaoperativo = diaoperativo;
this.ultcierre = ultcierre;
this.ultrecepcion = ultrecepcion;
this.utlrecepauto = utlrecepauto;
this.ultrecekardex = ultrecekardex;
this.activa = activa;
this.esdrogueria = esdrogueria;
this.rutaweb = rutaweb;
this.lispre1 = lispre1;
this.lispre2 = lispre2;
this.lispre3 = lispre3;
this.lispre4 = lispre4;
this.lispre5 = lispre5;
this.dctodesde = dctodesde;
this.dctohasta = dctohasta;
this.porcen = porcen;
this.horacierre = horacierre;
this.direccionip = direccionip;
this.horaperturagen = horaperturagen;
this.horacierregen = horacierregen;
this.horaperturaes = horaperturaes;
this.horacierrees = horacierrees;
this.es24horas = es24horas;
this.latitud = latitud;
this.longitud = longitud;
this.direccion2 = direccion2;
this.pervenregu = pervenregu;
this.bodegases = bodegases;
}
public Integer getSucursalid() {
return this.sucursalid;
}
public void setSucursalid(Integer sucursalid) {
this.sucursalid = sucursalid;
}
public String getVersion() {
return this.version;
}
public void setVersion(String version) {
this.version = version;
}
public String getCodigo() {
return this.codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getDescripcion() {
return this.descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getZona() {
return this.zona;
}
public void setZona(String zona) {
this.zona = zona;
}
public String getDireccion() {
return this.direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public Long getCiudadcodigo() {
return this.ciudadcodigo;
}
public void setCiudadcodigo(Long ciudadcodigo) {
this.ciudadcodigo = ciudadcodigo;
}
public String getTelefono() {
return this.telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getTelefono2() {
return this.telefono2;
}
public void setTelefono2(String telefono2) {
this.telefono2 = telefono2;
}
public String getCelular() {
return this.celular;
}
public void setCelular(String celular) {
this.celular = celular;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public Double getTotventas() {
return this.totventas;
}
public void setTotventas(Double totventas) {
this.totventas = totventas;
}
public String getDiaoperativo() {
return this.diaoperativo;
}
public void setDiaoperativo(String diaoperativo) {
this.diaoperativo = diaoperativo;
}
public String getUltcierre() {
return this.ultcierre;
}
public void setUltcierre(String ultcierre) {
this.ultcierre = ultcierre;
}
public String getUltrecepcion() {
return this.ultrecepcion;
}
public void setUltrecepcion(String ultrecepcion) {
this.ultrecepcion = ultrecepcion;
}
public String getUtlrecepauto() {
return this.utlrecepauto;
}
public void setUtlrecepauto(String utlrecepauto) {
this.utlrecepauto = utlrecepauto;
}
public Date getUltrecekardex() {
return this.ultrecekardex;
}
public void setUltrecekardex(Date ultrecekardex) {
this.ultrecekardex = ultrecekardex;
}
public String getActiva() {
return this.activa;
}
public void setActiva(String activa) {
this.activa = activa;
}
public String getEsdrogueria() {
return this.esdrogueria;
}
public void setEsdrogueria(String esdrogueria) {
this.esdrogueria = esdrogueria;
}
public String getRutaweb() {
return this.rutaweb;
}
public void setRutaweb(String rutaweb) {
this.rutaweb = rutaweb;
}
public String getLispre1() {
return this.lispre1;
}
public void setLispre1(String lispre1) {
this.lispre1 = lispre1;
}
public String getLispre2() {
return this.lispre2;
}
public void setLispre2(String lispre2) {
this.lispre2 = lispre2;
}
public String getLispre3() {
return this.lispre3;
}
public void setLispre3(String lispre3) {
this.lispre3 = lispre3;
}
public String getLispre4() {
return this.lispre4;
}
public void setLispre4(String lispre4) {
this.lispre4 = lispre4;
}
public String getLispre5() {
return this.lispre5;
}
public void setLispre5(String lispre5) {
this.lispre5 = lispre5;
}
public Date getDctodesde() {
return this.dctodesde;
}
public void setDctodesde(Date dctodesde) {
this.dctodesde = dctodesde;
}
public Date getDctohasta() {
return this.dctohasta;
}
public void setDctohasta(Date dctohasta) {
this.dctohasta = dctohasta;
}
public double getPorcen() {
return this.porcen;
}
public void setPorcen(double porcen) {
this.porcen = porcen;
}
public String getHoracierre() {
return this.horacierre;
}
public void setHoracierre(String horacierre) {
this.horacierre = horacierre;
}
public String getDireccionip() {
return this.direccionip;
}
public void setDireccionip(String direccionip) {
this.direccionip = direccionip;
}
public Date getHoraperturagen() {
return this.horaperturagen;
}
public void setHoraperturagen(Date horaperturagen) {
this.horaperturagen = horaperturagen;
}
public Date getHoracierregen() {
return this.horacierregen;
}
public void setHoracierregen(Date horacierregen) {
this.horacierregen = horacierregen;
}
public Date getHoraperturaes() {
return this.horaperturaes;
}
public void setHoraperturaes(Date horaperturaes) {
this.horaperturaes = horaperturaes;
}
public Date getHoracierrees() {
return this.horacierrees;
}
public void setHoracierrees(Date horacierrees) {
this.horacierrees = horacierrees;
}
public String getEs24horas() {
return this.es24horas;
}
public void setEs24horas(String es24horas) {
this.es24horas = es24horas;
}
public String getLatitud() {
return this.latitud;
}
public void setLatitud(String latitud) {
this.latitud = latitud;
}
public String getLongitud() {
return this.longitud;
}
public void setLongitud(String longitud) {
this.longitud = longitud;
}
public String getDireccion2() {
return this.direccion2;
}
public void setDireccion2(String direccion2) {
this.direccion2 = direccion2;
}
public String getPervenregu() {
return this.pervenregu;
}
public void setPervenregu(String pervenregu) {
this.pervenregu = pervenregu;
}
public Set getBodegases() {
return this.bodegases;
}
public void setBodegases(Set bodegases) {
this.bodegases = bodegases;
}
}
|
import java.math.*;
// Calculate n! for n from 1 to 25 using long and BigInteger variables
public class Factorial {
public static long factorialLong(long i) {
if ( i == 1) {
return i;
}
return i * factorialLong(i - 1);
}
public static BigInteger factorialBI(int i) {
BigInteger bi = new BigInteger ("" + i);
if ( i == 1) {
return BigInteger.ONE;
}
return factorialBI(i-1).multiply(bi);
}
public static void main(String[] args) {
long n = factorialLong(20);
System.out.println(n);
BigInteger nBI = factorialBI(211);
System.out.println(nBI);
}
} |
package clases;
/**
* Esta clase perfil de usuario tiene los datos del usuario
* en una famosa red Social
*
* @author eserrano
*
*/
public class UserProfile{
/**
* Atributos de la clase
*
* <b>nick</b> atributo de tipo cadena. Los nick son unicos. Solo
* puede haber un usuario con el mismo nick. No se distingue entre
* Mayusculas y minusculas
*
* <b>regDate</b> atributo de tipo fecha "LocalDate". Registra la fecha en la que
* el usuario se dio de alta en la red social. La fecha sigue el formato
* "dd/MM/yyyy"
*
* <b>rating</b> atributo de tipo Float. almacena la media de las puntuaciones
* recibidas por popularidad recibida de otros usuarios.
*/
/**
* Metodos de la clase
*
* Generar el constructor por defecto
* Generar constructor sobrecargado con todos los atributos.
* Generar todos los getters/setters
* Generar un metodo equals que devuelve verdadero cuando el
* nick es el mismo y falso en caso contrario
*/
}
|
package model.personajes.modos;
import model.ataque.AtaqueBasico;
import model.atributos_de_unidad.Modo;
public class FreezerNormal extends Modo {
public FreezerNormal() {
nombre = "Freezer Normal";
velocidad = 4;
ataqueBasico = new AtaqueBasico(20);
distanciaDeAtaque = 2;
costoKiSiguienteTransformacion = 20;
siguienteModo = new FreezerSegundaForma();
}
} |
package conexion.jdbc;
import java.beans.PropertyVetoException;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* La clase ConexionPool.
* @see <a href="http://www.mchange.com/projects/c3p0/" target="_blank">c3p0 - JDBC3 Connection and Statement Pooling</a>
*/
public class ConexionPool {
/** El data source del pool de conexiones. */
private static ComboPooledDataSource cpds;
/** El nombre del driver. */
private static final String DRIVER_NAME = "org.sqlite.JDBC";
/** La URL a la base de datos. */
private static final String URL = "jdbc:sqlite:C:/Users/Bruno/Desktop/SeminarioII/easyGourmet/assets/databases/easygourmet.db";
static{
cpds = new ComboPooledDataSource();
try {
cpds.setDriverClass(DRIVER_NAME);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
cpds.setJdbcUrl(URL);
cpds.setMinPoolSize(3);
cpds.setMaxPoolSize(30);
cpds.setTestConnectionOnCheckin(true);
cpds.setIdleConnectionTestPeriod(300);
cpds.setMaxIdleTimeExcessConnections(240);
cpds.setAcquireIncrement(1);
}
/**
* <b>Descripción</b>- Retorna la varible de tipo ComboPooledDataSource del pool de conexiones.
*
* @return El data source
* @throws SQLException the SQL exception
*/
public synchronized static ComboPooledDataSource getDataSource() throws SQLException {
return cpds;
}
}
|
/*
* Copyright (c) 2023, WSO2 LLC. (https://www.wso2.com) All Rights Reserved.
*
* WSO2 LLC. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.auth.attribute.handler;
import org.apache.commons.lang.StringUtils;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.identity.application.common.model.AuthenticationStep;
import org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig;
import org.wso2.carbon.identity.application.mgt.ApplicationManagementService;
import org.wso2.carbon.identity.auth.attribute.handler.exception.AuthAttributeHandlerClientException;
import org.wso2.carbon.identity.auth.attribute.handler.exception.AuthAttributeHandlerException;
import org.wso2.carbon.identity.auth.attribute.handler.internal.AuthAttributeHandlerServiceDataHolder;
import org.wso2.carbon.identity.auth.attribute.handler.model.AuthAttributeHolder;
import org.wso2.carbon.identity.auth.attribute.handler.model.ValidationResult;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
/**
* Unit test for AuthAttributeHandlerManager.
*/
public class AuthAttributeHandlerManagerTest {
private AuthAttributeHandlerManager authAttributeHandlerManager = AuthAttributeHandlerManager.getInstance();
private static final String APP_ID = "0181313d-5c84-4ec4-a931-b73085408eff";
private static final String AUTHENTICATOR_BASICAUTH = "BasicAuthenticator";
private static final String AUTH_ATTRIBUTE_HANDLER_MAGICLINK = "MagicLinkAuthAttributeHandler";
private static final String AUTHENTICATOR_MAGICLINK = "MagicLinkAuthenticator";
private static final String AUTHENTICATOR_FIDO = "FIDOAuthenticator";
private static final String AUTHENTICATOR_TOTP = "TOTPAuthenticator";
private static final String AUTHENTICATOR_SMSOTP = "SMSOTPAuthenticator";
private static final String[] EXPECTED_HANDLERS = new String[]{AUTHENTICATOR_BASICAUTH, AUTHENTICATOR_MAGICLINK,
AUTHENTICATOR_FIDO};
@Mock
ApplicationManagementService applicationManagementService;
@Mock
AuthAttributeHandlerServiceDataHolder authAttributeHandlerServiceDataHolder;
private MockedStatic<AuthAttributeHandlerServiceDataHolder> mockedAuthAttributeHandlerServiceDataHolder;
@BeforeClass
private void setup() {
MockitoAnnotations.openMocks(this);
initiateMocks();
}
@AfterClass
public void tearDown() {
mockedAuthAttributeHandlerServiceDataHolder.close();
}
@Test
public void testGetAvailableAuthAttributeHolders() {
try {
when(applicationManagementService.getConfiguredAuthenticators(anyString()))
.thenReturn(getAuthenticators());
List<AuthAttributeHolder> authAttributeHolders =
authAttributeHandlerManager.getAvailableAuthAttributeHolders(APP_ID);
Assert.assertEquals(authAttributeHolders.size(), EXPECTED_HANDLERS.length, "Expected 3 auth attribute " +
"holders but there is " + authAttributeHolders.size());
String[] authAttributeHandlers = getAuthAttributeHandlers(authAttributeHolders);
Assert.assertEqualsNoOrder(authAttributeHandlers, EXPECTED_HANDLERS,
String.format("Expected auth attribute handlers: %s actual auth attribute handlers: %s",
StringUtils.join(EXPECTED_HANDLERS, ","),
StringUtils.join(authAttributeHandlers, ",")));
} catch (Exception e) {
Assert.fail("Test threw an unexpected exception.", e);
}
}
@Test
public void testValidateAuthAttributes() {
try {
ValidationResult validationResult =
authAttributeHandlerManager.validateAuthAttributes(AUTH_ATTRIBUTE_HANDLER_MAGICLINK,
getAttributeMap());
Assert.assertNotNull(validationResult, "Expected ValidationResult to be not null.");
} catch (Exception e) {
Assert.fail("Test threw an unexpected exception.", e);
}
}
@Test
public void testValidateAuthAttributesWithInvalidHandlerName() {
boolean isClientExceptionThrown = false;
try {
ValidationResult validationResult =
authAttributeHandlerManager.validateAuthAttributes(AUTHENTICATOR_SMSOTP, getAttributeMap());
} catch (AuthAttributeHandlerClientException e) {
isClientExceptionThrown = true;
Assert.assertEquals(e.getErrorCode(),
AuthAttributeHandlerConstants.ErrorMessages.ERROR_CODE_AUTH_ATTRIBUTE_HANDLER_NOT_FOUND.getCode(),
"Expected error code not found.");
} catch (Exception e) {
Assert.fail("Test threw an unexpected exception.", e);
}
if (!isClientExceptionThrown) {
Assert.fail("Expected to throw a AuthAttributeHandlerClientException but no exception was thrown.");
}
}
private String[] getAuthAttributeHandlers(List<AuthAttributeHolder> authAttributeHolderList) {
List<String> authAttributeHandlers = new ArrayList<>();
for (AuthAttributeHolder authAttributeHolder :
authAttributeHolderList) {
authAttributeHandlers.add(authAttributeHolder.getHandlerName());
}
return authAttributeHandlers.toArray(new String[0]);
}
private void initiateMocks() {
mockedAuthAttributeHandlerServiceDataHolder = Mockito.mockStatic(AuthAttributeHandlerServiceDataHolder.class);
mockedAuthAttributeHandlerServiceDataHolder.when(AuthAttributeHandlerServiceDataHolder::getInstance)
.thenReturn(authAttributeHandlerServiceDataHolder);
when(authAttributeHandlerServiceDataHolder.getApplicationManagementService())
.thenReturn(applicationManagementService);
when(authAttributeHandlerServiceDataHolder.getAuthAttributeHandlers())
.thenReturn(getAuthAttributeHandlers());
}
private AuthenticationStep[] getAuthenticators() {
List<AuthenticationStep> authenticationSteps = new ArrayList<>();
authenticationSteps.add(getAuthenticationStep(new String[]{AUTHENTICATOR_BASICAUTH, AUTHENTICATOR_MAGICLINK}));
authenticationSteps.add(getAuthenticationStep(new String[]{AUTHENTICATOR_FIDO, AUTHENTICATOR_SMSOTP}));
return authenticationSteps.toArray(new AuthenticationStep[0]);
}
private LocalAuthenticatorConfig getLocalAuthenticatorConfig(String name) {
LocalAuthenticatorConfig localAuthenticatorConfig = new LocalAuthenticatorConfig();
localAuthenticatorConfig.setName(name);
return localAuthenticatorConfig;
}
private AuthenticationStep getAuthenticationStep(String[] authenticators) {
List<LocalAuthenticatorConfig> localAuthenticatorConfigs = new ArrayList<>();
for (String authenticator : authenticators) {
localAuthenticatorConfigs.add(getLocalAuthenticatorConfig(authenticator));
}
AuthenticationStep authenticationStep = new AuthenticationStep();
authenticationStep.setLocalAuthenticatorConfigs(
localAuthenticatorConfigs.toArray(new LocalAuthenticatorConfig[0]));
return authenticationStep;
}
private List<AuthAttributeHandler> getAuthAttributeHandlers() {
List<AuthAttributeHandler> authAttributeHandlers = new ArrayList<>();
authAttributeHandlers.add(new BasicAuthAttributeHandler());
authAttributeHandlers.add(new MagicLinkAttributeHandler());
authAttributeHandlers.add(new FIDOAttributeHandler());
authAttributeHandlers.add(new TOTPAttributeHandler());
return authAttributeHandlers;
}
private AuthAttributeHolder getAuthAttributeHolder(String name) {
AuthAttributeHolder authAttributeHolder = new AuthAttributeHolder();
authAttributeHolder.setHandlerName(name);
authAttributeHolder.setHandlerBinding(AuthAttributeHandlerBindingType.AUTHENTICATOR);
authAttributeHolder.setHandlerBoundIdentifier(name);
return authAttributeHolder;
}
private Map<String, String> getAttributeMap() {
Map<String, String> attributeMap = new HashMap<>();
attributeMap.put("email", "johndoe@abc.com");
attributeMap.put("username", "johndoe");
return attributeMap;
}
class BasicAuthAttributeHandler extends MockAbstractAuthAttributeHandler {
@Override
public AuthAttributeHolder getAuthAttributeData() throws AuthAttributeHandlerException {
return getAuthAttributeHolder(AUTHENTICATOR_BASICAUTH);
}
@Override
public String getBoundIdentifier() throws AuthAttributeHandlerException {
return AUTHENTICATOR_BASICAUTH;
}
}
class MagicLinkAttributeHandler extends MockAbstractAuthAttributeHandler {
@Override
public String getName() throws AuthAttributeHandlerException {
return AUTH_ATTRIBUTE_HANDLER_MAGICLINK;
}
@Override
public AuthAttributeHolder getAuthAttributeData() throws AuthAttributeHandlerException {
return getAuthAttributeHolder(AUTHENTICATOR_MAGICLINK);
}
@Override
public String getBoundIdentifier() throws AuthAttributeHandlerException {
return AUTHENTICATOR_MAGICLINK;
}
@Override
public ValidationResult validateAttributes(Map<String, String> attributeMap)
throws AuthAttributeHandlerException {
return new ValidationResult(true);
}
}
class FIDOAttributeHandler extends MockAbstractAuthAttributeHandler {
@Override
public AuthAttributeHolder getAuthAttributeData() throws AuthAttributeHandlerException {
return getAuthAttributeHolder(AUTHENTICATOR_FIDO);
}
@Override
public String getBoundIdentifier() throws AuthAttributeHandlerException {
return AUTHENTICATOR_FIDO;
}
}
class TOTPAttributeHandler extends MockAbstractAuthAttributeHandler {
@Override
public AuthAttributeHolder getAuthAttributeData() throws AuthAttributeHandlerException {
return getAuthAttributeHolder(AUTHENTICATOR_TOTP);
}
@Override
public String getBoundIdentifier() throws AuthAttributeHandlerException {
return AUTHENTICATOR_TOTP;
}
}
}
|
package com.dbs.util;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.log4j.Logger;
public class CipherHelper {
private Logger logger = Logger.getLogger(this.getClass());
public String encrypt(String value){
try{
Cipher cipher;
Key key = getKey();
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
return new String (Base64.encode(cipher.doFinal(value.getBytes("UTF-8"))));
}catch(Exception e){
logger.error(e.getMessage(), e);
}
return null;
}
public String decrypt(String value){
try{
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
Key key = getKey();
cipher.init(Cipher.DECRYPT_MODE,key,cipher.getParameters());
byte[] byteDecryptedText = cipher.doFinal(Base64.decode(value.getBytes("UTF-8")));
return new String(byteDecryptedText);
}catch(Exception e){
logger.error(e.getMessage(), e);
}
return null;
}
public Key getKey() throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException{
MessageDigest digester = MessageDigest.getInstance("MD5");
String key = "Abcd1234";
char[] password = key.toCharArray();
for (int i = 0; i < password.length; i++) {
digester.update((byte) password[i]);
}
byte[] passwordData = digester.digest();
Key secretkey = new SecretKeySpec(passwordData, "AES");
return secretkey;
}
} |
package com.gestion.service.impression;
import java.io.FileOutputStream;
import java.util.Date;
import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Header;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class Test {
private static String FILE = "FirstPdf.pdf";
private static Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD, BaseColor.BLACK);
private static Font redFont = new Font(Font.FontFamily.TIMES_ROMAN, 12,Font.BOLDITALIC, BaseColor.RED);
private static Font subFont = new Font(Font.FontFamily.TIMES_ROMAN, 16, Font.UNDERLINE, BaseColor.BLACK);
private static Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12,Font.BOLD, BaseColor.BLACK);
public static void addMetaData(Document document) {
document.addTitle("My first PDF");
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Lars Vogel");
document.addCreator("Lars Vogel");
}
public static void addTitlePage(Document document , String title)
throws DocumentException {
Paragraph preface = new Paragraph();
// We add one empty line
addEmptyLine(preface, 1);
// Lets write a big header
preface.add(new Paragraph(title, catFont));
preface.getChunks();
Chunk vv = new Chunk();
preface.add(vv);
/*addEmptyLine(preface, 1);
// Will create: Report generated by: _name, _date
preface.add(new Paragraph("Report generated by: " + System.getProperty("user.name") + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
smallBold));
addEmptyLine(preface, 3);
preface.add(new Paragraph("This document describes something which is very important ",
smallBold));
addEmptyLine(preface, 8);
preface.add(new Paragraph("This document is a preliminary version and not subject to your license agreement or any other agreement with vogella.com ;-).",
redFont));*/
document.add(preface);
// Start a new page
document.newPage();
}
public static void addTable(Document document) throws BadElementException, DocumentException
{
document.add(createTable());//Header header = new Header("nom", content)
}
public static void addContent(Document document) throws DocumentException {
Anchor anchor = new Anchor("First Chapter", catFont);
anchor.setName("First Chapter");
// Second parameter is the number of the chapter
Chapter catPart = new Chapter(new Paragraph(anchor), 1);
Paragraph subPara = new Paragraph("Subcategory 1", subFont);
Section subCatPart = catPart.addSection(subPara);
subCatPart.add(new Paragraph("Hello"));
subPara = new Paragraph("Subcategory 2", subFont);
subCatPart = catPart.addSection(subPara);
subCatPart.add(new Paragraph("Paragraph 1"));
subCatPart.add(new Paragraph("Paragraph 2"));
subCatPart.add(new Paragraph("Paragraph 3"));
// add a list
createList(subCatPart);
Paragraph paragraph = new Paragraph();
addEmptyLine(paragraph, 5);
subCatPart.add(paragraph);
// add a table
// now add all this to the document
document.add(catPart);
// Next section
anchor = new Anchor("Second Chapter", catFont);
anchor.setName("Second Chapter");
// Second parameter is the number of the chapter
catPart = new Chapter(new Paragraph(anchor), 1);
subPara = new Paragraph("Subcategory", subFont);
subCatPart = catPart.addSection(subPara);
subCatPart.add(new Paragraph("This is a very important message"));
// now add all this to the document
document.add(catPart);
}
public static PdfPTable createTable()
throws BadElementException {
PdfPTable table = new PdfPTable(3);
// t.setBorderColor(BaseColor.GRAY);
// t.setPadding(4);
// t.setSpacing(4);
// t.setBorderWidth(1);
PdfPCell c1 = new PdfPCell(new Phrase("Table Header 1"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Table Header 2"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Table Header 3"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
table.setHeaderRows(1);
table.addCell("1.0");
table.addCell("1.1");
table.addCell("1.2");
table.addCell("2.1");
table.addCell("2.2");
table.addCell("2.3");
return table;
}
public static void createList(Section subCatPart) {
List list = new List(true, false, 10);
list.add(new ListItem("First point"));
list.add(new ListItem("Second point"));
list.add(new ListItem("Third point"));
subCatPart.add(list);
}
public static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
} |
import java.time.LocalDate;
public abstract class User {
public abstract String name();
public abstract String email();
public abstract String creditNum();
public abstract LocalDate creditExpDate();
public abstract String secCode();
public abstract String zipCode();
}
|
package com.ufrpe.ppgia.quantumapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.ufrpe.ppgia.quantumapp.fragments.AboutFragment;
import com.ufrpe.ppgia.quantumapp.fragments.ControledNotFragment;
import com.ufrpe.ppgia.quantumapp.fragments.ControledPhaseFragment;
import com.ufrpe.ppgia.quantumapp.fragments.EditorFragment;
import com.ufrpe.ppgia.quantumapp.fragments.PauliFragment;
import com.ufrpe.ppgia.quantumapp.fragments.SwapFragment;
import com.ufrpe.ppgia.quantumapp.fragments.ControledZFragment;
import com.ufrpe.ppgia.quantumapp.fragments.FaseFragment;
import com.ufrpe.ppgia.quantumapp.fragments.FundamentalsFragment;
import com.ufrpe.ppgia.quantumapp.fragments.HadamardFragment;
import com.ufrpe.ppgia.quantumapp.fragments.HistoryFragment;
import com.ufrpe.ppgia.quantumapp.fragments.Pi8Fragment;
import com.ufrpe.ppgia.quantumapp.fragments.TeamFragment;
public class MainActivityDrawer extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FragmentManager mFragmentManager;
private Fragment mFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_drawer);
this.mFragmentManager = getSupportFragmentManager();
this.mFragment = mFragmentManager.findFragmentById(R.id.fragment_container);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
mFragment = new EditorFragment();
mFragmentManager.beginTransaction()
.replace(R.id.fragment_container, mFragment)
.commit();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_drawer, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
startActivity( new Intent(getApplicationContext(), SettingsActivity.class) );
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.sub_menu_editor) {
mFragment = new EditorFragment();
mFragmentManager.beginTransaction()
.replace(R.id.fragment_container, mFragment)
.commit();
} else if (id == R.id.sub_menu_history) {
mFragment = new HistoryFragment();
mFragmentManager.beginTransaction()
.replace(R.id.fragment_container, mFragment)
.commit();
} else if (id == R.id.sub_menu_fundamentals) {
mFragment = new FundamentalsFragment();
mFragmentManager.beginTransaction()
.replace(R.id.fragment_container, mFragment)
.commit();
} else if (id == R.id.sub_menu_hadamard) {
mFragment = new HadamardFragment();
mFragmentManager.beginTransaction()
.replace(R.id.fragment_container, mFragment)
.commit();
} else if (id == R.id.sub_menu_pauli_matrix) {
mFragment = new PauliFragment();
mFragmentManager.beginTransaction()
.replace(R.id.fragment_container, mFragment)
.commit();
} else if (id == R.id.sub_menu_fase) {
mFragment = new FaseFragment();
mFragmentManager.beginTransaction()
.replace(R.id.fragment_container, mFragment)
.commit();
} else if (id == R.id.sub_menu_pi_8) {
mFragment = new Pi8Fragment();
mFragmentManager.beginTransaction()
.replace(R.id.fragment_container, mFragment)
.commit();
}
// else if (id == R.id.sub_menu_controled_not) {
// mFragment = new ControledNotFragment();
// mFragmentManager.beginTransaction()
// .replace(R.id.fragment_container, mFragment)
// .commit();
//
// } else if (id == R.id.sub_menu_controled_z) {
// mFragment = new ControledZFragment();
// mFragmentManager.beginTransaction()
// .replace(R.id.fragment_container, mFragment)
// .commit();
//
// } else if (id == R.id.sub_menu_controled_phase) {
// mFragment = new ControledPhaseFragment();
// mFragmentManager.beginTransaction()
// .replace(R.id.fragment_container, mFragment)
// .commit();
//
// } else if (id == R.id.sub_menu_swap) {
// mFragment = new SwapFragment();
// mFragmentManager.beginTransaction()
// .replace(R.id.fragment_container, mFragment)
// .commit();
//
// }
else if (id == R.id.sub_menu_about_app) {
mFragment = new AboutFragment();
mFragmentManager.beginTransaction()
.replace(R.id.fragment_container, mFragment)
.commit();
} else if (id == R.id.sub_menu_about_team) {
mFragment = new TeamFragment();
mFragmentManager.beginTransaction()
.replace(R.id.fragment_container, mFragment)
.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
|
package graphics_control.game_control;
import game_object.Cell;
import graphics_control.files_and_parsing.FileCreator;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.stage.Stage;
import java.io.*;
import java.net.URL;
import java.nio.file.Files;
import java.util.ResourceBundle;
import static javafx.fxml.FXMLLoader.load;
public class PreferencesController implements Initializable {
ObservableList<String> firstTurnSelections =
FXCollections.observableArrayList(
"Player1",
"Player2"
);
ObservableList<String> diskColors =
FXCollections.observableArrayList(
Cell.BLACK.toString(), Cell.WHITE.toString(),
Cell.RED.toString(), Cell.GREEN.toString(), Cell.BLUE.toString(),
Cell.BROWN.toString(), Cell.ORANGE.toString()
);
ObservableList<String> boardSizes =
FXCollections.observableArrayList(
"4x4", "6x6", "8x8",
"10x10", "12x12", "14x14",
"16x16", "18x18", "20x20"
);
private FileCreator fileCreator;
@FXML
private ComboBox firstTurn;
@FXML
private ComboBox player1Color;
@FXML
private ComboBox player2Color;
@FXML
private ComboBox boardSize;
@FXML
private Button apply;
/**
* initialize().
*/
@FXML
public void initialize(URL location, ResourceBundle resources) {
firstTurn.setItems(firstTurnSelections);
player1Color.setItems(diskColors);
player2Color.setItems(diskColors);
boardSize.setItems(boardSizes);
firstTurn.setValue(FileCreator.DEFAULT_FIRST_TURN);
player1Color.setValue(FileCreator.DEFAULT_PLAYER1_COLOR);
player2Color.setValue(FileCreator.DEFAULT_PLAYER2_COLOR);
boardSize.setValue(FileCreator.DEFAULT_BOARD_SIZE);
this.fileCreator = new FileCreator();
}
/**
* applyChanges().
*/
public void applyChanges() {
BufferedWriter bufferedWriter = null;
try {
File file = new File("preferences.txt");
bufferedWriter = new BufferedWriter(new FileWriter(file));
} catch(Exception e) {
System.out.println(e.getCause().toString());
}
String preferences = "firstTurnPlayer: " + firstTurn.getValue().toString() + "\nplayer1Color: " +
player1Color.getValue().toString() + "\nplayer2Color: " + player2Color.getValue().toString() +
"\nboardSize: " + boardSize.getValue().toString();
try {
try {
bufferedWriter.write(preferences);
} catch (NullPointerException e) {
System.out.println(e.getCause().toString());
}
bufferedWriter.close();
} catch (IOException e) {
System.out.println(e.getCause().toString());
}
ReversiMain reversiMain = new ReversiMain();
Stage stage = (Stage) apply.getScene().getWindow();
try {
reversiMain.start(stage);
} catch (Exception e) {
}
}
}
|
package bicycles.rides;
import bicycles.Bicycle;
import bicycles.BicycleType;
import bicycles.specification.BicycleFromSpec;
import bicycles.specification.BicycleSpecification;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class BikeRideForMountainBike {
@Test
public void MountainBikeRideOne(){
BicycleSpecification mountainBikeSpec = new BicycleSpecification(5, -3, BicycleType.MOUNTAINBIKE);
Bicycle mountainBike = new BicycleFromSpec(mountainBikeSpec);
BikeRideOne mBikeRide = new BikeRideOne(mountainBike);
mBikeRide.ride();// MountainBike
assertEquals(14,mBikeRide.currentSpeed());
}
@Test
public void MountainBikeRideTwo(){
BicycleSpecification mountainBikeSpec = new BicycleSpecification(5, -3, BicycleType.MOUNTAINBIKE);
Bicycle mountainBike = new BicycleFromSpec(mountainBikeSpec);
BikeRideTwo mBikeRide = new BikeRideTwo(mountainBike);
mBikeRide.ride();// MountainBike
assertEquals(31,mBikeRide.currentSpeed());
}
@Test
public void MountainBikeRideThree(){
BicycleSpecification mountainBikeSpec = new BicycleSpecification(5, -3, BicycleType.MOUNTAINBIKE);
Bicycle mountainBike = new BicycleFromSpec(mountainBikeSpec);
BikeRideThree mBikeRide = new BikeRideThree(mountainBike);
mBikeRide.ride();// MountainBike
assertEquals(16,mBikeRide.currentSpeed());
}
}
|
import java.util.*;
import java.text.DecimalFormat;
import java.io.*;
public class HuffmanTree
{
ArrayList<Character> c=new ArrayList<Character>();
Node root;
String decoded="";
PriorityQueue<Node> pq;
PriorityQueue<Node> p;
Comparator<Node> comp=new MyComparator();
String message;
String huffCode="";
Map<Character, String> char_code = new HashMap<Character, String>();
public HuffmanTree(String m)
{
message=m;
message=message.trim();
}
/* Main function to build Huffman tree */
public void HuffmanCode()
{
String text=message;
/* Count the frequency of each character in the string */
//if the character does not exist in the list add it
for(int i=0;i<text.length();i++)
{
if(!(c.contains(text.charAt(i))))
c.add(text.charAt(i));
}
int[] freq=new int[c.size()];
//counting the frequency of each character in the text
for(int i=0;i<c.size();i++)
for(int j=0;j<text.length();j++)
if(c.get(i)==text.charAt(j))
freq[i]++;
/* Build the huffman tree */
root= buildTree(freq);
}
/* This function builds the Huffman tree */
public Node buildTree(int[] frequency)
{
/* Initialize the priority queue */
pq=new PriorityQueue<Node>(c.size(),comp);
p=new PriorityQueue<Node>(c.size(),comp);
/* Create leaf node for each unique character in the string */
for(int i = 0; i < c.size(); i++)
{
pq.offer(new Node(c.get(i), frequency[i], null, null));
}
createCopy(pq);
/* Until there is only one node in the priority queue */
while(pq.size() > 1)
{
/* Minimum frequency is kept in the left */
Node left = pq.poll();
/* Next minimum frequency is kept in the right */
Node right = pq.poll();
/* Create a new internal node as the parent of left and right */
pq.offer(new Node('\0', left.frequency+right.frequency, left, right));
}
/* Return the only node which is the root */
return pq.poll();
}
public void createCode()
{
createCodeRecursive(root,"");
}
public void createCodeRecursive(Node t,String c)
{
if(t!=null)
{
if(t.left==null && t.right==null)
char_code.put(t.character,c);
if(t.left!=null)
createCodeRecursive(t.left,c+"0");
if(t.right!=null)
createCodeRecursive(t.right,c+"1");
}
}
public String getEncodedMessage()
{
for(int i=0;i<message.length();i++)
huffCode+=char_code.get(message.charAt(i));
return huffCode;
}
public String decomp(String code)
{
return decompress(root,code,code.length(),0);
}
public String decompress(Node t, String c,int l,int i)
{
if(l==0)
return String.valueOf(t.character);
else
if(t.left==null && t.right==null)
return String.valueOf(t.character)+decompress(root,c,l,i);
else
if(c.charAt(i) == '0')
return decompress(t.left,c,--l,++i);
else
if(c.charAt(i) == '1')
return decompress(t.right,c,--l,++i);
return "";
}
public String disp()
{
String stringreturn="";
stringreturn+="The total number of letters are:"+root.frequency;
stringreturn+="\n-------------------------------------------------------\n\n";
stringreturn+="Characters \t : Frequency\n";
stringreturn+="----------------------------------------------------------------\n";
Iterator it=p.iterator();
while(it.hasNext())
stringreturn+=(Node)it.next();
stringreturn+="\n-------------------------------------------------------\n";
stringreturn+="-------------------------------------------------------\n\n";
stringreturn+="Characters \t : \tHuffmanCodes";
stringreturn+="\n---------------------------------------------------------------";
for (Map.Entry<Character, String> entry : char_code.entrySet())
{
stringreturn+="\n"+entry.getKey()+" \t : \t "+entry.getValue();
}
stringreturn+="\n\nCompression Ratio: "+calcCompRatio()+"%"+"\n";
PrintWriter fout=null;
try
{
writeToFile(fout);
}
catch(IOException e)
{}
return stringreturn;
}
public void writeToFile(PrintWriter fout)throws IOException
{
fout = new PrintWriter("Files/statistics.txt");
fout.println("\nThe total number of letters are:"+root.frequency);
fout.println("------------------------------------------------------------\n\n");
fout.println("Characters \t : \t Frequency");
Iterator it=p.iterator();
while(it.hasNext())
fout.println("\t"+(Node)it.next());
fout.println("-----------------------------------------------------------\n\n");
fout.println("Characters \t : \t HuffmanCodes");
fout.println("-------------------------------------------------------------");
for (Map.Entry<Character, String> entry : char_code.entrySet())
{
fout.println("\t"+entry.getKey()+" \t : \t "+entry.getValue());
}
fout.println("\n\n***************************************");
fout.println("\n\nCompression Ratio: "+calcCompRatio());
fout.println("***************************************");
if(fout !=null)
fout.close();
}
public void createCopy(PriorityQueue<Node> q)
{
Iterator it=q.iterator();
while(it.hasNext())
{
p.offer((Node)it.next());
}
}
public double calcCompRatio()
{
double compressionRatio=(1-((huffCode.length()*1)/((double)(root.frequency*8))))*100;
DecimalFormat cr=new DecimalFormat("#.##");
compressionRatio=Double.valueOf(cr.format(compressionRatio));
return compressionRatio;
}
}
|
package velvet.obj;
public class OBJVertex
{
public float[] position;
public float[] texture;
public float[] normal;
}
|
package de.mq.vaadin.util;
@FunctionalInterface
public interface Observer<EventType> {
void process(final EventType event);
} |
package modelo;
import modelo.excepciones.PasosInsuficientes;
public class Movimiento {
private int cantidadPasosMoverse;
private Posicion posicionActual;
public Movimiento(int velocidad,Posicion pos){
this.cantidadPasosMoverse = velocidad;
this.posicionActual = pos;
}
public Posicion getPosicion() {
return this.posicionActual;
}
public void MoverArriba(Tablero tablero){
if(this.cantidadPasosMoverse == 0) throw new PasosInsuficientes();
Posicion posicionAMoverme = new Posicion(this.posicionActual.getCoordenadaX(),this.posicionActual.getCoordenadaY()+1);
tablero.moverPersonaje(this.posicionActual, posicionAMoverme);
this.cantidadPasosMoverse -= 1;
this.posicionActual = posicionAMoverme;
}
public void MoverAbajo(Tablero tablero){
if(this.cantidadPasosMoverse == 0) throw new PasosInsuficientes();
Posicion posicionAMoverme = new Posicion(this.posicionActual.getCoordenadaX(),this.posicionActual.getCoordenadaY()-1);
tablero.moverPersonaje(posicionActual, posicionAMoverme);
this.cantidadPasosMoverse -= 1;
this.posicionActual = posicionAMoverme;
}
public void MoverDerecha(Tablero tablero){
if(this.cantidadPasosMoverse == 0) throw new PasosInsuficientes();
Posicion posicionAMoverme = new Posicion(this.posicionActual.getCoordenadaX()+1,this.posicionActual.getCoordenadaY());
tablero.moverPersonaje(posicionActual, posicionAMoverme);
this.cantidadPasosMoverse -= 1;
this.posicionActual = posicionAMoverme;
}
public void MoverIzquierda(Tablero tablero){
if(this.cantidadPasosMoverse == 0) throw new PasosInsuficientes();
Posicion posicionAMoverme = new Posicion(this.posicionActual.getCoordenadaX()-1,this.posicionActual.getCoordenadaY());
tablero.moverPersonaje(posicionActual, posicionAMoverme);
this.cantidadPasosMoverse -= 1;
this.posicionActual = posicionAMoverme;
}
public void MoverArribaDerecha(Tablero tablero){
if(this.cantidadPasosMoverse == 0) throw new PasosInsuficientes();
Posicion posicionAMoverme = new Posicion(this.posicionActual.getCoordenadaX()+1,this.posicionActual.getCoordenadaY()+1);
tablero.moverPersonaje(posicionActual, posicionAMoverme);
this.cantidadPasosMoverse -= 1;
this.posicionActual = posicionAMoverme;
}
public void MoverArribaIzquierda(Tablero tablero){
if(this.cantidadPasosMoverse == 0) throw new PasosInsuficientes();
Posicion posicionAMoverme = new Posicion(this.posicionActual.getCoordenadaX()-1,this.posicionActual.getCoordenadaY()+1);
tablero.moverPersonaje(posicionActual, posicionAMoverme);
this.cantidadPasosMoverse -= 1;
this.posicionActual = posicionAMoverme;
}
public void MoverAbajoDerecha(Tablero tablero){
if(this.cantidadPasosMoverse == 0) throw new PasosInsuficientes();
Posicion posicionAMoverme = new Posicion(this.posicionActual.getCoordenadaX()+1,this.posicionActual.getCoordenadaY()-1);
tablero.moverPersonaje(posicionActual, posicionAMoverme);
this.cantidadPasosMoverse -= 1;
this.posicionActual = posicionAMoverme;
}
public void MoverAbajoIzquierda(Tablero tablero){
if(this.cantidadPasosMoverse == 0) throw new PasosInsuficientes();
Posicion posicionAMoverme = new Posicion(this.posicionActual.getCoordenadaX()-1,this.posicionActual.getCoordenadaY()-1);
tablero.moverPersonaje(this.posicionActual, posicionAMoverme);
this.cantidadPasosMoverse -= 1;
this.posicionActual = posicionAMoverme;
}
public void actualizarCantidadPasos(int velocidad) {
this.cantidadPasosMoverse = velocidad;
}
public int getRestantes() {
if (this.cantidadPasosMoverse==0) throw new PasosInsuficientes();
return this.cantidadPasosMoverse;
}
}
|
package ru.pft.addressbook.appmanager;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import ru.pft.addressbook.model.GroupData;
import ru.pft.addressbook.model.Groups;
import ru.pft.addressbook.model.PersonData;
import ru.pft.addressbook.model.Persons;
import java.util.List;
/**
* Класс для работы с БД.
*
* @author tovChe
* @version 1.5
*/
public class DbHelper {
private final SessionFactory sessionFactory;
public DbHelper() {
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
}
/**
* <p>Получаем список групп из БД.</p>
*
* @return result - список групп
*/
public Groups groups() {
Session session = sessionFactory.openSession();
session.beginTransaction();
List result = session.createQuery("from ru.pft.addressbook.model.GroupData").list();
for (GroupData group : (List<GroupData>) result) {
System.out.println(group);
}
session.getTransaction().commit();
session.close();
return new Groups(result);
}
/**
* <p>Получаем список контактов из БД.</p>
*
* @return result - список контактов с ограничением deprecated
*/
public Persons persons() {
Session session = sessionFactory.openSession();
session.beginTransaction();
List<PersonData> result = session.createQuery("from PersonData where deprecated = '0000-00-00'").list();
session.getTransaction().commit();
session.close();
return new Persons(result);
}
/**
* <p>Обновляет список групп.</p>
*
* @param groups Принимает группу в которую был добавлен контакт
*/
public void groupsNextQuery(GroupData groups) {
Session session = sessionFactory.openSession();
session.refresh(groups); // обновление ранее полученного списка групп
// Также возможно сделать так же как public Groups groups()
session.close();
}
/**
* <p>Обновляет список контактов.</p>
*
* @param persons Принимает контакт добавленный в группу
*/
public void personNextQuery(PersonData persons) {
Session session = sessionFactory.openSession();
session.refresh(persons); // обновление ранее полученного списка контактов
// Также возможно сделать так же как public Persons persons()
session.close();
}
}
|
/*
* This file is part of the LIRE project: http://www.semanticmetadata.net/lire
* LIRE 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.
*
* LIRE 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 LIRE; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* We kindly ask you to refer the any or one of the following publications in
* any publication mentioning or employing Lire:
*
* Lux Mathias, Savvas A. Chatzichristofis. Lire: Lucene Image Retrieval –
* An Extensible Java CBIR Library. In proceedings of the 16th ACM International
* Conference on Multimedia, pp. 1085-1088, Vancouver, Canada, 2008
* URL: http://doi.acm.org/10.1145/1459359.1459577
*
* Lux Mathias. Content Based Image Retrieval with LIRE. In proceedings of the
* 19th ACM International Conference on Multimedia, pp. 735-738, Scottsdale,
* Arizona, USA, 2011
* URL: http://dl.acm.org/citation.cfm?id=2072432
*
* Mathias Lux, Oge Marques. Visual Information Retrieval using Java and LIRE
* Morgan & Claypool, 2013
* URL: http://www.morganclaypool.com/doi/abs/10.2200/S00468ED1V01Y201301ICR025
*
* Copyright statement:
* ====================
* (c) 2002-2013 by Mathias Lux (mathias@juggle.at)
* http://www.semanticmetadata.net/lire, http://www.lire-project.net
*
* Updated: 02.06.13 08:13
*/
package org.exist.xquery.modules.mpeg7.net.semanticmetadata.lire.indexing.tools;
import org.exist.xquery.modules.mpeg7.net.semanticmetadata.lire.imageanalysis.LireFeature;
import org.exist.xquery.modules.mpeg7.net.semanticmetadata.lire.imageanalysis.PHOG;
import org.exist.xquery.modules.mpeg7.net.semanticmetadata.lire.indexing.hashing.BitSampling;
import org.exist.xquery.modules.mpeg7.net.semanticmetadata.lire.utils.SerializationUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
/**
* This class extends Indexor and does hashing (bit sampling) on a given feature.
* The hashes are stored in a Lucene field named "Hashes".
* <p/>
* Created: 21.03.13 10:03
*
* @author Mathias Lux, mathias@juggle.at
*/
public class HashingIndexor extends Indexor {
protected Class featureClass = PHOG.class;
public static void main(String[] args) throws IOException, IllegalAccessException, InstantiationException {
HashingIndexor indexor = new HashingIndexor();
BitSampling.readHashFunctions();
// BitSampling.readHashFunctions(new FileInputStream(BitSampling.hashFunctionsFileName));
// LocalitySensitiveHashing.readHashFunctions();
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.startsWith("-i") || arg.startsWith("--input-file")) {
// infile ...
if ((i + 1) < args.length)
indexor.addInputFile(new File(args[i + 1]));
else printHelp();
} else if (arg.startsWith("-l") || arg.startsWith("--index")) {
// index
if ((i + 1) < args.length)
indexor.setIndexPath(args[i + 1]);
else printHelp();
} else if (arg.startsWith("-f") || arg.startsWith("--feature")) {
// index
if ((i + 1) < args.length)
try {
indexor.setFeatureClass(Class.forName(args[i + 1]));
} catch (ClassNotFoundException e) {
System.err.println("Could not find feature class named " + args[i + 1]);
printHelp();
}
else printHelp();
} else if (arg.startsWith("-h")) {
// help
printHelp();
} else if (arg.startsWith("-s")) {
// silent ...
verbose = false;
} else if (arg.startsWith("-c")) {
// list of input files within a file.
if ((i + 1) < args.length) {
BufferedReader br = new BufferedReader(new FileReader(new File(args[i + 1])));
String file;
while ((file = br.readLine()) != null) {
if (file.trim().length() > 2) {
File f = new File(file);
if (f.exists()) indexor.addInputFile(f);
else System.err.println("Did not find file " + f.getName());
}
}
} else printHelp();
}
}
// check if there is an infile, an outfile and some features to extract.
if (!indexor.isConfigured()) {
printHelp();
} else {
indexor.run();
}
}
public void setFeatureClass(Class featureClass) {
this.featureClass = featureClass;
}
protected void addToDocument(LireFeature feature, Document document, String featureFieldName) {
// This is for debugging the image features.
// try {
//// System.out.println(feature.getClass().getName() + " " + document.getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0]);
// LireFeature f1 = feature.getClass().newInstance();
// f1.extract(ImageIO.read(new File(document.getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0])));
// float distance = feature.getDistance(f1);
// if (distance != 0) {
// System.out.println("Extracted:" + java.util.Arrays.toString(f1.getDoubleHistogram()).replaceAll("\\.0,", "") + "\n" +
// "Data :" + java.util.Arrays.toString(feature.getDoubleHistogram()).replaceAll("\\.0,", "") + "\n" +
// "Problem with " + f1.getClass().getName() + " at file " + document.getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0] + ", distance=" + distance
// );
//// System.out.println("Problem with " + f1.getClass().getName() + " at file " + document.getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0] + ", distance=" + distance);
// }
// } catch (Exception e) {
// e.printStackTrace();
//
// }
if (feature.getClass().getCanonicalName().equals(featureClass.getCanonicalName())) {
// generate hashes here:
// int[] hashes = LocalitySensitiveHashing.generateHashes(feature.getDoubleHistogram());
int[] hashes = BitSampling.generateHashes(feature.getDoubleHistogram());
// System.out.println(Arrays.toString(hashes));
// store hashes in index as terms
document.add(new TextField(featureFieldName + "_hash", SerializationUtils.arrayToString(hashes), Field.Store.YES));
// add the specific feature
document.add(new StoredField(featureFieldName, feature.getByteArrayRepresentation()));
}
// add the specific feature
// document.add(new StoredField(featureFieldName, feature.getByteArrayRepresentation()));
}
}
|
package com.evan.demo.yizhu;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.evan.demo.yizhu.yushi_fragment.yushi_dengju;
import com.evan.demo.yizhu.yushi_fragment.yushi_paifengshan;
import com.evan.demo.yizhu.yushi_fragment.yushi_tizhongcheng;
import java.util.ArrayList;
public class WodeFragment extends Fragment {
private View rootView3;
private ImageView wode;
@Override
public void onAttach(Context context){
super.onAttach(context);
}
@Override
public View onCreateView(@Nullable LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
rootView3 = inflater.inflate(R.layout.fragment_wode,container,false);
initUi();
return rootView3;
}
private void initUi(){
//这里写加载布局的代码
wode = (ImageView)rootView3.findViewById(R.id.wode);
}
@Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
//这里写逻辑代码
wode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getActivity(),com.evan.demo.yizhu.wode.wode_shimingrenzheng1.class);
startActivity(i);
}
});
}
}
|
package com.lintcode.simple;
public class digitCounts {
public static int digitCount(int k, int n) {
int current =0;
int before = 0;
int after = 0;
int i = 1 ,count =0 ;
while(n/i!=0){
current = (n/i)%10;
before = n/(i*10);
after = n-n/i*i;
if(current > k){
count = count + (before+1) *i;
}else if(current < k){
count = count + before *i;
}else {
count = count + before*i+after+1;
}
}
return 0;
}
public static void main(String[] args) {
System.out.println(digitCount(122,2));
}
}
|
package accesscode.c4q.nyc.memeifyme;
import android.content.ContentResolver;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.FrameLayout;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
public class SaveMeme {
public Bitmap loadBitmapFromView(FrameLayout view) {
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bm = view.getDrawingCache();
return bm;
}
public void saveMeme(Bitmap bm, String imgName, ContentResolver c) {
OutputStream fOut = null;
String strDirectory = Environment.getExternalStorageDirectory().toString();
File f = new File(strDirectory, imgName);
try {
fOut = new FileOutputStream(f);
// Compress image
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
// Update image to gallery
MediaStore.Images.Media.insertImage(c,
f.getAbsolutePath(), f.getName(), f.getName());
} catch (Exception e) {
e.printStackTrace();
}
}
} |
package kr.mjc.sehyuckpark.spring.day1.class03;
import kr.mjc.sehyuckpark.spring.day1.class02.LgTV;
import kr.mjc.sehyuckpark.spring.day1.class02.SamsungTV;
import kr.mjc.sehyuckpark.spring.day1.class02.TV;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public TV samsungTV() {
return new SamsungTV();
}
@Bean
public TV lgTV() {
return new LgTV();
}
} |
public class nilaiRata
{
public float rata (int total) //total pengambilan nilai total yg ada pada class data_mahasiswa
{
return(total/2); //menentukan nilai rata - rata
}
public String nilaiHuruf(int total) //menentukan nilai huruf sesuai nilai rata - rata
{
if ((total/2)>=80 && (total/2)<=100) // jika nnilai rata - rata 80 - 100 nilai huruf A
return "A";
else if ((total/2)>=75 && (total/2)<80) // jika nnilai rata - rata 75 - 80 nilai huruf B+
return "B+";
else if ((total/2)>=65 && (total/2)<75) // jika nnilai rata - rata 65 - 75 nilai huruf B
return "B";
else if ((total/2)>=60 && (total/2)<65) // jika nnilai rata - rata 60 - 65 nilai huruf C+
return "C+";
else if ((total/2)>=50 && (total/2)<60) // jika nnilai rata - rata 50 - 60 nilai huruf C
return "C";
else if ((total/2)>=20 && (total/2)<50) // jika nnilai rata - rata 20 - 50 nilai huruf D
return "D";
else if ((total/2)>=0 && (total/2)<20) // jika nnilai rata - rata 0 - 20 nilai huruf E
return "E";
else //selain dari syarat diatas maka akan keluar output error
return "Error";
}
}
|
package com.goldenasia.lottery.view.adapter;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.goldenasia.lottery.R;
import com.goldenasia.lottery.data.GgcMoneyNumberEntity;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Sakura on 2016/10/5.
*/
public class GgcCodeAdapter extends BaseAdapter
{
private ArrayList<GgcMoneyNumberEntity> data;
public void setData(ArrayList<GgcMoneyNumberEntity> data)
{
this.data = data;
notifyDataSetChanged();
}
@Override
public int getCount()
{
return data == null ? 0 : data.size();
}
@Override
public Object getItem(int position)
{
return null;
}
@Override
public long getItemId(int position)
{
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder viewHolder;
if (convertView == null)
{
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_ggc_code_prize, parent, false);
viewHolder = new ViewHolder(convertView);
} else
viewHolder = (ViewHolder) convertView.getTag();
if (data.get(position).isRed())
{
viewHolder.number.setTextColor(Color.RED);
viewHolder.money.setTextColor(Color.RED);
}
viewHolder.number.setText(data.get(position).getNumber() + "");
viewHolder.money.setText("¥" + data.get(position).getMoney());
return convertView;
}
static class ViewHolder
{
@BindView(R.id.number)
TextView number;
@BindView(R.id.money)
TextView money;
ViewHolder(View view)
{
ButterKnife.bind(this, view);
view.setTag(this);
}
}
}
|
package vista;
import com.sun.glass.events.KeyEvent;
import controlador.MiFuncion;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import modelo.Estudiante;
/**
*
* @author Jonathan Pacheco R.
* @version 0.1
*
*/
public class GestionarEstudiante extends javax.swing.JFrame {
Estudiante est = new Estudiante();
DefaultTableModel model;
int rowIndex;
public GestionarEstudiante() {
initComponents();
est.llenarJTEstudiante(tbl_estudiantes, "");
ButtonGroup bg = new ButtonGroup();
bg.add(rbtn_fem);
bg.add(rbtn_mas);
model = (DefaultTableModel) tbl_estudiantes.getModel();
tbl_estudiantes.setRowHeight(30);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
txtf_id_est = new javax.swing.JTextField();
txtf_apellido = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
txtf_telefono = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
rbtn_fem = new javax.swing.JRadioButton();
rbtn_mas = new javax.swing.JRadioButton();
dch_nacimiento = new com.toedter.calendar.JDateChooser();
btn_agregar = new javax.swing.JButton();
btn_eliminar = new javax.swing.JButton();
jLabel8 = new javax.swing.JLabel();
txtf_nombre = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
txta_direccion = new javax.swing.JTextArea();
btn_editar = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
tbl_estudiantes = new javax.swing.JTable();
jLabel9 = new javax.swing.JLabel();
txtf_buscar = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Myriad Pro", 0, 24)); // NOI18N
jLabel1.setText("Gestión de estudiantes");
jLabel2.setFont(new java.awt.Font("Myriad Pro", 0, 13)); // NOI18N
jLabel2.setText("Nro. identificador:");
txtf_id_est.setFont(new java.awt.Font("Myriad Pro", 0, 14)); // NOI18N
txtf_id_est.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtf_id_estActionPerformed(evt);
}
});
txtf_apellido.setFont(new java.awt.Font("Myriad Pro", 0, 14)); // NOI18N
jLabel3.setFont(new java.awt.Font("Myriad Pro", 0, 13)); // NOI18N
jLabel3.setText("Apellido(s):");
jLabel4.setFont(new java.awt.Font("Myriad Pro", 0, 13)); // NOI18N
jLabel4.setText("Sexo:");
jLabel5.setFont(new java.awt.Font("Myriad Pro", 0, 13)); // NOI18N
jLabel5.setText("Fecha de nacimiento:");
txtf_telefono.setFont(new java.awt.Font("Myriad Pro", 0, 14)); // NOI18N
txtf_telefono.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtf_telefonoActionPerformed(evt);
}
});
txtf_telefono.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txtf_telefonoKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
txtf_telefonoKeyTyped(evt);
}
});
jLabel6.setFont(new java.awt.Font("Myriad Pro", 0, 13)); // NOI18N
jLabel6.setText("Teléfono:");
jLabel7.setFont(new java.awt.Font("Myriad Pro", 0, 13)); // NOI18N
jLabel7.setText("Dirección:");
rbtn_fem.setFont(new java.awt.Font("Myriad Pro", 0, 14)); // NOI18N
rbtn_fem.setText("Femenino");
rbtn_mas.setFont(new java.awt.Font("Myriad Pro", 0, 14)); // NOI18N
rbtn_mas.setText("Masculino");
dch_nacimiento.setFont(new java.awt.Font("Myriad Pro", 0, 14)); // NOI18N
btn_agregar.setFont(new java.awt.Font("Myriad Pro", 0, 14)); // NOI18N
btn_agregar.setText("AGREGAR");
btn_agregar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 204, 102)));
btn_agregar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_agregarActionPerformed(evt);
}
});
btn_eliminar.setFont(new java.awt.Font("Myriad Pro", 0, 14)); // NOI18N
btn_eliminar.setText("ELIMINAR");
btn_eliminar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 0, 0)));
btn_eliminar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_eliminarActionPerformed(evt);
}
});
jLabel8.setFont(new java.awt.Font("Myriad Pro", 0, 13)); // NOI18N
jLabel8.setText("Nombre(s):");
txtf_nombre.setFont(new java.awt.Font("Myriad Pro", 0, 14)); // NOI18N
txta_direccion.setColumns(20);
txta_direccion.setFont(new java.awt.Font("Myriad Pro", 0, 14)); // NOI18N
txta_direccion.setRows(5);
jScrollPane1.setViewportView(txta_direccion);
btn_editar.setFont(new java.awt.Font("Myriad Pro", 0, 14)); // NOI18N
btn_editar.setText("EDITAR");
btn_editar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 204, 0)));
btn_editar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn_editarActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(rbtn_fem)
.addGap(18, 18, 18)
.addComponent(rbtn_mas))
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5)
.addComponent(jLabel6)
.addComponent(jLabel7)
.addComponent(jLabel8)
.addComponent(jScrollPane1)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(btn_agregar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btn_editar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btn_eliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(txtf_telefono)
.addComponent(dch_nacimiento, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtf_apellido)
.addComponent(txtf_nombre)
.addComponent(txtf_id_est))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtf_id_est, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel8)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtf_nombre, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtf_apellido, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(rbtn_fem)
.addComponent(rbtn_mas))
.addGap(18, 18, 18)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(dch_nacimiento, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtf_telefono, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn_agregar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_eliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn_editar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
tbl_estudiantes.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
tbl_estudiantes.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Identificador", "Nombre(s)", "Apellido(s)", "Sexo", "Fecha nac.", "Teléfono", "Dirección"
}
));
tbl_estudiantes.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tbl_estudiantesMouseClicked(evt);
}
});
tbl_estudiantes.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
tbl_estudiantesKeyReleased(evt);
}
});
jScrollPane2.setViewportView(tbl_estudiantes);
jLabel9.setFont(new java.awt.Font("Myriad Pro", 0, 14)); // NOI18N
jLabel9.setText("Ingresa el término a buscar:");
txtf_buscar.setFont(new java.awt.Font("Myriad Pro", 0, 14)); // NOI18N
txtf_buscar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtf_buscarActionPerformed(evt);
}
});
txtf_buscar.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txtf_buscarKeyPressed(evt);
}
public void keyReleased(java.awt.event.KeyEvent evt) {
txtf_buscarKeyReleased(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
txtf_buscarKeyTyped(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 781, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(15, 15, 15)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtf_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 389, javax.swing.GroupLayout.PREFERRED_SIZE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(51, 51, 51)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(txtf_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 588, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(11, 11, 11))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtf_telefonoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtf_telefonoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtf_telefonoActionPerformed
private void txtf_telefonoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtf_telefonoKeyPressed
// TODO add your handling code here:
}//GEN-LAST:event_txtf_telefonoKeyPressed
private void txtf_telefonoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtf_telefonoKeyTyped
if (!Character.isDigit(evt.getKeyChar())) {
evt.consume();
}
}//GEN-LAST:event_txtf_telefonoKeyTyped
private void btn_eliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_eliminarActionPerformed
/*
ALTER TABLE nota
add CONSTRAINT fk_nota_estudiante
FOREIGN KEY(`id_estudiante`)
REFERENCES estudiante (id)
ON DELETE CASCADE
*/
if (txtf_id_est.getText().equals("")) {
JOptionPane.showMessageDialog(null, "Selecciona a un estudiante primero");
} else {
int id = Integer.valueOf(txtf_id_est.getText());
est.inUpDelEstudiante('b', id, null, null, null, null, null, null);
est.llenarJTEstudiante(tbl_estudiantes, "");
tbl_estudiantes.setModel(new DefaultTableModel(null, new Object[]{"Identificador", "Nombre(s)", "Apellido(s)", "Sexo", "Fecha nac.", "Teléfono", "Dirección"}));
est.llenarJTEstudiante(tbl_estudiantes, txtf_buscar.getText());
FormularioPrincipal.lbl_cant_est.setText("Cantidad de estudiantes: "+Integer.toString(MiFuncion.contarData("estudiante")));
txtf_id_est.setText("");
txtf_nombre.setText("");
txtf_apellido.setText("");
txtf_telefono.setText("");
txta_direccion.setText("");
rbtn_fem.setSelected(false);
rbtn_mas.setSelected(false);
dch_nacimiento.setDate(null);
}
}//GEN-LAST:event_btn_eliminarActionPerformed
private void txtf_id_estActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtf_id_estActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtf_id_estActionPerformed
public boolean verifText() {
// Valida que no haya campos vacíos
if (txtf_nombre.getText().equals("") || txtf_apellido.getText().equals("")
|| txtf_telefono.getText().equals("") || txta_direccion.getText().equals("")
|| txtf_id_est.getText().equals("") || dch_nacimiento.getDate() == null) {
JOptionPane.showMessageDialog(null, "Debe llenar todos los campos");
return false;
// Evita que se elija una fecha futura
} else if (dch_nacimiento.getDate().compareTo(new Date()) > 0) {
JOptionPane.showMessageDialog(null, "Fecha no válida");
return false;
} else {
return true;
}
}
private void btn_editarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_editarActionPerformed
String nombre = txtf_nombre.getText();
String apellido = txtf_apellido.getText();
String telefono = txtf_telefono.getText();
String direccion = txta_direccion.getText();
int id = Integer.valueOf(txtf_id_est.getText());
String sexo = "";
if (rbtn_fem.isSelected()) {
sexo = "Femenino";
} else if (rbtn_mas.isSelected()) {
sexo = "Masculino";
}
// Registro verificado de nuevos estudiantes
if (verifText()) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String nacimiento = dateFormat.format(dch_nacimiento.getDate());
Estudiante est = new Estudiante();
est.inUpDelEstudiante('e', id, nombre, apellido, sexo, nacimiento, telefono, direccion);
//FormularioPrincipal.lbl_cant_est.setText("Cantidad de estudiantes: "+Integer.toString(MiFuncion.contarData("estudiante")));
}
tbl_estudiantes.setModel(new DefaultTableModel(null, new Object[]{"Identificador", "Nombre(s)", "Apellido(s)", "Sexo", "Fecha nac.", "Teléfono", "Dirección"}));
est.llenarJTEstudiante(tbl_estudiantes, "");
}//GEN-LAST:event_btn_editarActionPerformed
private void tbl_estudiantesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl_estudiantesMouseClicked
int rowIndex = tbl_estudiantes.getSelectedRow();
if (model.getValueAt(rowIndex, 3).toString().equals("Masculino")) {
rbtn_mas.setSelected(true);
rbtn_fem.setSelected(false);
} else {
rbtn_fem.setSelected(true);
rbtn_mas.setSelected(false);
}
Date nac;
try {
nac = new SimpleDateFormat("yyyy-MM-dd").parse(model.getValueAt(rowIndex, 4).toString());
dch_nacimiento.setDate(nac);
} catch (ParseException ex) {
Logger.getLogger(GestionarEstudiante.class.getName()).log(Level.SEVERE, null, ex);
}
txtf_id_est.setText(model.getValueAt(rowIndex, 0).toString());
txtf_nombre.setText(model.getValueAt(rowIndex, 1).toString());
txtf_apellido.setText(model.getValueAt(rowIndex, 2).toString());
txtf_telefono.setText(model.getValueAt(rowIndex, 5).toString());
txta_direccion.setText(model.getValueAt(rowIndex, 6).toString());
}//GEN-LAST:event_tbl_estudiantesMouseClicked
private void txtf_buscarKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtf_buscarKeyTyped
}//GEN-LAST:event_txtf_buscarKeyTyped
private void txtf_buscarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtf_buscarKeyPressed
}//GEN-LAST:event_txtf_buscarKeyPressed
private void txtf_buscarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtf_buscarKeyReleased
tbl_estudiantes.setModel(new DefaultTableModel(null, new Object[]{"Identificador", "Nombre(s)", "Apellido(s)", "Sexo", "Fecha nac.", "Teléfono", "Dirección"}));
est.llenarJTEstudiante(tbl_estudiantes, txtf_buscar.getText());
}//GEN-LAST:event_txtf_buscarKeyReleased
private void tbl_estudiantesKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbl_estudiantesKeyReleased
if (evt.getKeyCode() == KeyEvent.VK_UP || evt.getKeyCode() == KeyEvent.VK_DOWN) {
int rowIndex = tbl_estudiantes.getSelectedRow();
txtf_id_est.setText(model.getValueAt(rowIndex, 0).toString());
txtf_nombre.setText(model.getValueAt(rowIndex, 1).toString());
txtf_apellido.setText(model.getValueAt(rowIndex, 2).toString());
txtf_telefono.setText(model.getValueAt(rowIndex, 5).toString());
txta_direccion.setText(model.getValueAt(rowIndex, 6).toString());
if (model.getValueAt(rowIndex, 3).toString().equals("Masculino")) {
rbtn_mas.setSelected(true);
rbtn_fem.setSelected(false);
} else {
rbtn_fem.setSelected(true);
rbtn_mas.setSelected(false);
}
Date nac;
try {
nac = new SimpleDateFormat("yyyy-MM-dd").parse(model.getValueAt(rowIndex, 4).toString());
dch_nacimiento.setDate(nac);
} catch (ParseException ex) {
Logger.getLogger(GestionarEstudiante.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_tbl_estudiantesKeyReleased
private void btn_agregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_agregarActionPerformed
AgregarEstudiante aEst = new AgregarEstudiante();
aEst.setVisible(true);
aEst.pack();
aEst.setLocationRelativeTo(null);
aEst.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// String nombre = txtf_id_est.getText();
// String apellido = txtf_apellido.getText();
// String telefono = txtf_telefono.getText();
// String direccion = txta_direccion.getText();
// String sexo = "Masculino";
// if (rbtn_fem.isSelected()) {
// sexo = "Femenino";
// }
//
// // Registro verificado de nuevos estudiantes
// if (verifText()) {
// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// String nacimiento = dateFormat.format(dch_nacimiento.getDate());
// Estudiante est = new Estudiante();
// est.inUpDelEstudiante('i', null, nombre, apellido, sexo, nacimiento, telefono, direccion);
// FormularioPrincipal.lbl_cant_est.setText("Cantidad de estudiantes: "+Integer.toString(MiFuncion.contarData("estudiante")));
// }
}//GEN-LAST:event_btn_agregarActionPerformed
private void txtf_buscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtf_buscarActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtf_buscarActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GestionarEstudiante.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GestionarEstudiante.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GestionarEstudiante.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GestionarEstudiante.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GestionarEstudiante().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn_agregar;
private javax.swing.JButton btn_editar;
private javax.swing.JButton btn_eliminar;
private com.toedter.calendar.JDateChooser dch_nacimiento;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JRadioButton rbtn_fem;
private javax.swing.JRadioButton rbtn_mas;
public static javax.swing.JTable tbl_estudiantes;
private javax.swing.JTextArea txta_direccion;
private javax.swing.JTextField txtf_apellido;
private javax.swing.JTextField txtf_buscar;
private javax.swing.JTextField txtf_id_est;
private javax.swing.JTextField txtf_nombre;
private javax.swing.JTextField txtf_telefono;
// End of variables declaration//GEN-END:variables
}
|
package co.company.spring.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import co.company.spring.dao.Emp;
import co.company.spring.dao.EmpMapper;
import co.company.spring.dao.EmpSearch;
//Jackson 라이브러리 아작스 이용
@RestController
public class EmpRestController {
@Autowired EmpMapper dao;
@RequestMapping("/ajax/empSelect")
public List<Emp> empSelect(EmpSearch emp){
return dao.getEmpList(emp);
}
}
|
package se.rtz.csvtool.commonArgs;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import se.rtz.tool.arg.CommandLineArg;
import se.rtz.tool.arg.Extractor;
import se.rtz.tool.arg.ExtractorParam;
import se.rtz.tool.arg.ParamException;
import se.rtz.tool.arg.common.ArgumentUtil;
@ExtractorParam(args =
{ @CommandLineArg(description = "A file containing characters (or ':in:' for std in)", example = "aFile.txt",
mandatory = true, name = "filename"), //
@CommandLineArg(
description = "Encoding. If not given or does not match a valid charset, default encoding will be used.",
example = "UTF-8", mandatory = false, name = "encoding") //
})
public class ReaderExtractor implements Extractor<Reader>
{
@Override
public Reader doExtract(String token, String[] args) throws ParamException
{
int indexOfToken = ArgumentUtil.indexOfToken(token, args);
if (indexOfToken == -1)
{
return null;
}
try
{
return getReader(args, indexOfToken);
}
catch (FileNotFoundException e)
{
throw new ParamException("could not find file", e);
}
}
private Reader getReader(String[] args, int indexOfToken) throws FileNotFoundException
{
String flagValue = args[indexOfToken + 1];
Charset charset = getCharSet(args, indexOfToken);
if (flagValue.trim().equals(":in:"))
{
return new InputStreamReader(System.in, charset);
}
else
{
return new InputStreamReader(new FileInputStream(flagValue), charset);
}
}
private Charset getCharSet(String[] args, int indexOfToken)
{
int index = indexOfToken + 2;
if (args.length <= index)
{
return Charset.defaultCharset();
}
String charsetName = args[index];
try
{
return Charset.forName(charsetName);
}
catch (IllegalArgumentException e)
{
return Charset.defaultCharset();
}
}
}
|
package com.reacheng.rc.service.impl;
import com.reacheng.rc.dao.UserRepository;
import com.reacheng.rc.entity.User;
import com.reacheng.rc.service.UserService;
import com.reacheng.rc.tools.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
@Service
public class UserServiceImpl extends BaseServiceImpl <User, Integer> implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public User adminLogin(String userName, String password) {
User user = userRepository.adminLogin(userName, Tools.Md5(password));
if (user != null) {
user.setLoginTime(new Date());
user.setLoginNum(user.getLoginNum()+1);
userRepository.save(user);
return user;
}
return null;
}
@Override
public User findByName(String userName) {
return userRepository.findByName(userName);
}
@Override
public User findByEmail(String email) {
return userRepository.findByEmail(email);
}
}
|
package com.base.danmaku;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
import com.heihei.model.User;
import com.wmlives.heihei.R;
public class DanmakuColorBgItemView extends DanmakuItemView {
private TextView tv_danmaku;
public DanmakuColorBgItemView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onFinishInflate() {
// TODO Auto-generated method stub
super.onFinishInflate();
tv_danmaku = (TextView) findViewById(R.id.danmaku_text);
};
@Override
public void refreshView() {
if (item.gender == User.FEMALE) {
tv_danmaku.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_danmaku_female));
} else {
tv_danmaku.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_danmaku_male));
}
tv_danmaku.setText(item.userName + ":" + item.text);
}
}
|
package com.dexvis.javafx.util;
import javafx.scene.effect.DropShadow;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class TextUtil
{
public static Text DropShadow(String text)
{
DropShadow ds = new DropShadow();
ds.setOffsetY(3.0f);
ds.setColor(Color.color(0.4f, 0.4f, 0.4f));
Text t = new Text();
t.setEffect(ds);
t.setCache(true);
t.setX(10.0f);
t.setY(270.0f);
t.setFill(Color.DARKBLUE);
t.setText(text);
t.setFont(Font.font(null, FontWeight.BOLD, 18));
return t;
}
}
|
package count;
public class Test {
public static void main(String[] args) {
int[] a = {1,2,7,3,5,3,9,2,5,2,4,3,6,2,9,3,5,3,9,2,8,0,9,2,3,7,9,6,3,8,7};
BiTree bt = new BiTree();
for (int i = 0;i<a.length;i++){
bt.addValue(bt.root,a[i]);
}
/* bt.preOrder(bt.root);
System.out.println();*/
bt.InOrder(bt.root);
System.out.println();
/* bt.postOrder(bt.root);*/
System.out.println();
bt.search(bt.root,4);
bt.find(bt.root,1,5);
System.out.println();
bt.listAll(bt.root);
}
}
|
package com.spreadtrum.android.eng;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class wifitest extends Activity {
private engfetch mEf;
private int sockid = 0;
private String str = null;
public TextView tv;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mEf = new engfetch();
this.sockid = this.mEf.engopen();
ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();
DataOutputStream outputBufferStream = new DataOutputStream(outputBuffer);
this.str = "CMD:" + "WIFI";
try {
outputBufferStream.writeBytes(this.str);
this.mEf.engwrite(this.sockid, outputBuffer.toByteArray(), outputBuffer.toByteArray().length);
this.mEf.engclose(this.sockid);
this.tv = new TextView(this);
this.tv.setText("Enter wifi test mode");
setContentView(this.tv);
} catch (IOException e) {
Log.e("engnetinfo", "writebytes error");
}
}
protected void onDestroy() {
super.onDestroy();
}
}
|
package com.rubic.demo.value;
import com.lmax.disruptor.EventHandler;
import java.util.concurrent.CountDownLatch;
/**
* @author rubic
*/
public class ValueAdditionEventHandler implements EventHandler<ValueEvent> {
private long value = 0;
private long count;
private CountDownLatch latch;
public long getValue()
{
return value;
}
public void reset(final CountDownLatch latch, final long expectedCount)
{
value = 0;
this.latch = latch;
count = expectedCount;
}
public void onEvent(final ValueEvent event, final long sequence, final boolean endOfBatch) throws Exception
{
value = event.getValue();
if(count == sequence)
{
latch.countDown();
}
}
}
|
package com.lollipop.springcloud.service;
import org.springframework.cloud.client.ServiceInstance;
import java.util.List;
/**
* @Description: TODO
* @Auther: shanpeng.wang
* @Create: 2021/3/12 10:40
*/
public interface LoadBalancer {
ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
|
package com.gaoshin.sorma.examples.addressbook;
public class Contact {
private Long id;
private String firstName;
private String lastName;
private Gender gender;
private boolean married;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public boolean isMarried() {
return married;
}
public void setMarried(boolean married) {
this.married = married;
}
}
|
package com.sinodynamic.hkgta.service.crm.payment;
import com.sinodynamic.hkgta.entity.crm.MemberPaymentAcc;
import com.sinodynamic.hkgta.service.IServiceBase;
public interface MemberPaymentAccService extends IServiceBase<MemberPaymentAcc> {
public String getVccNoByCustomerId(Long CustomerId);
}
|
package com.vuforia.samples.VuforiaSamples.ui.Adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.vuforia.samples.VuforiaSamples.R;
import com.vuforia.samples.VuforiaSamples.ui.Common.CommentInfo;
import com.vuforia.samples.VuforiaSamples.ui.Common.UserInfo;
import com.vuforia.samples.VuforiaSamples.ui.CustomView.EvaluationView;
/**
* Created by aquat on 2017/12/28.
*/
public class CommentListAdapter extends ArrayAdapter<CommentInfo>{
LayoutInflater mInflater;
public CommentListAdapter(@NonNull Context context) {
super(context,0);
mInflater = LayoutInflater.from(context);
}
//タップアクションを無効にする
@Override
public boolean isEnabled(int position){
return false;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
//コメント情報を取得
CommentInfo info = getItem(position);
//Viewが再利用可能かどうか
if(convertView != null){
// int id = (int)convertView.getTag();
}
//レイアウトを取得
//if(convertView == null){
//自分のコメントかどうか
int gravity = Gravity.RIGHT;
try{
if(!info.userId.equals(UserInfo.getInstance().getUserId())){
convertView = mInflater.inflate(R.layout.cmt_other,parent,false);
gravity = Gravity.LEFT;
}else {
convertView = mInflater.inflate(R.layout.cmt_self,parent,false);
}
}catch (Exception e){
e.printStackTrace();
}
if(info != null){
//コメント作成
TextView tv = (TextView)convertView.findViewById(R.id.cmt);
tv.setText(info.userCmt);
//評価を設定
EvaluationView evaluationView = (EvaluationView)convertView.findViewById(R.id.stars_mini);
evaluationView.setImageSize(15);
evaluationView.setGravity(gravity);
evaluationView.changeStarState((int)info.star - 1);
evaluationView.setCallBackState(EvaluationView.CallBackState.OFF);
evaluationView.setMargin(0,0,0,0);
/* ViewGroup vg = (ViewGroup)convertView.findViewById(R.id.stars_mini);
//LinearLayout linearLayout = (LinearLayout)convertView.findViewById(R.id.starsmini_line2);
//linearLayout.setGravity(Gravity.RIGHT);
for(int i = 0;i< 5;i++){
ImageButton imageButton = (ImageButton)vg.getChildAt(i);
if(i < info.star) {
imageButton.setImageResource(R.drawable.star_on);
}else{
imageButton.setImageResource(R.drawable.star_off);
}
}*/
//ユーザー名
TextView userName = (TextView)convertView.findViewById(R.id.user_name);
userName.setText(info.userName);
//登録日
TextView insertDate = (TextView)convertView.findViewById(R.id.insert_date);
insertDate.setText(info.insertDate);
//タグにIDを登録する
convertView.setTag(info.userId);
}
//; }
return convertView;
}
}
|
package com.housesline.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.housesline.bean.User;
import com.housesline.service.user.UserService;
import com.housesline.utils.SysContent;
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/tologin", method = RequestMethod.GET)
public String toLoginPage() {
return "/login";
}
/**
* 请求登录
* @param model
* @param phone
* @return
*/
@RequestMapping(value = "/login/{phone}", method = RequestMethod.POST)
public String toLogin(Model model, @PathVariable("phone") String phone) {
User user = userService.findUserByPhone(phone);
if(user != null){
SysContent.getSession().setAttribute("userInfo", user);
model.addAttribute("data", "登录成功");
return "/home";
}else{
model.addAttribute("data", "登录失败,用户名不存在");
return "/login";
}
}
}
|
package vista;
public class VAyuda {
}
|
package com.infohold.ebpp.bill.model;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import com.infohold.core.model.BaseIdModel;
/**
* 日终日志表
* @author Administrator
*
*/
@Entity
@Table(name = "IH_EBPP_END_LOG" )
public class EndDayLog extends BaseIdModel{
private static final long serialVersionUID = -120686350822480973L;
@Transient
public static final String FLAG_FAILED = "0";
@Transient
public static final String FLAG_SUCCESS = "1";
@Transient
public static final String FLAG_SUCCESS_WARN = "2";//虽然成功了,但是执行过程中存在异常情况,比如某一条日终是无效的,或某条数据插入账单表失败等等。
@Transient
public static final String SYNC_TYPE_NORMAL = "0";
@Transient
public static final String SYNC_TYPE_AGAIN= "1";
/** 定时器对账类型map */
public static Map<String, String> SYNC_TYPE_MAP = new HashMap<String, String>();
static{
SYNC_TYPE_MAP.put(EndDayLog.SYNC_TYPE_NORMAL, "正常");
SYNC_TYPE_MAP.put(EndDayLog.SYNC_TYPE_AGAIN, "重复执行");
}
/** 定时器对账结果map */
public static Map<String, String> FLAG_MAP = new HashMap<String, String>();
static{
FLAG_MAP.put(EndDayLog.FLAG_FAILED, "失败");
FLAG_MAP.put(EndDayLog.FLAG_SUCCESS, "成功");
FLAG_MAP.put(EndDayLog.FLAG_SUCCESS_WARN, "带有警告的成功");
}
private String beginTime;
private String syncDate;
private String syncType;
private long billEndHeadNum;
private long billEndParsedNum;
private long billEndValidNum;
private long billEndInvalidNum;
private long billLessNum;
private long billMoreNum;
private long billOldNum;
private long billNewNum;
private long billDiffNum;
private long billSameNum;
private String billSyncFlag;
private String billSyncInfo;
private long payEndHeadNum;
private long payEndParsedNum;
private long payEndValidNum;
private long payEndInvalidNum;
private long payLessNum;
private long payMoreNum;
private long payOldNum;
private long payNewNum;
private long payDiffNum;
private long paySameNum;
private String paySyncFlag;
private String paySyncInfo;
private String endTableMovFlag;
private String endTableMovInfo;
private String endFilesMovFlag;
private String endFilesMovInfo;
private String endTime;
private long costTime;
private String flag;
private String failedCause;
private String failedDetailInfo;
private String warnInfo;
private String logInfo;
public String getBeginTime() {
return beginTime;
}
public void setBeginTime(String beginTime) {
this.beginTime = beginTime;
}
public String getSyncDate() {
return syncDate;
}
public void setSyncDate(String syncDate) {
this.syncDate = syncDate;
}
public String getSyncType() {
return syncType;
}
public void setSyncType(String syncType) {
this.syncType = syncType;
}
public long getBillEndHeadNum() {
return billEndHeadNum;
}
public void setBillEndHeadNum(long billEndHeadNum) {
this.billEndHeadNum = billEndHeadNum;
}
public long getBillEndParsedNum() {
return billEndParsedNum;
}
public void setBillEndParsedNum(long billEndParsedNum) {
this.billEndParsedNum = billEndParsedNum;
}
public long getBillEndValidNum() {
return billEndValidNum;
}
public void setBillEndValidNum(long billEndValidNum) {
this.billEndValidNum = billEndValidNum;
}
public long getBillEndInvalidNum() {
return billEndInvalidNum;
}
public void setBillEndInvalidNum(long billEndInvalidNum) {
this.billEndInvalidNum = billEndInvalidNum;
}
public long getBillLessNum() {
return billLessNum;
}
public void setBillLessNum(long billLessNum) {
this.billLessNum = billLessNum;
}
public long getBillMoreNum() {
return billMoreNum;
}
public void setBillMoreNum(long billMoreNum) {
this.billMoreNum = billMoreNum;
}
public long getBillOldNum() {
return billOldNum;
}
public void setBillOldNum(long billOldNum) {
this.billOldNum = billOldNum;
}
public long getBillNewNum() {
return billNewNum;
}
public void setBillNewNum(long billNewNum) {
this.billNewNum = billNewNum;
}
public long getBillDiffNum() {
return billDiffNum;
}
public void setBillDiffNum(long billDiffNum) {
this.billDiffNum = billDiffNum;
}
public long getBillSameNum() {
return billSameNum;
}
public void setBillSameNum(long billSameNum) {
this.billSameNum = billSameNum;
}
public String getBillSyncFlag() {
return billSyncFlag;
}
public void setBillSyncFlag(String billSyncFlag) {
this.billSyncFlag = billSyncFlag;
}
public String getBillSyncInfo() {
return billSyncInfo;
}
public void setBillSyncInfo(String billSyncInfo) {
this.billSyncInfo = billSyncInfo;
}
public long getPayEndHeadNum() {
return payEndHeadNum;
}
public void setPayEndHeadNum(long payEndHeadNum) {
this.payEndHeadNum = payEndHeadNum;
}
public long getPayEndParsedNum() {
return payEndParsedNum;
}
public void setPayEndParsedNum(long payEndParsedNum) {
this.payEndParsedNum = payEndParsedNum;
}
public long getPayEndValidNum() {
return payEndValidNum;
}
public void setPayEndValidNum(long payEndValidNum) {
this.payEndValidNum = payEndValidNum;
}
public long getPayEndInvalidNum() {
return payEndInvalidNum;
}
public void setPayEndInvalidNum(long payEndInvalidNum) {
this.payEndInvalidNum = payEndInvalidNum;
}
public long getPayLessNum() {
return payLessNum;
}
public void setPayLessNum(long payLessNum) {
this.payLessNum = payLessNum;
}
public long getPayMoreNum() {
return payMoreNum;
}
public void setPayMoreNum(long payMoreNum) {
this.payMoreNum = payMoreNum;
}
public long getPayOldNum() {
return payOldNum;
}
public void setPayOldNum(long payOldNum) {
this.payOldNum = payOldNum;
}
public long getPayNewNum() {
return payNewNum;
}
public void setPayNewNum(long payNewNum) {
this.payNewNum = payNewNum;
}
public long getPayDiffNum() {
return payDiffNum;
}
public void setPayDiffNum(long payDiffNum) {
this.payDiffNum = payDiffNum;
}
public long getPaySameNum() {
return paySameNum;
}
public void setPaySameNum(long paySameNum) {
this.paySameNum = paySameNum;
}
public String getPaySyncFlag() {
return paySyncFlag;
}
public void setPaySyncFlag(String paySyncFlag) {
this.paySyncFlag = paySyncFlag;
}
public String getPaySyncInfo() {
return paySyncInfo;
}
public void setPaySyncInfo(String paySyncInfo) {
this.paySyncInfo = paySyncInfo;
}
public String getEndTableMovFlag() {
return endTableMovFlag;
}
public void setEndTableMovFlag(String endTableMovFlag) {
this.endTableMovFlag = endTableMovFlag;
}
public String getEndTableMovInfo() {
return endTableMovInfo;
}
public void setEndTableMovInfo(String endTableMovInfo) {
this.endTableMovInfo = endTableMovInfo;
}
public String getEndFilesMovFlag() {
return endFilesMovFlag;
}
public void setEndFilesMovFlag(String endFilesMovFlag) {
this.endFilesMovFlag = endFilesMovFlag;
}
public String getEndFilesMovInfo() {
return endFilesMovInfo;
}
public void setEndFilesMovInfo(String endFilesMovInfo) {
this.endFilesMovInfo = endFilesMovInfo;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public long getCostTime() {
return costTime;
}
public void setCostTime(long costTime) {
this.costTime = costTime;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public String getFailedCause() {
return failedCause;
}
public void setFailedCause(String failedCause) {
this.failedCause = failedCause;
}
public String getFailedDetailInfo() {
return failedDetailInfo;
}
public void setFailedDetailInfo(String failedDetailInfo) {
this.failedDetailInfo = failedDetailInfo;
}
public String getWarnInfo() {
return warnInfo;
}
public void setWarnInfo(String warnInfo) {
this.warnInfo = warnInfo;
}
public String getLogInfo() {
return logInfo;
}
public void setLogInfo(String logInfo) {
this.logInfo = logInfo;
}
/**
* 重载toString;
*/
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
/**
* 重载hashCode;
*/
public int hashCode() {
return new HashCodeBuilder().append(this.getId()).toHashCode();
}
/**
* 重载equals
*/
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
}
|
package com.learningjava.VideoRentalApi.controller;
import com.learningjava.VideoRentalApi.TokenHandler;
import com.learningjava.VideoRentalApi.entity.User;
import com.learningjava.VideoRentalApi.services.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserServiceImpl userService; //service class injection
@Autowired
private TokenHandler tokenHandler;
@PostMapping("/login")
public ResponseEntity<Map<String, String>> loginUser(@RequestBody Map<String, Object> userMap){
String email = (String) userMap.get("email");
String password = (String) userMap.get("password");
User user = userService.validateUser(email, password);
//Map<String, String> map = new HashMap<>();
//map.put("message", "loggedIn successfully");
var token = tokenHandler.generateJWTToken(user);
return new ResponseEntity<>(token, HttpStatus.OK);
}
@PostMapping("/register")
public ResponseEntity<Map<String, String>> registerUser(@RequestBody User user) {
userService.registerUser(user);
//Map<String, String> map = new HashMap<>();
//map.put("message", "registered successfully");
var token = tokenHandler.generateJWTToken(user);
return new ResponseEntity<>(token, HttpStatus.CREATED);
}
}
|
package com.tandon.tanay.locationtracker;
import android.app.Application;
import android.database.sqlite.SQLiteDatabase;
import com.tandon.tanay.locationtracker.constants.DbConfig;
import com.tandon.tanay.locationtracker.data.DatabaseHelper;
import com.tandon.tanay.locationtracker.model.persistent.DaoMaster;
import com.tandon.tanay.locationtracker.model.persistent.DaoSession;
public class LocationTracker extends Application {
private DaoSession daoSession;
private Long activeSessionId;
@Override
public void onCreate() {
super.onCreate();
DatabaseHelper helper = new DatabaseHelper(this, DbConfig.NAME);
SQLiteDatabase database = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(database);
daoSession = daoMaster.newSession();
}
public DaoSession getDaoSession() {
return daoSession;
}
public Long getActiveSessionId() {
return activeSessionId;
}
public void setActiveSessionId(Long sessionId) {
this.activeSessionId = sessionId;
}
}
|
import exception.ParcingException;
import exception.WorkflowException;
import java.util.Scanner;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
class ExecutionListIterator {
private static final Logger log = LogManager.getLogger();
private Scanner lineScanner;
ExecutionListIterator(Scanner scanner) throws ParcingException {
if (!scanner.hasNextLine()) {
throw new ParcingException("No execution list");
}
String line = scanner.nextLine();
lineScanner = new Scanner(line).useDelimiter("[ ]*->[ ]*");
log.debug("java.ExecutionListIterator created");
}
Integer next() throws WorkflowException {
if(!lineScanner.hasNext()){
log.debug("End for exec list found");
return null;
}
try{
return new Integer(lineScanner.next());
}catch(NumberFormatException exc){
log.debug("Wrong format of execution list");
throw new WorkflowException("Wrong format of execution list");
}
}
} |
package cn.lyh.spa.ptrnew;
/**
* Created by zhaolb on 2017/11/3.
*/
public class HttpConstants {
//项目入口
//测试地址
public static final String PIC_URL = "http://1.202.234.148:8080";
//唐
//public static final String PIC_URL = "http://10.9.1.196:8080";
//付
//public static final String PIC_URL = "http://10.9.1.158:8080";
public static final String ROOT_URL = PIC_URL+"/mxcb";
//登录接口
public static final String LOGIN = ROOT_URL + "/app/login.jspx";
//菜单列表接口
public static final String MENU_URL = ROOT_URL + "/app/getMenu.jspx";
//获取发稿信息接口
public static final String GETSENDINFO_URL = ROOT_URL + "/app/fgSelect.jspx";
//获取类型接口
public static final String GET_TYPE = ROOT_URL + "/app/selectLx.jspx";
//获取地域接口
public static final String GET_AREA = ROOT_URL + "/app/selectDistrict.jspx";
//签收文章
public static final String SIGN_ARTICLE = ROOT_URL + "/app/receive.jspx";
//审核详情接口
public static final String GET_CHECK_DETAIL = ROOT_URL + "/app/getDetail_check.jspx";
//已审稿库详情接口
public static final String GET_YISHEN_DETAIL = ROOT_URL + "/app/getDetail_modify.jspx";
//解除稿件锁定接口
public static final String RELEASE_LOCK = ROOT_URL + "/app/releaseLock.jspx";
//发稿接口
public static final String ARTICLE_ADD = ROOT_URL + "/app/article_add.jspx";
//草稿箱接口
public static final String GET_DETAIL_EDIT = ROOT_URL + "/app/getDetail_edit.jspx";
//删除稿件接口
public static final String ARTICLE_DELETE = ROOT_URL + "/app/article_delete.jspx";
//草稿箱编辑接口
public static final String ARTICLE_EDIT = ROOT_URL + "/app/article_edit.jspx";
//审核接口
public static final String ARTICLE_CHECK = ROOT_URL + "/app/article_check.jspx";
//修改详情接口
public static final String GET_DETAIL_MODIFY = ROOT_URL + "/app/getDetail_modify.jspx";
//修改接口
public static final String ARTICLE_MODIFY_AFTER_CHECK = ROOT_URL + "/app/article_modifyAftercheck.jspx";
//退稿接口
public static final String ARTICLE_SEND_BACK = ROOT_URL + "/app/article_sendback.jspx";
//功能介绍接口
public static final String GET_INTRODUCTION = ROOT_URL + "/app/getIntroduction.jspx";
//修改密码接口
public static final String MODIFY_PASSWORD = ROOT_URL + "/app/modifyPwd.jspx";
//检查更新接口
public static final String GET_VERSION = ROOT_URL + "/app/getVersion.jspx";
/**
* 正式服务器下载apk接口
*/
public static final String UPDATE_APK_URL = "http://app.newszu.com:8080/newszu.apk";
}
|
package dicegame;
import javax.swing.ImageIcon;
/**
* @author Maria Bartoszuk, w1510769
*/
public interface DieIntf {
/** Image of this die face for displaying in the interface. */
public ImageIcon getDieImage();
/** Associates this die face with given image. */
public void setDieImage(ImageIcon dieImage);
/** Gives this die face certain value used in score computing. */
public void setValue(int v);
/** Returns the value of this die face for computing the score. */
public int getValue();
}
|
package learn.exceptions.university.subjects;
public class InvalidGradeException extends Exception {
public InvalidGradeException(String message) {
super(message);
}
}
|
import java.awt.Image;
/**
* CarriageEnum is an enumeration class to represents values of various instances of carriage target
*/
public enum CarriageEnum {
SMALL(100),
MEDIUM(250),
LARGE(500);
private int health;
private CarriageEnum(int health){
this.health = health;
}
public int health(){
return health;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.inbio.ara.dto.taxonomy;
import org.inbio.ara.dto.BaseEntityOrDTOFactory;
import org.inbio.ara.persistence.taxonomy.TaxonCountry;
import org.inbio.ara.persistence.taxonomy.TaxonCountryPK;
/**
*
* @author gsulca
*/
public class TaxonCountryDTOFactory extends BaseEntityOrDTOFactory<TaxonCountry ,TaxonCountryDTO>{
@Override
public TaxonCountry getEntityWithPlainValues(TaxonCountryDTO dto) {
if(dto==null){
return null;
}
TaxonCountry taxonCountry = new TaxonCountry();
TaxonCountryPK newTaxonCountryPK = new TaxonCountryPK(dto.getTaxonId(),dto.getCountryId());
taxonCountry.setTaxonCountryPK(newTaxonCountryPK);
taxonCountry.setDescription(dto.getDescription());
return taxonCountry;
}
@Override
public TaxonCountry updateEntityWithPlainValues(TaxonCountryDTO dto, TaxonCountry entity) {
if(dto == null || entity == null)
{
return null;
}
else
{
entity.getTaxonCountryPK().setTaxonId(dto.getTaxonId());
entity.getTaxonCountryPK().setCountryId(dto.getCountryId());
entity.setDescription(dto.getDescription());
return entity;
}
}
public TaxonCountryDTO createDTO(TaxonCountry entity) {
TaxonCountryDTO taxonCountryDTO = new TaxonCountryDTO();
taxonCountryDTO.setTaxonId(entity.getTaxonCountryPK().getTaxonId());
taxonCountryDTO.setCountryId(entity.getTaxonCountryPK().getCountryId());
taxonCountryDTO.setDescription(entity.getDescription());
return taxonCountryDTO;
}
}
|
package by.epam.tr.collection;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
public class MyArrayList<E> implements List<E> {
private static final int DEFAULT_CAPACITY = 10;
private Object[] elementData;
private int size;
private int capacity;
public MyArrayList(int initialCapacity) {
if (initialCapacity >= 0) {
this.elementData = new Object[initialCapacity];
} else {
throw new IllegalArgumentException("Illegal initialCapacity" + initialCapacity);
}
}
public MyArrayList() {
this.elementData = new Object[DEFAULT_CAPACITY];
}
public MyArrayList(Collection<? extends E> c) {
this.elementData = c.toArray();
this.size = elementData.length;
this.capacity = size + size / 2;
}
private MyArrayList(Object[] array) {
this.elementData = array;
this.size = elementData.length;
this.capacity = size;
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public boolean contains(Object o) {
for (int i = 0; i < size; i++) {
if (elementData[i].equals(o)) {
return true;
}
}
return false;
}
class MyArrayListIterator<E> implements Iterator<E> {
int cursor;
@Override
public boolean hasNext() {
return cursor != size;
}
@Override
public E next() {
int i = cursor;
if (i >= size) {
throw new NoSuchElementException();
}
Object[] elementData = MyArrayList.this.elementData;
cursor = i + 1;
return (E) elementData[i];
}
}
@Override
public Iterator<E> iterator() {
return new MyArrayListIterator<E>();
}
@Override
public Object[] toArray() {
return Arrays.copyOf(this.elementData, size);
}
@Override
public boolean add(E e) {
checkSizeCapacity();
this.elementData[size++] = e;
return true;
}
@Override
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++) {
if (elementData[index] == null) {
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
}
elementData[--size] = null;
return true;
}
}
} else {
for (int index = 0; index < size; index++) {
if (o.equals(elementData[index])) {
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
}
elementData[--size] = null;
return true;
}
}
}
return false;
}
@Override
public boolean addAll(Collection c) {
if (c.size() > 0) {
Object[] a = c.toArray();
while ((c.size() + this.size) > capacity) {
checkSizeCapacity();
}
System.arraycopy(a, 0, elementData, size, c.size());
size += c.size();
return true;
}
return false;
}
@Override
public boolean addAll(int index, Collection c) {
checkIndex(index);
if (c.size() > 0) {
Object[] a = c.toArray();
while ((c.size() + this.size) > capacity) {
checkSizeCapacity();
}
if (size - index > 0) {
System.arraycopy(elementData, index, elementData, index + c.size(), size - index);
}
System.arraycopy(a, 0, elementData, index, c.size());
size += c.size();
return true;
}
return false;
}
@Override
public void clear() {
if (size > 0) {
elementData = new Object[DEFAULT_CAPACITY];
}
}
@Override
public E get(int index) {
checkIndex(index);
return (E) elementData[index];
}
@Override
public E set(int index, E element) {
checkIndex(index);
E oldElement = (E) elementData[index];
elementData[index] = element;
return oldElement;
}
@Override
public void add(int index, E element) {
checkSizeCapacity();
System.arraycopy(elementData, index, elementData, index + 1, size - index);
elementData[index] = element;
size++;
}
@Override
public E remove(int index) {
checkIndex(index);
E oldValue = (E) elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0) {
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
}
elementData[--size] = null;
return oldValue;
}
@Override
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++) {
if (elementData[i] == null) {
return i;
}
}
} else {
for (int i = 0; i < size; i++) {
if (elementData[i].equals(o)) {
return i;
}
}
}
return -1;
}
@Override
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = 0; i < elementData.length; i++) {
if (elementData[i] == null) {
return i;
}
}
} else {
for (int i = size - 1; i >= 0; i--) {
if (elementData[i].equals(o)) {
return i;
}
}
}
return -1;
}
@Override
public ListIterator listIterator() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ListIterator listIterator(int index) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List subList(int fromIndex, int toIndex) {
if (fromIndex < 0 || toIndex < 0 || fromIndex > size - 1 || toIndex > size || toIndex < fromIndex) {
throw new ArrayIndexOutOfBoundsException("From index: " + fromIndex + ", toIndex: " + toIndex + ", size: " + size);
}
Object[] array = new Object[toIndex - fromIndex];
System.arraycopy(elementData, fromIndex, array, 0, toIndex - fromIndex + 1);
return new MyArrayList(array);
}
@Override
public boolean retainAll(Collection c) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean removeAll(Collection c) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean containsAll(Collection c) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Object[] toArray(Object[] a) {
throw new UnsupportedOperationException("Not supported yet.");
}
private void checkSizeCapacity() {
if (size == capacity) {
capacity = size + size / 2;
Object[] timedList = new Object[capacity];
for (int i = 0; i < size; i++) {
timedList[i] = elementData[i];
}
elementData = timedList;
}
}
private void checkIndex(int index) {
if (index >= size) {
throw new ArrayIndexOutOfBoundsException("Index: " + index + ", size: " + size);
}
}
}
|
package POM;
import commonMethods.CommMeths;
import commonMethods.Logs;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
public class Ai_dash_create_tree_screen2 {
WebDriver driver;
CommMeths cm;
String info = "INFO";
String pass = "PASS";
String fail = "FAIL";
HashMap<Integer, String> LoginMap= new HashMap<Integer, String>();
public Ai_dash_create_tree_screen2(WebDriver driver) {
Logs.startLog("Aidash create tree screen");
this.driver = driver;
PageFactory.initElements(driver, this);
cm = new CommMeths();
}
//Xpath for Nearest Circuit
@FindBy(xpath = "//*[@class='MuiGrid-root MuiGrid-container MuiGrid-item'][1]/div/div[2]/div/div/div")
WebElement NearestCircuit;
//Xpath for No of phases
@FindBy(xpath = "//*[@class='MuiGrid-root MuiGrid-container MuiGrid-item'][1]/div/div[2]/div[2]/div/div/div")
WebElement NoOfphases;
//Xpath for Submit button
@FindBy(xpath = "//*[@class='MuiButton-label'][contains(text(),'Submit')]")
WebElement SubmitButton;
public void NearestCircuit() {
cm.elementExplicitWait(driver, NearestCircuit, 100);
Logs.startLog("Click on Nearest Circuit");
if (NearestCircuit.isDisplayed()) {
NearestCircuit.click();
driver.findElement(By.xpath("//*[contains(text(),'Add Location Information')]")).click();
Logs.addToReport("Nearest Circuit is clicked", pass);
} else {
Logs.addToReport("Nearest Circuit is clicked", fail);
Logs.stopLog();
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
Logs.stopLog();
}
}
public void NoOfphases() {
cm.elementExplicitWait(driver, NoOfphases, 100);
Logs.startLog("Click on Nearest Circuit");
if (NoOfphases.isDisplayed()) {
NoOfphases.click();
Logs.addToReport("NoOfphases is clicked", info);
Logs.stopLog();
} else {
Logs.addToReport("NoOfphases Circuit is clicked", pass);
Logs.stopLog();
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
}
}
public void SubmitButton() {
cm.elementExplicitWait(driver, SubmitButton, 100);
Logs.startLog("Click on Nearest Circuit");
if (SubmitButton.isDisplayed()) {
SubmitButton.click();
Logs.addToReport("NoOfphases is clicked", pass);
Logs.stopLog();
} else {
Logs.addToReport("NoOfphases Circuit is clicked", fail);
Logs.stopLog();
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
}
}
}
|
package example.destan.com.a011_mymemoapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class AddNoteActivity extends Activity {
private EditText m_editTextTitle,m_editTextText;
private NoteInfo m_noteInfo = null;
private Intent m_intent;
private void initData(){
m_intent = this.getIntent();
m_noteInfo = (NoteInfo) m_intent.getSerializableExtra("NOTEINFO");
if (m_noteInfo != null){
m_editTextTitle.setText(m_noteInfo.getTitle());
m_editTextText.setText(m_noteInfo.getText());
}
}
private void initControls()
{
m_editTextTitle = this.findViewById(R.id.ADDNOTEACTIVITY_EDITTEXT_TITLE);
m_editTextText = this.findViewById(R.id.ADDNOTEACTIVITY_EDITTEXT_NOTE);
}
private void initialize()
{
this.initControls();
this.initData();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_note);
this.initialize();
}
public void onSaveButtonClicked(View view) {
Intent intent = new Intent();
NoteInfo noteInfo;
NotesDBHelper helper = new NotesDBHelper(this);
String title = m_editTextTitle.getText().toString().trim();
String text = m_editTextText.getText().toString();
if (title.isEmpty()){
UtilKt.makeToastLong(this,"Title should not be empty.");
return;
}
if (m_noteInfo == null){
//ADD NEW PART
noteInfo = new NoteInfo(title,text,new GregorianCalendar());
helper.insertNote(noteInfo);
intent.putExtra("NOTEINFO",noteInfo);
}else{
//UPDATE PART
m_noteInfo.setTitle(title);
m_noteInfo.setText(text);
m_noteInfo.setUpdateDate(new GregorianCalendar());
helper.updateNotes(m_noteInfo);
intent.putExtra("NOTEINFO",m_noteInfo);
}
this.setResult(RESULT_OK,intent);
this.finish();
}
public void onCancelButtonClicked(View view) {
this.finish();
}
}
|
package com.riddit.Riddit.model;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import javax.persistence.*;
import java.util.Date;
import java.util.Set;
@Entity(name="text")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class Text {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
private String title;
private String body;
private Date date;
private int votes;
@ManyToOne
private User user;
@OneToMany(mappedBy="text", cascade = CascadeType.ALL)
private Set<Comment> commentList;
// TODO: Add: VoteList: Map<User, Boolean>
public Text() {
}
public Text(String title, String body, User user, Date date) {
this.title = title;
this.body = body;
this.user = user;
this.date = date;
this.votes = 0;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public int getVotes() {
return votes;
}
public void setVotes(int votes) {
this.votes = votes;
}
public Set<Comment> getCommentList() {
return commentList;
}
public void setCommentList(Set<Comment> commentList) {
this.commentList = commentList;
}
}
|
package br.com.mixfiscal.prodspedxnfe.dao.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import br.com.mixfiscal.prodspedxnfe.domain.own.CFOP;
import br.com.mixfiscal.prodspedxnfe.domain.own.CFOPDePara;
import br.com.mixfiscal.prodspedxnfe.domain.own.CST;
import br.com.mixfiscal.prodspedxnfe.domain.own.CSTDePara;
import br.com.mixfiscal.prodspedxnfe.domain.own.ClassificacaoTributaria;
import br.com.mixfiscal.prodspedxnfe.domain.own.ClassificacaoTributariaProduto;
import br.com.mixfiscal.prodspedxnfe.domain.own.Cliente;
import br.com.mixfiscal.prodspedxnfe.domain.own.Empresa;
import br.com.mixfiscal.prodspedxnfe.domain.own.Fornecedor;
import br.com.mixfiscal.prodspedxnfe.domain.own.IcmsEntrada;
import br.com.mixfiscal.prodspedxnfe.domain.own.IcmsSaida;
import br.com.mixfiscal.prodspedxnfe.domain.own.PisCofins;
import br.com.mixfiscal.prodspedxnfe.domain.own.Produto;
import br.com.mixfiscal.prodspedxnfe.domain.own.RelacaoProdutoFornecedor;
import br.com.mixfiscal.prodspedxnfe.domain.own.RequisicaoAtualizacaoInfoFiscal;
import br.com.mixfiscal.prodspedxnfe.domain.own.Usuario;
import br.com.mixfiscal.prodspedxnfe.domain.own.custom.ClassificacaoTributariaProdutoCustom;
import br.com.mixfiscal.prodspedxnfe.domain.own.custom.IcmsEntradaCustom;
import br.com.mixfiscal.prodspedxnfe.domain.own.custom.IcmsSaidaCustom;
@SuppressWarnings("deprecation")
public class ConstroyerHibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
Configuration cfg = new AnnotationConfiguration().configure("constroyer_hibernate.cfg.xml");
cfg.addAnnotatedClass(Empresa.class);
cfg.addAnnotatedClass(Fornecedor.class);
cfg.addAnnotatedClass(Produto.class);
cfg.addAnnotatedClass(RelacaoProdutoFornecedor.class);
cfg.addAnnotatedClass(CFOP.class);
cfg.addAnnotatedClass(CFOPDePara.class);
cfg.addAnnotatedClass(CST.class);
cfg.addAnnotatedClass(CSTDePara.class);
cfg.addAnnotatedClass(Usuario.class);
cfg.addAnnotatedClass(Cliente.class);
cfg.addAnnotatedClass(ClassificacaoTributaria.class);
cfg.addAnnotatedClass(ClassificacaoTributariaProduto.class);
cfg.addAnnotatedClass(ClassificacaoTributariaProdutoCustom.class);
cfg.addAnnotatedClass(PisCofins.class);
cfg.addAnnotatedClass(IcmsEntrada.class);
cfg.addAnnotatedClass(IcmsEntradaCustom.class);
cfg.addAnnotatedClass(IcmsSaida.class);
cfg.addAnnotatedClass(IcmsSaidaCustom.class);
cfg.addAnnotatedClass(RequisicaoAtualizacaoInfoFiscal.class);
sessionFactory = cfg.buildSessionFactory();
} catch(Throwable e) {
System.err.println("Initial Constroyer SessionFactory creation failed." + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
|
package com.java.practice.google;
import java.util.*;
public class HashMapNetflix {
public static void main(String[] args) {
// Driver code
String titles[] = {"duel", "dule", "speed", "spede", "deul", "cars"};
List<List<String>> gt = groupTitles(titles);
String query = "dule";
// Searching for all titles
for (List<String> g : gt) {
if (g.contains(query))
System.out.println(g);
}
}
public static List<List<String>> groupTitles(String[] strs) {
// write your code here
if (strs == null || strs.length == 0) {
return new ArrayList<List<String>>();
}
int[] chars = new int[26];
Map<String, List<String>> result = new HashMap<>();
for (String s : strs) {
Arrays.fill(chars, 0);
for (char c : s.toCharArray()) {
int index = c - 'a';
chars[index]++;
}
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < 26; i++) {
sb.append("#");
sb.append(chars[i]);
}
String key = sb.toString();
if (!result.containsKey(key)) {
result.put(key, new ArrayList<>());
}
result.get(key).add(s);
}
return new ArrayList<>(result.values());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.