blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
8f6e7948493abe5e05873aa1116ad9c8e95029e2
|
Java
|
ChanchalRajguru/E-Commerce
|
/src/main/java/com/classwork/csj/repository/CartRepository.java
|
UTF-8
| 284
| 1.84375
| 2
|
[] |
no_license
|
package com.classwork.csj.repository;
import com.classwork.csj.entity.Cart;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface CartRepository extends JpaRepository<Cart, Long> {
Optional<Cart> findByUserId(Long userId);
}
| true
|
4000e7d31215bdb9caf17c478cf7496944301282
|
Java
|
mahmoudimus/obo-edit
|
/java/bbop/trunk/src/org/bbop/expression/parser/ASTImportStatement.java
|
UTF-8
| 577
| 2.046875
| 2
|
[] |
no_license
|
/* Generated By:JJTree: Do not edit this line. ASTImportStatement.java */
package org.bbop.expression.parser;
import org.apache.log4j.*;
public class ASTImportStatement extends SimpleNode {
//initialize logger
protected final static Logger logger = Logger.getLogger(ASTImportStatement.class);
public ASTImportStatement(int id) {
super(id);
}
public ASTImportStatement(Parser p, int id) {
super(p, id);
}
/** Accept the visitor. **/
@Override
public Object jjtAccept(ParserVisitor visitor, Object data) {
return visitor.visit(this, data);
}
}
| true
|
198358a54cdd40494d9c4f8be867b9aaa95f6db4
|
Java
|
churakovIA/javarush
|
/2.JavaCore/src/com/javarush/task/task12/task1206/Solution.java
|
UTF-8
| 307
| 1.960938
| 2
|
[] |
no_license
|
package com.javarush.task.task12.task1206;
/*
Выполняем перегрузку!
*/
public class Solution {
public static void main(String[] args) {
}
//Напишите тут ваши методы
private static void print(int n) {}
private static void print(String n) {}
}
| true
|
d05b26dd5f5c4dff1c3d05942460df7fdb922fea
|
Java
|
weibruce/JAVA2
|
/GUI Applications/OrderGUI/OrderGUI.java
|
UTF-8
| 2,028
| 3.375
| 3
|
[] |
no_license
|
import java.awt.*;
import javax.swing.*;
/**
* Write a description of class OrderGUI here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class OrderGUI extends JPanel
{
protected BagelPanel bagels; // Bagel panel
protected ToppingPanel toppings; // Topping panel
protected CoffeePanel coffee; // Coffee panel
protected GreetingPanel banner; // To display a greeting
protected JPanel buttonPanel;// To hold the buttons
protected JButton calcButton, // To calculate the cost
exitButton; // To exit the application
/**
* Constructor for objects of class OrderGUI
*/
public OrderGUI()
{
// Create a BorderLayout manager.
setLayout(new BorderLayout());
// Create the custom panels.
banner = new GreetingPanel();
bagels = new BagelPanel();
toppings = new ToppingPanel();
coffee = new CoffeePanel();
// Create the button panel.
buildButtonPanel();
// Add the components to the content pane.
add(banner, BorderLayout.NORTH);
add(bagels, BorderLayout.WEST);
add(toppings, BorderLayout.CENTER);
add(coffee, BorderLayout.EAST);
add(buttonPanel,BorderLayout.SOUTH);
}
/**
* The buildButtonPanel method builds the button panel.
*/
private void buildButtonPanel()
{
// Create a panel for the buttons.
buttonPanel = new JPanel();
// Create the buttons.
calcButton = new JButton("Calculate");
exitButton = new JButton("Exit");
//Register the action listeners.
OrderHandler handler = new OrderHandler(this);
calcButton.addActionListener(handler);
exitButton.addActionListener(handler);
// Add the buttons to the button panel.
buttonPanel.add(calcButton);
buttonPanel.add(exitButton);
}
}
| true
|
b6a13fa134708e5c7ba7386a5817c174080f2216
|
Java
|
zhouwanfeng/keycloak
|
/services/src/main/java/org/keycloak/forms/account/freemarker/model/ReferrerBean.java
|
UTF-8
| 387
| 1.976563
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.keycloak.forms.account.freemarker.model;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class ReferrerBean {
private String[] referrer;
public ReferrerBean(String[] referrer) {
this.referrer = referrer;
}
public String getName() {
return referrer[0];
}
public String getUrl() {
return referrer[1];
}
}
| true
|
9c250eef03902614c5a4b739cefd7c2ccd0064a3
|
Java
|
ericjack77/L2018020804
|
/app/src/main/java/com/example/student/l2018020804/MainActivity.java
|
UTF-8
| 916
| 2.140625
| 2
|
[] |
no_license
|
package com.example.student.l2018020804;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
MyReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiver = new MyReceiver();
}
public void click1(View v)
{
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.setPriority(500);
registerReceiver(receiver,filter);
}
public void click2(View v)
{
unregisterReceiver(receiver);
}
public void click3(View v)
{
Intent it=new Intent("myaction");
sendBroadcast(it);
}
}
| true
|
c166eb3460ffbe56bbe07def718fc2eee99533ca
|
Java
|
fieldenms/tg
|
/platform-pojo-bl/src/main/java/ua/com/fielden/platform/expression/ast/visitor/TypeEnforcementVisitor.java
|
UTF-8
| 42,405
| 2.328125
| 2
|
[
"MIT"
] |
permissive
|
package ua.com.fielden.platform.expression.ast.visitor;
import static java.lang.String.format;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collection;
import java.util.Date;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.expression.EgTokenCategory;
import ua.com.fielden.platform.expression.ast.AbstractAstVisitor;
import ua.com.fielden.platform.expression.ast.AstNode;
import ua.com.fielden.platform.expression.exception.semantic.CouldNotDetermineTypeException;
import ua.com.fielden.platform.expression.exception.semantic.SemanticException;
import ua.com.fielden.platform.expression.exception.semantic.TypeCompatibilityException;
import ua.com.fielden.platform.expression.exception.semantic.UnexpectedNumberOfOperandsException;
import ua.com.fielden.platform.expression.exception.semantic.UnsupportedTypeException;
import ua.com.fielden.platform.expression.type.AbstractDateLiteral;
import ua.com.fielden.platform.expression.type.DateLiteral;
import ua.com.fielden.platform.expression.type.Day;
import ua.com.fielden.platform.expression.type.Month;
import ua.com.fielden.platform.expression.type.Null;
import ua.com.fielden.platform.expression.type.Year;
import ua.com.fielden.platform.reflection.Finder;
import ua.com.fielden.platform.types.Money;
/**
* A visitor, which enforces type compatibility between AST nodes and identifies the type of the expression represented by the AST.
*
* @author TG Team
*
*/
public class TypeEnforcementVisitor extends AbstractAstVisitor {
public TypeEnforcementVisitor(final Class<? extends AbstractEntity> higherOrderType, final String contextProperty) {
super(higherOrderType, contextProperty);
}
public TypeEnforcementVisitor(final Class<? extends AbstractEntity> higherOrderType) {
super(higherOrderType, null);
}
@Override
public final void visit(final AstNode node) throws SemanticException {
final EgTokenCategory cat = EgTokenCategory.byIndex(node.getToken().category.getIndex());
switch (cat) {
// literal types
case INT:
node.setType(Integer.class);
node.setValue(Integer.parseInt(node.getToken().text));
break;
case DECIMAL:
node.setType(BigDecimal.class);
node.setValue(new BigDecimal(node.getToken().text));
break;
case STRING:
node.setType(String.class);
final String origValue = node.getToken().text;
final String value = origValue.substring(1, origValue.length() - 1); // removes double quotes from token
node.setValue(value); // value with removed double quotes
break;
case DATE_CONST:
processDateConstantToken(node);
break;
case DATE:
processDateLiteralToken(node);
break;
case SELF:
node.setType(getContextPropertyType());
break;
case NOW:
node.setType(Date.class);
break;
case NULL:
node.setType(Null.class);
break;
// property types
case NAME:
node.setType(identifyPropertyType(node));
break;
// bi-operand operation types
case PLUS:
case MINUS:
case MULT:
case DIV:
processOperation(node);
break;
// uno-operand date type functions
case YEAR:
case MONTH:
case DAY:
case HOUR:
case MINUTE:
case SECOND:
processDatePartExtractionFunction(node);
break;
// uno-operand string type functions
case UPPER:
case LOWER:
processStringFunction(node);
break;
// bi-operand date type functions
case DAY_DIFF: // TODO deprecated function
case YEARS:
case MONTHS:
case DAYS:
case HOURS:
case MINUTES:
case SECONDS:
processDateDiffFunctions(node);
break;
// uno-operand aggregation functions
case AVG:
case SUM:
processAvgSum(node);
break;
case MIN:
case MAX:
processMinMax(node);
break;
case COUNT:
processCount(node);
break;
case LT:
case GT:
case LE:
case GE:
case EQ:
case NE:
processComparisonOperator(node);
break;
case AND:
case OR:
processLogicalOperator(node);
break;
case CASE:
processCaseOperator(node);
break;
case WHEN:
processWhenOperator(node);
break;
default:
throw new TypeCompatibilityException("Unexpected token " + node.getToken() + " in AST node.", node.getToken());
}
}
private void processComparisonOperator(final AstNode node) throws SemanticException {
final EgTokenCategory cat = EgTokenCategory.byIndex(node.getToken().category.getIndex());
if (node.getChildren().size() != 2) {
throw new UnexpectedNumberOfOperandsException("Operation " + cat + " expects 2 operands, found " + node.getChildren().size(), node.getToken());
}
// check if the operands have type
final AstNode leftOperand = node.getChildren().get(0);
final Class<?> leftOperandType = leftOperand.getType();
if (leftOperandType == null) {
throw new TypeCompatibilityException("Operand " + leftOperand + " is missing type.", leftOperand.getToken());
}
final AstNode rightOperand = node.getChildren().get(1);
final Class<?> rightOperandType = rightOperand.getType();
if (rightOperandType == null) {
throw new TypeCompatibilityException("Operand " + rightOperand + " is missing type.", rightOperand.getToken());
}
// check compatibility of operand types
// TODO more precise error reporting can be achieved here
if (String.class.isAssignableFrom(leftOperandType) && leftOperandType.isAssignableFrom(rightOperandType)
|| // strings are comparable
Money.class.isAssignableFrom(leftOperandType) && (leftOperandType.isAssignableFrom(rightOperandType) || Number.class.isAssignableFrom(rightOperandType))
|| // money are comparable with each other and numbers
Number.class.isAssignableFrom(leftOperandType) && (Number.class.isAssignableFrom(rightOperandType) || Money.class.isAssignableFrom(rightOperandType))
|| // the same, but in reverse order
(Date.class.isAssignableFrom(leftOperandType) || DateTime.class.isAssignableFrom(leftOperandType))
&& (Date.class.isAssignableFrom(rightOperandType) || DateTime.class.isAssignableFrom(rightOperandType)) || // dates are comparable
Day.class.isAssignableFrom(leftOperandType) && rightOperand.getToken().category == EgTokenCategory.DAYS || // day literal is comparable only with DAYS function
leftOperand.getToken().category == EgTokenCategory.DAYS && Day.class.isAssignableFrom(rightOperandType) || // the same, but in reverse
Month.class.isAssignableFrom(leftOperandType) && rightOperand.getToken().category == EgTokenCategory.MONTHS || // month literal is comparable only with MONTHS function
leftOperand.getToken().category == EgTokenCategory.MONTHS && Month.class.isAssignableFrom(rightOperandType) || // the same, but in reverse
Year.class.isAssignableFrom(leftOperandType) && rightOperand.getToken().category == EgTokenCategory.YEARS || // year literal is comparable only with YEARS function
leftOperand.getToken().category == EgTokenCategory.YEARS && Year.class.isAssignableFrom(rightOperandType)) { // the same, but in reverse
// the type of the comparison operation is always boolean
node.setType(boolean.class);
} else if ((cat == EgTokenCategory.EQ || cat == EgTokenCategory.NE) && leftOperandType.isAssignableFrom(rightOperandType) && Null.class != leftOperandType
&& Null.class != rightOperandType) { // this basically checks whether some other types such as entities are being compared
node.setType(boolean.class);
} else if ((cat == EgTokenCategory.EQ || cat == EgTokenCategory.NE) && (Null.class == leftOperandType || Null.class == rightOperandType)) { // = and <> with NULL is possible, and needs to be validated further
if (Null.class == leftOperandType && (String.class.isAssignableFrom(rightOperandType) || //
Money.class.isAssignableFrom(rightOperandType) || //
Number.class.isAssignableFrom(rightOperandType) || //
Date.class.isAssignableFrom(rightOperandType) || //
DateTime.class.isAssignableFrom(rightOperandType) || //
AbstractEntity.class.isAssignableFrom(rightOperandType) //
)) {
// the type of the comparison operation is always boolean
node.setType(boolean.class);
} else if (String.class.isAssignableFrom(leftOperandType) || //
Money.class.isAssignableFrom(leftOperandType) || //
Number.class.isAssignableFrom(leftOperandType) || //
Date.class.isAssignableFrom(leftOperandType) || //
DateTime.class.isAssignableFrom(leftOperandType) || //
AbstractEntity.class.isAssignableFrom(leftOperandType)) { //
// the type of the comparison operation is always boolean
node.setType(boolean.class);
}
} else {
throw new UnsupportedTypeException("Operands for operation " + cat + " should have compatible types.", leftOperandType, node.getToken());
}
}
private void processLogicalOperator(final AstNode node) throws SemanticException {
final EgTokenCategory cat = EgTokenCategory.byIndex(node.getToken().category.getIndex());
if (node.getChildren().size() != 2) {
throw new UnexpectedNumberOfOperandsException("Operation " + cat + " expects 2 operands, found " + node.getChildren().size(), node.getToken());
}
// check if the operands have type
final AstNode leftOperand = node.getChildren().get(0);
final Class<?> leftOperandType = leftOperand.getType();
if (leftOperandType == null) {
throw new TypeCompatibilityException("Operand " + leftOperand + " is missing type.", leftOperand.getToken());
}
final AstNode rightOperand = node.getChildren().get(1);
final Class<?> rightOperandType = rightOperand.getType();
if (rightOperandType == null) {
throw new TypeCompatibilityException("Operand " + rightOperand + " is missing type.", rightOperand.getToken());
}
// check compatibility of operand types
if (!boolean.class.isAssignableFrom(leftOperandType) || !boolean.class.isAssignableFrom(rightOperandType)) {
throw new UnsupportedTypeException("Operands for operation " + cat + " should both be of boolean type.", leftOperandType, node.getToken());
}
node.setType(boolean.class);
}
private void processCaseOperator(final AstNode node) throws SemanticException {
// ensure that all operands have type assigned
// and that all those types are the same
Class<?> resultantType = null;
for (final AstNode child : node.getChildren()) {
if (child.getType() == null) {
throw new TypeCompatibilityException(format("Operand %s is missing type.", child), child.getToken());
}
// if resultantType has not been assigned yet then the current child is the first one
// and its type should be used as the reference type
if (resultantType == null) {
resultantType = child.getType();
} else { // let's try to resolve type
final Optional<Class<?>> resolvedType = resolveExpressionTypes(resultantType, child.getType());
if (resolvedType.isPresent()) { // resolved?
resultantType = resolvedType.get();
} else { // otherwise compare the reference and the current child's type
throw new TypeCompatibilityException(format("Operand %s has type %s that is different to type %s of preceeding operand(s).", child, child.getType(), resultantType), child.getToken());
}
}
}
node.setType(resultantType);
}
private void processWhenOperator(final AstNode node) throws SemanticException {
final EgTokenCategory cat = EgTokenCategory.byIndex(node.getToken().category.getIndex());
if (node.getChildren().size() != 2) {
throw new UnexpectedNumberOfOperandsException("Operation " + cat + " expects 2 operands, found " + node.getChildren().size(), node.getToken());
}
// check if the operands have type
final AstNode leftOperand = node.getChildren().get(0);
final Class<?> leftOperandType = leftOperand.getType();
if (leftOperandType == null) {
throw new TypeCompatibilityException("Operand " + leftOperand + " is missing type.", leftOperand.getToken());
}
final AstNode rightOperand = node.getChildren().get(1);
final Class<?> rightOperandType = rightOperand.getType();
if (rightOperandType == null) {
throw new TypeCompatibilityException("Operand " + rightOperand + " is missing type.", rightOperand.getToken());
}
// check compatibility of operand types
if (!boolean.class.isAssignableFrom(leftOperandType)) {
throw new UnsupportedTypeException("First operand for operation " + cat + " should be of boolen type.", leftOperandType, node.getToken());
}
// the type of the CASE WHEN expression is determined by the type of its right operand
node.setType(rightOperandType);
}
private void processAvgSum(final AstNode node) throws SemanticException {
final EgTokenCategory cat = EgTokenCategory.byIndex(node.getToken().category.getIndex());
if (node.getChildren().size() != 1) {
throw new UnexpectedNumberOfOperandsException("Operation " + cat + " expects 1 operand, found " + node.getChildren().size(), node.getToken());
}
// ensure that type of the operand is determined
final Class<?> operandType = node.getChildren().get(0).getType();
if (operandType == null) {
throw new TypeCompatibilityException("Operand " + node.getChildren().get(0) + " is missing type.", node.getChildren().get(0).getToken());
}
// validate operand type
if (!Money.class.isAssignableFrom(operandType) && !BigDecimal.class.isAssignableFrom(operandType) && !Integer.class.isAssignableFrom(operandType)) {
throw new UnsupportedTypeException(operandType, node.getToken());
}
// check whether operand is a constant value
if (node.getChildren().get(0).getValue() != null) {
throw new TypeCompatibilityException("Constant value is not applicable to aggregation functions.", node.getChildren().get(0).getToken());
}
// determine resulting type
if (EgTokenCategory.AVG == cat) {
if (Money.class.isAssignableFrom(operandType)) {
node.setType(Money.class);
} else {
node.setType(BigDecimal.class);
}
} else if (EgTokenCategory.SUM == cat) {
if (Money.class.isAssignableFrom(operandType)) {
node.setType(Money.class);
} else if (BigDecimal.class.isAssignableFrom(operandType)) {
node.setType(BigDecimal.class);
} else if (Integer.class.isAssignableFrom(operandType)) {
node.setType(Integer.class);
}
}
}
/**
* Validates correctness of the operand for the MIN, MAX aggregation functions and determines the type of the node.
*
* @param node
* @throws SemanticException
*/
private void processMinMax(final AstNode node) throws SemanticException {
final EgTokenCategory cat = EgTokenCategory.byIndex(node.getToken().category.getIndex());
if (node.getChildren().size() != 1) {
throw new UnexpectedNumberOfOperandsException("Operation " + cat + " expects 1 operand, found " + node.getChildren().size(), node.getToken());
}
// ensure that type of the operand is determined
final Class<?> operandType = node.getChildren().get(0).getType();
if (operandType == null) {
throw new TypeCompatibilityException("Operand " + node.getChildren().get(0) + " is missing type.", node.getChildren().get(0).getToken());
}
// validate operand type
if (!Money.class.isAssignableFrom(operandType) && !BigDecimal.class.isAssignableFrom(operandType) && !Integer.class.isAssignableFrom(operandType)
&& !Date.class.isAssignableFrom(operandType) && !DateTime.class.isAssignableFrom(operandType) && !String.class.isAssignableFrom(operandType)) {
throw new UnsupportedTypeException(operandType, node.getToken());
}
// check whether operand is a constant value
if (node.getChildren().get(0).getValue() != null) {
throw new TypeCompatibilityException("Constant value is not applicable to aggregation functions.", node.getChildren().get(0).getToken());
}
// resulting type should be compatible or match the operand type
if (Money.class.isAssignableFrom(operandType)) {
node.setType(Money.class);
} else if (BigDecimal.class.isAssignableFrom(operandType)) {
node.setType(BigDecimal.class);
} else if (Integer.class.isAssignableFrom(operandType)) {
node.setType(Integer.class);
} else if (Date.class.isAssignableFrom(operandType)) {
node.setType(Date.class);
} else if (DateTime.class.isAssignableFrom(operandType)) {
node.setType(DateTime.class);
} else {
node.setType(operandType);
}
}
/**
* Validates correctness of the operand for the COUNT aggregation function and determines the type of the node.
*
* @param node
* @throws SemanticException
*/
private void processCount(final AstNode node) throws SemanticException {
final EgTokenCategory cat = EgTokenCategory.byIndex(node.getToken().category.getIndex());
if (node.getChildren().size() != 1) {
throw new UnexpectedNumberOfOperandsException("Operation " + cat + " expects 1 operands, found " + node.getChildren().size(), node.getToken());
}
// ensure that type of the operand is determined
final Class<?> operandType = node.getChildren().get(0).getType();
if (operandType == null) {
throw new TypeCompatibilityException("Operand " + node.getChildren().get(0) + " is missing type.", node.getChildren().get(0).getToken());
}
// check whether operand is a constant value
if (node.getChildren().get(0).getValue() != null) {
throw new TypeCompatibilityException("Constant value is not applicable to aggregation functions.", node.getChildren().get(0).getToken());
}
// set the node type
node.setType(Integer.class);
}
/**
* Validates correctness of operands for functions DAYS, MONTHS, YEARS and determines the type of the node.
*
* @param node
* @throws SemanticException
*/
private void processDateDiffFunctions(final AstNode node) throws SemanticException {
final EgTokenCategory cat = EgTokenCategory.byIndex(node.getToken().category.getIndex());
if (node.getChildren().size() != 2) {
throw new UnexpectedNumberOfOperandsException("Operation " + cat + " expects 2 operands, found " + node.getChildren().size(), node.getToken());
}
// ensure that types of the operands are determined
final AstNode firstOperand = node.getChildren().get(0);
final Class<?> firstOperandType = firstOperand.getType();
if (firstOperandType == null) {
throw new TypeCompatibilityException("Operand " + firstOperand + " is missing type.", firstOperand.getToken());
}
final AstNode secondOperand = node.getChildren().get(1);
final Class<?> secondOperandType = secondOperand.getType();
if (secondOperandType == null) {
throw new TypeCompatibilityException("Operand " + secondOperand + " is missing type.", secondOperand.getToken());
}
// validate operand types
if (!Date.class.isAssignableFrom(firstOperandType) && !DateTime.class.isAssignableFrom(firstOperandType)) {
throw new UnsupportedTypeException(firstOperandType, firstOperand.getToken());
}
if (!Date.class.isAssignableFrom(secondOperandType) && !DateTime.class.isAssignableFrom(secondOperandType)) {
throw new UnsupportedTypeException(secondOperandType, secondOperand.getToken());
}
// set the node type
node.setType(Integer.class);
}
/**
* Validates correctness of the operand for the string functions UPPER, LOWER and determines the type of the node.
*
* @param node
* @throws SemanticException
*/
private void processStringFunction(final AstNode node) throws SemanticException {
final EgTokenCategory cat = EgTokenCategory.byIndex(node.getToken().category.getIndex());
if (node.getChildren().size() != 1) {
throw new UnexpectedNumberOfOperandsException("Operation " + cat + " expects 1 operand, found " + node.getChildren().size(), node.getToken());
}
// ensure that type of the operand is determined
final Class<?> operandType = node.getChildren().get(0).getType();
if (operandType == null) {
throw new TypeCompatibilityException("Operand " + node.getChildren().get(0) + " is missing type.", node.getChildren().get(0).getToken());
}
// validate operand type
if (!String.class.isAssignableFrom(operandType)) {
throw new UnsupportedTypeException(operandType, node.getChildren().get(0).getToken());
}
// set the node type
node.setType(String.class);
}
/**
* Validates correctness of the operand for the date part extraction functions such as DAY, MONTH, YEAR and determines the type of the node.
*
* @param node
* @throws SemanticException
*/
private void processDatePartExtractionFunction(final AstNode node) throws SemanticException {
final EgTokenCategory cat = EgTokenCategory.byIndex(node.getToken().category.getIndex());
if (node.getChildren().size() != 1) {
throw new UnexpectedNumberOfOperandsException("Operation " + cat + " expects 1 operand, found " + node.getChildren().size(), node.getToken());
}
// ensure that type of the operand is determined
final Class<?> operandType = node.getChildren().get(0).getType();
if (operandType == null) {
throw new TypeCompatibilityException("Operand " + node.getChildren().get(0) + " is missing type.", node.getChildren().get(0).getToken());
}
// validate operand type
if (!Date.class.isAssignableFrom(operandType) && !DateTime.class.isAssignableFrom(operandType)) {
throw new UnsupportedTypeException(operandType, node.getChildren().get(0).getToken());
}
// set the node type
node.setType(Integer.class);
}
/**
* Identifies AST node type based the property type.
*
* @param node
* @return
* @throws UnsupportedTypeException
*/
private Class<?> identifyPropertyType(final AstNode node) throws UnsupportedTypeException {
final Field field = Finder.findFieldByName(getHigherOrderType(), relative2Absolute(node.getToken().text));
final Class<?> type = field.getType();
if (Money.class.isAssignableFrom(type)) {
return Money.class;
} else if (BigDecimal.class.isAssignableFrom(type) || double.class.isAssignableFrom(type)) {
return BigDecimal.class;
} else if (Integer.class.isAssignableFrom(type) || int.class.isAssignableFrom(type)) {
return Integer.class;
} else if (String.class.isAssignableFrom(type)) {
return String.class;
} else if (DateTime.class.isAssignableFrom(type)) {
return DateTime.class;
} else if (Date.class.isAssignableFrom(type)) {
return Date.class;
} else if (boolean.class.isAssignableFrom(type) || Boolean.class.isAssignableFrom(type)) {
return type;
} else if (Collection.class.isAssignableFrom(type)) {
return type;
} else if (AbstractEntity.class.isAssignableFrom(type)) {
return type;
}
throw new UnsupportedTypeException(type, node.getToken());
}
/**
* Determines the type of the operation and calculates the value if possible.
*
* Value calculation is possible if the operands are reducible to constants (i.e. have value).
*
* @param node
* @param cat
* @throws SemanticException
*/
private void processOperation(final AstNode node) throws SemanticException {
final EgTokenCategory cat = EgTokenCategory.byIndex(node.getToken().category.getIndex());
if (node.getChildren().size() != 2) {
throw new UnexpectedNumberOfOperandsException("Operation " + cat + " expects 2 operands, found " + node.getChildren().size(), node.getToken());
}
// check if the operands have type
final AstNode leftOperand = node.getChildren().get(0);
final Class<?> leftOperandType = leftOperand.getType();
if (leftOperandType == null) {
throw new TypeCompatibilityException("Operand " + leftOperand + " is missing type.", leftOperand.getToken());
}
final AstNode rightOperand = node.getChildren().get(1);
final Class<?> rightOperandType = rightOperand.getType();
if (rightOperandType == null) {
throw new TypeCompatibilityException("Operand " + rightOperand + " is missing type.", rightOperand.getToken());
}
// check compatibility of operand types
// the type of the operation should be the lease restrictive type of its operands
node.setType(operationType(node, leftOperandType, rightOperandType, cat));
if (node.getType() == null) {
throw new CouldNotDetermineTypeException("Could not determine type for operation " + node, node.getToken());
}
// evaluate the operation
node.setValue(evaluateOperation(node));
}
/**
* A utility function that determines the best possible type out of the two provided from the perspective of type compatibility
* in the scope of the expression query language.
* <p>
* In cases where the provided types are not compatible in any way, an empty result is returned.
* <p>
* It is important to understand that this type resolution does not take into account the operation.
* For example, division of two integers should resolve to BigDecimal based on the logic in {@link #operationType(AstNode, Class, Class, EgTokenCategory).
* However, applying type resolution to two <code>Integer.class</code> arguments would return <code>Integer.class</code>.
* Therefore, whenever an operation influences type resolution, this method should not be used.
* <p>
* Please refer test case <code>TypeEnforcementTypeCompatibilityTest</code> for more details to better understand type compatibility in this context.
*
* @param type1
* @param type2
* @return
*/
public static Optional<Class<?>> resolveExpressionTypes(final Class<?> type1, final Class<?> type2) {
// first let's simply check subtyping rules with primitive boolean to overrule Boolean.
// this covers cases where both types are the same
// and cases where types are mutually incompatible such as Date, String and Numeric (includes Integer, BigDecimal and Money)
if (type1.isAssignableFrom(type2)) {
return Boolean.class.isAssignableFrom(type1) ? Optional.of(boolean.class) : Optional.of(type1);
} else if (type2.isAssignableFrom(type1)) {
return Boolean.class.isAssignableFrom(type2) ? Optional.of(boolean.class) : Optional.of(type2);
}
// let's check booleans, which should always resolve to primitive type boolean
if (Boolean.class.isAssignableFrom(type1) && boolean.class.isAssignableFrom(type2) ||
boolean.class.isAssignableFrom(type1) && Boolean.class.isAssignableFrom(type2)) {
return Optional.of(boolean.class);
}
// there could still be the case of numeric compatibility
if (BigDecimal.class.isAssignableFrom(type1)) {
if (Integer.class.isAssignableFrom(type2)) {
return Optional.of(BigDecimal.class); // BigDecimal wins over Integer
} else if (Money.class.isAssignableFrom(type2)) {
return Optional.of(Money.class); // Money winds over BigDecimal
}
} else if (Integer.class.isAssignableFrom(type1)) {
if (BigDecimal.class.isAssignableFrom(type2)) {
return Optional.of(BigDecimal.class); // BigDecimal wins over Integer
} else if (Money.class.isAssignableFrom(type2)) {
return Optional.of(Money.class); // Money winds over Integer
}
} else if (Money.class.isAssignableFrom(type1)) {
if (BigDecimal.class.isAssignableFrom(type2) || Integer.class.isAssignableFrom(type2)) {
return Optional.of(Money.class); // Money wins over BigDecimal and Integer
}
}
return Optional.empty();
}
/**
* Provides the rules for identifying types of operation operands and the resultant operation type.
*
* @param node
* @param leftOperandType
* @param rightOperandType
* @param cat
* @return
* @throws SemanticException
*/
private Class<?> operationType(final AstNode node, final Class<?> leftOperandType, final Class<?> rightOperandType, final EgTokenCategory cat) throws SemanticException {
// Date is not supported
if (isDate(leftOperandType)) {
throw new UnsupportedTypeException("Left operand of date type is not applicable to operation " + cat, leftOperandType, node.getToken());
}
if (isDate(rightOperandType)) {
throw new UnsupportedTypeException("Right operand of date type are not applicable to operation " + cat, rightOperandType, node.getToken());
}
// collectional and entity types are not supported
if (Collection.class.isAssignableFrom(leftOperandType)) {
throw new UnsupportedTypeException("Left operand of collectional type is not applicable to operation " + cat, leftOperandType, node.getToken());
}
if (Collection.class.isAssignableFrom(rightOperandType)) {
throw new UnsupportedTypeException("Right operand of collectional type is not applicable to operation " + cat, leftOperandType, node.getToken());
}
if (AbstractEntity.class.isAssignableFrom(leftOperandType)) {
throw new UnsupportedTypeException("Left operand of entity type is not applicable to operation " + cat, leftOperandType, node.getToken());
}
if (AbstractEntity.class.isAssignableFrom(rightOperandType)) {
throw new UnsupportedTypeException("Right operand of entity type is not applicable to operation " + cat, leftOperandType, node.getToken());
}
switch (cat) {
case PLUS:
return resolveExpressionTypes(leftOperandType, rightOperandType).orElse(null);
case MINUS:
if (String.class.isAssignableFrom(leftOperandType) || String.class.isAssignableFrom(rightOperandType)) {
throw new UnsupportedTypeException(format("Operands of String type are not applicable to operation %s", cat), String.class, node.getToken());
}
return resolveExpressionTypes(leftOperandType, rightOperandType).orElse(null);
case MULT:
if (String.class.isAssignableFrom(leftOperandType) || String.class.isAssignableFrom(rightOperandType)) {
throw new UnsupportedTypeException("Operands of string type are not applicable to operation " + cat, String.class, node.getToken());
}
if (AbstractDateLiteral.class.isAssignableFrom(leftOperandType) || AbstractDateLiteral.class.isAssignableFrom(rightOperandType)) {
throw new UnsupportedTypeException("Operands of date literal type are not applicable to operation " + cat, AbstractDateLiteral.class, node.getToken());
}
return resolveExpressionTypes(leftOperandType, rightOperandType).orElse(null);
case DIV:
if (String.class.isAssignableFrom(leftOperandType) || String.class.isAssignableFrom(rightOperandType)) {
throw new UnsupportedTypeException("Operands of string type are not applicable to operation " + cat, String.class, node.getToken());
}
if (AbstractDateLiteral.class.isAssignableFrom(leftOperandType) || AbstractDateLiteral.class.isAssignableFrom(rightOperandType)) {
throw new UnsupportedTypeException("Operands of date literal type are not applicable to operation " + cat, AbstractDateLiteral.class, node.getToken());
}
// in case of DIV operation resolveExpressionTypes cannot be used due to special rules
// so, let's proceed manually case by case
// is BigDecimal or Money?
if (BigDecimal.class.isAssignableFrom(leftOperandType)) {
if (leftOperandType.isAssignableFrom(rightOperandType) || Integer.class.isAssignableFrom(rightOperandType)) {
return BigDecimal.class;
} else if (Money.class.isAssignableFrom(rightOperandType)) {
return Money.class;
}
}
// is Integer or Money?
if (Integer.class.isAssignableFrom(leftOperandType)) {
if (leftOperandType.isAssignableFrom(rightOperandType) || BigDecimal.class.isAssignableFrom(rightOperandType)) {
return BigDecimal.class;
} else if (Money.class.isAssignableFrom(rightOperandType)) {
return Money.class;
}
return Integer.class;
}
// is Money or Integer or BigDecimal?
if (Money.class.isAssignableFrom(leftOperandType)) {
if (leftOperandType.isAssignableFrom(rightOperandType)) {
return BigDecimal.class;
}
if (Integer.class.isAssignableFrom(rightOperandType) || BigDecimal.class.isAssignableFrom(rightOperandType)) {
return Money.class;
}
}
break;
default:
break;
}
return null;
}
private boolean isDate(final Class<?> type) {
return Date.class.isAssignableFrom(type) || DateTime.class.isAssignableFrom(type);
}
/**
* Calculates the operation result is possible.
*
* @param node
*/
private static final String DBL_QUOTE = "\"";
private Object evaluateOperation(final AstNode node) {
final EgTokenCategory cat = EgTokenCategory.byIndex(node.getToken().category.getIndex());
final AstNode leftOperand = node.getChildren().get(0);
final AstNode rightOperand = node.getChildren().get(1);
if (leftOperand.hasValue() && rightOperand.hasValue()) {
switch (cat) {
case PLUS:
if (BigDecimal.class.isAssignableFrom(node.getType())) {
final BigDecimal value = new BigDecimal(leftOperand.getValue().toString()).add(new BigDecimal(rightOperand.getValue().toString()));
return value;
} else if (Integer.class.isAssignableFrom(node.getType())) {
final Integer value = new Integer(leftOperand.getValue().toString()) + new Integer(rightOperand.getValue().toString());
return value;
} else if (String.class.isAssignableFrom(node.getType())) {
final String value = DBL_QUOTE + StringUtils.remove(leftOperand.getValue().toString(), DBL_QUOTE) + StringUtils.remove(rightOperand.getValue().toString(), DBL_QUOTE) + DBL_QUOTE;
return value;
} else if (Day.class.isAssignableFrom(node.getType())) {
return ((Integer) leftOperand.getValue()) + ((Integer) rightOperand.getValue());
} else if (Month.class.isAssignableFrom(node.getType())) {
return ((Integer) leftOperand.getValue()) + ((Integer) rightOperand.getValue());
} else if (Year.class.isAssignableFrom(node.getType())) {
return ((Integer) leftOperand.getValue()) + ((Integer) rightOperand.getValue());
}
break;
case MINUS:
if (BigDecimal.class.isAssignableFrom(node.getType())) {
final BigDecimal value = new BigDecimal(leftOperand.getValue().toString()).subtract(new BigDecimal(rightOperand.getValue().toString()));
return value;
} else if (Integer.class.isAssignableFrom(node.getType())) {
final Integer value = new Integer(leftOperand.getValue().toString()) - new Integer(rightOperand.getValue().toString());
return value;
} else if (Day.class.isAssignableFrom(node.getType())) {
return ((Integer) leftOperand.getValue()) - ((Integer) rightOperand.getValue());
} else if (Month.class.isAssignableFrom(node.getType())) {
return ((Integer) leftOperand.getValue()) - ((Integer) rightOperand.getValue());
} else if (Year.class.isAssignableFrom(node.getType())) {
return ((Integer) leftOperand.getValue()) - ((Integer) rightOperand.getValue());
}
break;
case MULT:
if (BigDecimal.class.isAssignableFrom(node.getType())) {
final BigDecimal value = new BigDecimal(leftOperand.getValue().toString()).multiply(new BigDecimal(rightOperand.getValue().toString()));
return value;
} else if (Integer.class.isAssignableFrom(node.getType())) {
final Integer value = new Integer(leftOperand.getValue().toString()) * new Integer(rightOperand.getValue().toString());
return value;
}
break;
case DIV:
if (BigDecimal.class.isAssignableFrom(node.getType()) || Integer.class.isAssignableFrom(node.getType())) {
final BigDecimal value = new BigDecimal(leftOperand.getValue().toString()).setScale(4, RoundingMode.HALF_EVEN).divide(new BigDecimal(rightOperand.getValue().toString()).setScale(4, RoundingMode.HALF_EVEN), RoundingMode.HALF_EVEN);
return value;
}
break;
}
}
return null;
}
/**
* Processes DATE_CONST token in order to update the node with correct type and value.
*
* @param node
* @throws TypeCompatibilityException
*/
private void processDateConstantToken(final AstNode node) throws TypeCompatibilityException {
final String text = node.getToken().text;
final String valueText = text.substring(0, text.length() - 1);
if (text.endsWith(DateLiteral.DAY.discriminator)) {
node.setType(Day.class);
node.setValue(Integer.parseInt(valueText));
} else if (text.endsWith(DateLiteral.MONTH.discriminator)) {
node.setType(Month.class);
node.setValue(Integer.parseInt(valueText));
} else if (text.endsWith(DateLiteral.YEAR.discriminator)) {
node.setType(Year.class);
node.setValue(Integer.parseInt(valueText));
} else {
throw new TypeCompatibilityException("Value " + node.getToken().text + " could not be type casted to any of the date literal types.", node.getToken());
}
}
/**
* Processes DATE token in order to update the node with correct type and value.
*
* @param node
* @throws TypeCompatibilityException
*/
private void processDateLiteralToken(final AstNode node) {
final String pureDateStr = StringUtils.remove(node.getToken().text, "'");
final DateTime date;
// let's now check if we can covert recognised sequence to date
if (pureDateStr.split(" ").length == 2) { // has time portion
final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
date = formatter.parseDateTime(pureDateStr);
} else { // has only the date portion
final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");
date = formatter.parseDateTime(pureDateStr);
}
node.setType(Date.class);
node.setValue(date.toDate());
}
}
| true
|
8dcd972d86700cb9d73a5e1b42278b55bce60d8d
|
Java
|
cnoke/Dynamic
|
/dynamicpage/src/main/java/com/knd/dynamicpage/adapter/HonCourseNoTitleAdapter.java
|
UTF-8
| 2,013
| 1.984375
| 2
|
[] |
no_license
|
package com.knd.dynamicpage.adapter;
import androidx.recyclerview.widget.GridLayoutManager;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.layout.SingleLayoutHelper;
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder;
import com.knd.common.bean.FloorBean;
import com.knd.common.route.DynamicRouteManager;
import com.knd.common.utils.ScreenUtils;
import com.knd.dynamicannotations.Adapter;
import com.knd.dynamicpage.ModuleApp;
import com.knd.dynamicpage.R;
import com.knd.dynamicpage.adapter.base.FloorDelegateAdapter;
import com.knd.dynamicpage.databinding.DynamicItemRecycleviewBinding;
import com.knd.dynamicpage.itemAdapter.HonCourseContentAdapter;
import com.knd.dynamicpage.utils.DelegateViewType;
@Adapter(DelegateViewType.HonCourseNoTitle)
public class HonCourseNoTitleAdapter extends FloorDelegateAdapter {
public HonCourseNoTitleAdapter() {
super(R.layout.dynamic_item_recycleview,3,DelegateViewType.HonCourseNoTitle);
}
@Override
public LayoutHelper onCreateLayoutHelper() {
SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
int dp26 = (int)ScreenUtils.dp2px(ModuleApp.getInstance().appContext,26.67f);
layoutHelper.setPaddingLeft(dp26);
layoutHelper.setPaddingRight(dp26);
return layoutHelper;
}
@Override
protected void convert(BaseDataBindingHolder holder, FloorBean item) {
DynamicItemRecycleviewBinding viewBinding = (DynamicItemRecycleviewBinding)holder.getDataBinding();
viewBinding.recycleCourse.setLayoutManager(new GridLayoutManager(getContext(),3));
HonCourseContentAdapter adapter = new HonCourseContentAdapter(item.getElementDtoList());
adapter.setOnItemClickListener((adapter1, view, position) -> DynamicRouteManager.getInstance().route(item.getElementDtoList().get(position).getSkipUrl(),item.getElementDtoList().get(position).getParam()));
viewBinding.recycleCourse.setAdapter(adapter);
}
}
| true
|
6ff80646224431f2da9ae2c7163a8145c2b03a05
|
Java
|
c2921707677/test
|
/HelloWorld/src/tij/fourteen/Operation.java
|
UTF-8
| 149
| 1.75
| 2
|
[] |
no_license
|
/**
* 2018年11月23日
*/
package tij.fourteen;
/**
* @author chengj
*/
public interface Operation {
String description();
void command();
}
| true
|
7ded4060733d21c974b681e193dccd82e70f908d
|
Java
|
HuangRicher/tree
|
/service-fishing/src/main/java/com/tongzhu/fishing/service/impl/FishingSecretOperationServiceImpl.java
|
UTF-8
| 1,095
| 2.078125
| 2
|
[] |
no_license
|
package com.tongzhu.fishing.service.impl;
import com.tongzhu.fishing.mapper.FishingSecretOperationMapper;
import com.tongzhu.fishing.model.FishingSecretOperation;
import com.tongzhu.fishing.model.FishingSecretOperationExample;
import com.tongzhu.fishing.service.FishingSecretOperationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 好友操作
*/
@Service
public class FishingSecretOperationServiceImpl implements FishingSecretOperationService {
@Autowired
private FishingSecretOperationMapper fishingSecretOperationMapper;
@Override
public List<FishingSecretOperation> getSecretPrize(Integer begin, Integer end) {
FishingSecretOperationExample example=new FishingSecretOperationExample();
example.createCriteria().andNumberFishingGreaterThan(begin).andNumberFishingLessThanOrEqualTo(end);
List<FishingSecretOperation> fishingSecretOperations = fishingSecretOperationMapper.selectByExample(example);
return fishingSecretOperations;
}
}
| true
|
9637b086ab02b708ff4b06a5b0e840eef31f1474
|
Java
|
kanontds/springmvc
|
/src/main/javas/cn/springmvc/dao/LogInfoMapper.java
|
UTF-8
| 358
| 1.765625
| 2
|
[] |
no_license
|
package cn.springmvc.dao;
import cn.springmvc.model.LogInfo;
public interface LogInfoMapper {
int deleteByPrimaryKey(Short logid);
int insert(LogInfo record);
int insertSelective(LogInfo record);
LogInfo selectByPrimaryKey(Short logid);
int updateByPrimaryKeySelective(LogInfo record);
int updateByPrimaryKey(LogInfo record);
}
| true
|
5a1736ad44e0893ac1ced71792e5f14396e90cd7
|
Java
|
michaelrausch/Party-Parrots-At-Sea
|
/src/main/java/seng302/visualiser/fxObjects/assets_3D/BoatMeshType.java
|
UTF-8
| 2,783
| 2.6875
| 3
|
[] |
no_license
|
package seng302.visualiser.fxObjects.assets_3D;
/**
* Enum for boat meshes. Enum values should be of the form :
* ENUM_VALUE (hull file, mast file, Y offset of mast CoR from origin, sail file, Y offset of sail CoR from origin, jib file, fixed sail)
* Files must be valid .stl files.
*/
public enum BoatMeshType {
DINGHY("dinghy_hull.stl", "dinghy_mast.stl", 1.36653, "dinghy_sail.stl", 1.36653, null, false, 1.8, 1.0, 1.0),
CATAMARAN("catamaran_hull.stl", "catamaran_mast.stl", 0.997, "catamaran_sail.stl",
0.997, null, false, 1.0, 1.4, 2.0),
PIRATE_SHIP("pirateship_hull.stl", "pirateship_mast.stl", -0.5415, "pirateship_mainsail.stl",
-0.5415, "pirateship_frontsail.stl", true, 1.2, 1.6, 1.2),
DUCKY("ducky_hull.stl", "ducky_mast.stl", -2.18539, "ducky_sail.stl", -2.18539, "ducky_eyes.stl", false, 1.2, 1.1, 1.4),
PARROT("parrot_hull.stl", null, 0, "parrot_features.stl", 0, "parrot_sail.stl", true, 1, 1, 1),
WAKA("waka_hull.stl", "waka_mast.stl", 0, "waka_sail.stl", 0, null, true, 1.7, 0.5, 1.5);
final String hullFile, mastFile, sailFile, jibFile;
final double mastOffset, sailOffset;
public final double maxSpeedMultiplier;
public final double accelerationMultiplier;
public final double turnStep;
final boolean fixedSail;
final static BoatMeshType[] boatTypes = new BoatMeshType[]{DINGHY, CATAMARAN, PIRATE_SHIP, DUCKY, PARROT, WAKA};
BoatMeshType(String hullFile, String mastFile, double mastOffset, String sailFile,
double sailOffset, String jibFile, boolean fixedSail, double maxSpeedMultiplier, double accelerationMultiplier, double turnStep) {
this.hullFile = hullFile;
this.mastFile = mastFile;
this.mastOffset = mastOffset;
this.sailFile = sailFile;
this.sailOffset = sailOffset;
this.jibFile = jibFile;
this.fixedSail = fixedSail;
this.maxSpeedMultiplier = maxSpeedMultiplier;
this.accelerationMultiplier = accelerationMultiplier;
this.turnStep = turnStep;
}
public static BoatMeshType getNextBoatType(BoatMeshType boatType) {
for (int i = 0; i < boatTypes.length; i++) {
if (i == boatTypes.length -1) {
return boatTypes[0];
} else if (boatType == boatTypes[i]) {
return boatTypes[i+1];
}
}
return boatType;
}
public static BoatMeshType getPrevBoatType(BoatMeshType boatType) {
for (int i = 0; i < boatTypes.length; i++) {
if (i == 0 && boatType == boatTypes[i]) {
return boatTypes[boatTypes.length -1];
} else if (boatType == boatTypes[i]) {
return boatTypes[i-1];
}
}
return boatType;
}
}
| true
|
fd5de1d8dba49afe67406cf1e4463147db80f842
|
Java
|
Nthalk/ferret
|
/web/src/main/java/com/iodesystems/ferret/xsd/TypeExtension.java
|
UTF-8
| 700
| 1.882813
| 2
|
[] |
no_license
|
package com.iodesystems.ferret.xsd;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSchemaType;
public class TypeExtension extends HasId {
private String extensionTypeId;
private SearchType search;
public SearchType getSearch() {
return search;
}
@XmlAttribute
public void setSearch(SearchType search) {
this.search = search;
}
public String getExtensionTypeId() {
return extensionTypeId;
}
@XmlAttribute(required = true, name = "extends")
@XmlSchemaType(name = "IDREF")
public void setExtensionTypeId(String extensionTypeId) {
this.extensionTypeId = extensionTypeId;
}
}
| true
|
4f5bab02c42985eba975d51742b8f768afe4b3e2
|
Java
|
GJuly00720/hello_world
|
/total_webStudy03_ssMaven/src/main/java/kr/or/ddit/commons/controller/LogoutController.java
|
UTF-8
| 837
| 2.4375
| 2
|
[] |
no_license
|
package kr.or.ddit.commons.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import kr.or.ddit.mvc.ICommandHandler;
public class LogoutController implements ICommandHandler {
@Override
public String process(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//로그아웃 (먼저 로그인상태여야함.)
HttpSession session = req.getSession(false);
if(session == null || session.isNew()){ // 새로 만들어진 세션인지 확인해줌.
resp.sendError(400,"로그아웃전 로그인이 필요합니다");
return null;
}
session.invalidate();
return "redirect:/";
}
}
| true
|
a4ba64d1825d5ceab06aef4a1e15e1ee834211ec
|
Java
|
kerkox/pruebaAndroid
|
/app/src/main/java/com/example/root/holamundo/MainActivity.java
|
UTF-8
| 2,229
| 2.109375
| 2
|
[] |
no_license
|
package com.example.root.holamundo;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button boton;
Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//**************************************
boton = (Button) findViewById(R.id.boton);
boton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setMessage("Mensaje")
.setCancelable(false)
.setPositiveButton("Si", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//lo que quieras hacer cuando se da clic a si
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//lo que quieras hacer cuando se da clic a no
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
}
}
| true
|
538b8dd45a332cdf6346a0b44b4130dccab87e2f
|
Java
|
lastforeverzl/PetAdoption
|
/app/src/main/java/com/zackyzhang/petadoption/ui/activity/SearchActivity.java
|
UTF-8
| 9,448
| 1.78125
| 2
|
[] |
no_license
|
package com.zackyzhang.petadoption.ui.activity;
import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.AutocompleteFilter;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import com.zackyzhang.petadoption.ApiUtils;
import com.zackyzhang.petadoption.EndlessRecyclerViewScrollListener;
import com.zackyzhang.petadoption.data.PetAdoptionPreferences;
import com.zackyzhang.petadoption.R;
import com.zackyzhang.petadoption.data.RecentQuery;
import com.zackyzhang.petadoption.api.model.PetBean;
import com.zackyzhang.petadoption.ui.PetListAdapter;
import com.zackyzhang.petadoption.ui.QueryListAdapter;
import com.zackyzhang.petadoption.ui.base.BasePresenterActivity;
import com.zackyzhang.petadoption.ui.base.PresenterFactory;
import com.zackyzhang.petadoption.ui.base.SearchContract;
import com.zackyzhang.petadoption.ui.presenter.SearchPresenter;
import com.zackyzhang.petadoption.ui.presenter.SearchPresenterFactory;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import timber.log.Timber;
/**
* Created by lei on 8/13/17.
*/
public class SearchActivity extends BasePresenterActivity<SearchPresenter, SearchContract.View>
implements SearchContract.View, PlaceSelectionListener, PetListAdapter.OnPetClickListener {
private static final String TAG = "SearchActivity";
private PetAdoptionPreferences myPreferences;
private PlaceAutocompleteFragment placeAutocompleteFragment;
private PetListAdapter mSearchAdapter;
private QueryListAdapter mQueryListAdapter;
private SearchPresenter presenter;
private String mZipCode;
private EndlessRecyclerViewScrollListener scrollListener;
@BindView(R.id.rv_container)
ViewGroup resultsContainer;
@BindView(R.id.pet_list)
RecyclerView recyclerView;
@BindView(R.id.rv_recent_search)
RecyclerView recentSearchList;
@BindView(R.id.place_autocomplete_search_input)
EditText searchInput;
@BindView(R.id.place_autocomplete_clear_button)
View clearButton;
@BindView(R.id.place_autocomplete_search_button)
View searchButton;
@BindView(R.id.progress_bar)
ProgressBar mProgressBar;
@BindView(R.id.tv_no_pets_found)
TextView mNoPets;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
ButterKnife.bind(this);
setupPlaceAutoComplete();
setupRecyclerView();
resultsContainer.setVisibility(View.GONE);
}
@Override
protected void onStart() {
super.onStart();
presenter.getRecentQuery();
}
@NonNull
@Override
protected String tag() {
return "SearchActivity";
}
@NonNull
@Override
protected PresenterFactory<SearchPresenter> getPresenterFactory() {
myPreferences = PetAdoptionPreferences.getInstance(this);
return new SearchPresenterFactory(myPreferences);
}
@Override
protected void onPresenterCreatedOrRestored(@NonNull SearchPresenter presenter) {
this.presenter = presenter;
}
@Override
public void onPlaceSelected(Place place) {
if (place == null || place.getLatLng() == null) {
Toast.makeText(this, getString(R.string.search_empty_message), Toast.LENGTH_SHORT).show();
}
Timber.tag(TAG).d(String.valueOf(place.getAddress()));
mZipCode = ApiUtils.getZipCodeFromAddress(String.valueOf(place.getAddress()));
presenter.setZipCode(mZipCode);
mSearchAdapter.clearAdapter();
loadingPets(String.valueOf(place.getName()));
}
@Override
public void onError(Status status) {
Timber.tag(TAG).d("onError: Status = " + status.toString());
Toast.makeText(this, getString(R.string.search_failed_message, status.getStatusMessage()), Toast.LENGTH_SHORT).show();
}
@Override
public void loadData(List<PetBean> pets) {
if (pets == null) {
Timber.tag(TAG).d("loadData() pets is null");
mNoPets.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
clearButton.setVisibility(View.VISIBLE);
return;
}
resultsContainer.setVisibility(View.VISIBLE);
mSearchAdapter.setData(pets);
clearButton.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
}
@Override
public void setZipCode(String zipCode) {
mZipCode = zipCode;
}
@Override
public void loadRecentQuery(List<RecentQuery> recentQueryList) {
mQueryListAdapter.setQueryList(recentQueryList);
}
private void loadingPets(String locationName) {
resultsContainer.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
presenter.loadPets();
presenter.setRecentQuery(locationName, mZipCode);
}
private void loadingPetsFromQuery(String locationName, String type, String size, String sex, String age) {
resultsContainer.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
presenter.loadPetsFromQuery(mZipCode, type, size, sex, age);
presenter.setRecentQuery(locationName, mZipCode);
}
private void setupPlaceAutoComplete() {
placeAutocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
searchButton.setVisibility(View.GONE);
clearButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mSearchAdapter.clearAdapter();
placeAutocompleteFragment.setText("");
clearButton.setVisibility(View.GONE);
resultsContainer.setVisibility(View.GONE);
presenter.getRecentQuery();
}
});
placeAutocompleteFragment.setHint(getString(R.string.auto_complete_hint));
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setCountry(getString(R.string.search_country))
.build();
placeAutocompleteFragment.setFilter(typeFilter);
placeAutocompleteFragment.setOnPlaceSelectedListener(this);
}
private void setupRecyclerView() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
mSearchAdapter = new PetListAdapter(this, false);
mSearchAdapter.setOnPetClickListener(this);
recyclerView.setAdapter(mSearchAdapter);
scrollListener = new EndlessRecyclerViewScrollListener(linearLayoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
presenter.fetchMoreData();
}
};
recyclerView.addOnScrollListener(scrollListener);
recentSearchList.setLayoutManager(new LinearLayoutManager(this));
RecyclerView.ItemDecoration itemDecoration = new
DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
recentSearchList.addItemDecoration(itemDecoration);
mQueryListAdapter = new QueryListAdapter(this);
recentSearchList.setAdapter(mQueryListAdapter);
}
public void clickRecentQuery(String address, String zipCode, String type, String size, String sex, String age) {
mZipCode = zipCode;
loadingPetsFromQuery(address, type, size, sex, age);
clearButton.setVisibility(View.VISIBLE);
searchInput.setText(address);
}
@OnClick(R.id.id_filter)
public void filter() {
startActivity(new Intent(this, SearchFilterActivity.class));
}
@OnClick({ R.id.id_searchback })
protected void dismiss() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
finishAfterTransition();
} else {
finish();
}
}
@OnClick(R.id.clear_recent_query)
protected void clearRecentSearch() {
presenter.clearRecentSearch();
mQueryListAdapter.clearQueryList();
}
@Override
public void onItemClick(PetBean pet, View transitionView) {
Intent intent = PetDetailActivity.newIntent(this, pet);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
Bundle bundle = ActivityOptions.makeSceneTransitionAnimation(
SearchActivity.this, transitionView, transitionView.getTransitionName())
.toBundle();
startActivity(intent, bundle);
} else {
startActivity(intent);
}
}
}
| true
|
840a72c905f1e84bd52ec84603d804c8f139b1b0
|
Java
|
kingj1261/oa
|
/oa-web/src/main/java/com/wantai/oa/web/controller/common/CommonController.java
|
UTF-8
| 948
| 2.046875
| 2
|
[] |
no_license
|
/**
* Wantai.com Inc.
* Copyright (c) 2004-2012 All Rights Reserved.
*/
package com.wantai.oa.web.controller.common;
import com.wantai.oa.biz.shared.result.Status;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 公共控制器
*
* @author maping.mp
* @version $Id: CommonController.java, v 0.1 2015-1-04 下午10:55:39 maping.mp Exp $
*/
@Controller
public class CommonController {
/**
* 错误异常拦截处理
* @param e 异常
* @return 错误对象
*/
@ExceptionHandler(Exception.class)
@ResponseBody
public Status handleException(Exception e) {
Status status = new Status();
status.setSuccess(false);
status.setErrorCode("Unkown");
status.setErrorMessage(e.getMessage());
return status;
}
}
| true
|
3c74a940635000b2c1274ebc3585ef31c7e7f407
|
Java
|
pancuz/ProblemPractice
|
/LinkedList/CreateAndOperate/CreateList.java
|
UTF-8
| 2,588
| 3.75
| 4
|
[] |
no_license
|
public class CreateList {
public class Node{
int data;
Node next;
public Node(int val){
this.data = val;
this.next=null;
}
}
public Node first=null;
private void insert(){
int [] arr = {2,3,4,5,6,7,8,9};
Node cur=null;
for(int i=0;i<arr.length;i++){
if(cur==null){
cur=new Node(arr[i]);
this.first=cur;
}
else{
Node temp= new Node(arr[i]);
cur.next = temp;
cur=cur.next;
}
}
}
private void reverse(Node first){
if(first == null){
return;
}
Node cur=first;
Node prev =null;
Node temp;
while(cur !=null){
temp=cur.next;
cur.next=prev;
prev=cur;
cur=temp;
}
this.first=prev;
}
private Node rev_rec(Node first){
if(first==null){
return first;
}
if(first.next==null){
return first;
}
Node rest = rev_rec(first.next);
first.next.next=first;
first.next=null;
return rest;
}
private void remove(Node first, int index){
if(first==null){
return;
}
if(index==1){
this.first=first.next;
return;
}
int count=1;
Node cur=first.next;
Node prev=first;
Node temp;
while(cur !=null && count<=index){
count++;
if(count==index){
prev.next=cur.next;
return;
}else{
prev=cur;
cur=cur.next;
}
}
if(cur==null){
System.out.println("Invalid Entry !");
}
}
private void findKthLast(int k){
if(first==null){
return;
}
Node cur=first;
Node prev=first;
Node temp=first;
int count=1;
while(cur!=null && count<=k){
cur=cur.next;
count++;
}
if(cur==null){
System.out.println("Invalid k value !");
return;
}
while(cur!=null){
//temp=prev;
prev=prev.next;
cur=cur.next;
}
System.out.println("kth last: "+ prev.data);
//temp.next=prev.next;
}
private void print(){
//System.out.println("\nContent printing");
Node cur = this.first;
while(cur!=null){
System.out.print(" => "+cur.data);
cur=cur.next;
}
System.out.println();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CreateList ll = new CreateList();
ll.insert();
System.out.println("Original list is: ");
ll.print();
System.out.println("Reversed list is: ");
ll.reverse(ll.first);
ll.print();
System.out.println("After recursize reverse: ");
ll.first = ll.rev_rec(ll.first);
ll.print();
System.out.println("After removing 5th element: ");
ll.remove(ll.first, 5);
ll.print();
System.out.println("Displaying 3rd element from last: ");
ll.findKthLast(3);
System.out.println("Final list is: ");
ll.print();
}
}
| true
|
a07a740a115efb17f3960fef6648fc2b9bd52d79
|
Java
|
yangmingxuan/algorithmicexamples
|
/src/algorithms/array/MaximumAreaofaPieceofCakeAfterHorizontalandVerticalCuts.java
|
UTF-8
| 2,940
| 3.96875
| 4
|
[] |
no_license
|
package algorithms.array;
import java.util.Arrays;
/****
* You are given a rectangular cake of size h x w and two arrays of integers horizontalCuts and verticalCuts where:
horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, and
verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut.
Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a large number, return this modulo 10^9 + 7.
Example 1:
Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]
Output: 4
Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.
Example 2:
Input: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]
Output: 6
Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.
Example 3:
Input: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]
Output: 9
Constraints:
2 <= h, w <= 10^9
1 <= horizontalCuts.length <= min(h - 1, 10^5)
1 <= verticalCuts.length <= min(w - 1, 10^5)
1 <= horizontalCuts[i] < h
1 <= verticalCuts[i] < w
All the elements in horizontalCuts are distinct.
All the elements in verticalCuts are distinct.
* @author miche
*
*/
public class MaximumAreaofaPieceofCakeAfterHorizontalandVerticalCuts {
/***
* Sort the arrays, then compute the maximum difference between two consecutive elements for horizontal cuts and vertical cuts.
* The answer is the product of these maximum values in horizontal cuts and vertical cuts.
* @param h
* @param w
* @param horizontalCuts
* @param verticalCuts
* @return
*/
public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) {
Arrays.sort(horizontalCuts);
Arrays.sort(verticalCuts);
int maxHdistance = horizontalCuts[0];
for(int i = 1; i < horizontalCuts.length; i++) {
maxHdistance = Math.max(maxHdistance, horizontalCuts[i]-horizontalCuts[i-1]);
}
maxHdistance = Math.max(maxHdistance, h-horizontalCuts[horizontalCuts.length-1]);
int maxVdistance = verticalCuts[0];
for(int i = 1; i < verticalCuts.length; i++) {
maxVdistance = Math.max(maxVdistance, verticalCuts[i]-verticalCuts[i-1]);
}
maxVdistance = Math.max(maxVdistance, w-verticalCuts[verticalCuts.length-1]);
return (int)((long)maxHdistance * (long)maxVdistance % 1000000007);
}
}
| true
|
63d43ce9bbebef66af080d7a664726b21b6faab0
|
Java
|
deekscitacija/NCProject
|
/NCBackend/src/main/java/com/ftn/nc/NCBackend/web/controller/GradController.java
|
UTF-8
| 966
| 2.09375
| 2
|
[] |
no_license
|
package com.ftn.nc.NCBackend.web.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.ftn.nc.NCBackend.web.model.Grad;
import com.ftn.nc.NCBackend.web.service.GradService;
@RestController
@RequestMapping(value = "/app/")
public class GradController {
@Autowired
private GradService gradService;
@RequestMapping(value = "getAllCities", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Grad>> findAllCities(){
return new ResponseEntity<List<Grad>>(gradService.getAll(), HttpStatus.OK);
}
}
| true
|
6ad48991b2b32823a3680da302241ac98926c187
|
Java
|
hxz156/Train
|
/J2EE/hibernate-demo/src/test/java/com/mercury/hibernate_demo/Test7.java
|
UTF-8
| 791
| 2.984375
| 3
|
[] |
no_license
|
package com.mercury.hibernate_demo;
import org.hibernate.Session;
import com.mercury.hibernate_demo.bean.Sample;
import com.mercury.hibernate_demo.util.HibernateUtil;
public class Test7 {
public static void main(String[] args) {
// difference status of an object to session
// transient: object is newly created and not associated with
// session yet.
Sample kevin = new Sample("kevin", 21);
Session s1 = HibernateUtil.getSession();
// persistent: object either loaded in session from DB or added to
// session which will be saved in DB later.
s1.save(kevin);
// detached: object will be detached automatically after session
// is closed.
s1.close();
// how to manually detach object from session?
s1.evict(kevin);
// or:
s1.clear();
}
}
| true
|
2c5fe19390ddfbbf3e48a1652a433011bdb72579
|
Java
|
TrungJimmy/quanlytaichinh
|
/app/src/main/java/com/example/trungqltc/KhoanChi/khoanchi.java
|
UTF-8
| 16,322
| 1.757813
| 2
|
[] |
no_license
|
package com.example.trungqltc.KhoanChi;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import com.example.trungqltc.NumberTextWatcher;
import com.example.trungqltc.R;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import at.markushi.ui.CircleButton;
public class khoanchi extends Fragment {
CircleButton btnaddkhoanchi;
private DB_Khoanchi db_khoanchi;
ListView rvKhoanchi;
List<Item_Khoan_Chi> list_khoanchi;
AdapterKhoanChi adapterKhoanChi;
private static String prefix = "VND ";
private static final int MAX_DECIMAL = 3;
public AlertDialog alertDialog;
public static khoanchi newInstance() {
Bundle args = new Bundle();
khoanchi fragment = new khoanchi();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_khoanchi, container, false);
btnaddkhoanchi = view.findViewById(R.id.btnaddKhoanchi);
rvKhoanchi = view.findViewById(R.id.rvKhoanchi);
db_khoanchi = new DB_Khoanchi(getContext());
list_khoanchi = db_khoanchi.getAllKhoanchi();
setAdapter();
btnaddkhoanchi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
final View alert = LayoutInflater.from(getContext()).inflate(R.layout.add_khoan_chi, null);
builder.setView(alert);
final EditText edittextDanhmuc_2, edittextSotien_2, edittextNgay_2, edittextGhichu_2;
final Button buttonHuy_2, buttonLuu_2;
final ImageButton btnMenuAddKhoanChi, btnMenuSuaKhoanChi;
Log.d("log", "onStart: ");
edittextDanhmuc_2 = alert.findViewById(R.id.edittextDanhmuc_2);
edittextSotien_2 = alert.findViewById(R.id.edittextSotien_2);
edittextNgay_2 = alert.findViewById(R.id.edittextNgay_2);
edittextGhichu_2 = alert.findViewById(R.id.edittextGhichu_2);
btnMenuAddKhoanChi = alert.findViewById(R.id.btnMenuAddKhoanChi);
buttonHuy_2 = alert.findViewById(R.id.buttonHuy_2);
buttonLuu_2 = alert.findViewById(R.id.buttonLuu_2);
final DB_Khoanchi db_khoanchi = new DB_Khoanchi(getContext());
//Chọn ngày
btnMenuAddKhoanChi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(getContext());
View mView = getLayoutInflater().inflate(R.layout.dialog_spinner, null);
final Spinner mSpinner = mView.findViewById(R.id.menuSpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item,
getResources().getStringArray(R.array.Spend));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
mBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
if(!mSpinner.getSelectedItem().toString().equalsIgnoreCase("Chọn mục thu")){
Toast.makeText(getContext(),mSpinner.getSelectedItem().toString(),Toast.LENGTH_SHORT).show();
edittextDanhmuc_2.setText(mSpinner.getSelectedItem().toString());
dialog.dismiss();
}
}
});
mBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
dialog.dismiss();
}
});
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
}
});
edittextNgay_2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view_2) {
ChonNgay();
}
private void ChonNgay() {
final Calendar calendar = Calendar.getInstance();
int ngay = calendar.get(Calendar.DATE);
int thang = calendar.get(Calendar.MONTH);
int nam = calendar.get(Calendar.YEAR);
DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
// i:năm, i1:tháng, i2:ngày
calendar.set(i, i1, i2);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
edittextNgay_2.setText(simpleDateFormat.format(calendar.getTime()));
}
}, nam, thang, ngay);
datePickerDialog.show();
}
});
//Hủy
buttonHuy_2.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
alertDialog.cancel();
Toast.makeText(getContext(), "Hủy", Toast.LENGTH_LONG).show();
}
});
//Lưu
buttonLuu_2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String danhmuc_2 = edittextDanhmuc_2.getText().toString();
Log.d("log", edittextSotien_2.getText().toString());
Integer sotien_2 = Integer.valueOf(edittextSotien_2.getText().toString());
String ngay_2 = edittextNgay_2.getText().toString();
String ghichu_2 = edittextGhichu_2.getText().toString();
Item_Khoan_Chi item_khoan_chi = new Item_Khoan_Chi(danhmuc_2,sotien_2 , ngay_2, ghichu_2);
db_khoanchi.addKhoanchi(item_khoan_chi);
updateListKhoanchi();
setAdapter();
alertDialog.cancel();
}
});
builder.create();
alertDialog = builder.show();
}
});
rvKhoanchi.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, final int position, long l) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
final View alert = LayoutInflater.from(getContext()).inflate(R.layout.suakhoanchi, null);
builder.setView(alert);
final EditText edittextDanhmuc_22, editSotien_22, editSuangay_22, editGhichu_22;
final Button editXoa_22, editUpdate_22, editResert_22, btncancel_22;
final ImageButton btnMenuSuaKhoanChi;
edittextDanhmuc_22 = alert.findViewById(R.id.editDanhmuc_22);
editSotien_22 = alert.findViewById(R.id.editSotien_22);
editSuangay_22 = alert.findViewById(R.id.editSuangay_22);
editGhichu_22 = alert.findViewById(R.id.editGhichu_22);
btnMenuSuaKhoanChi = alert.findViewById(R.id.btnMenuSuaKhoanChi);
editXoa_22 = alert.findViewById(R.id.editXoa_22);
editUpdate_22 = alert.findViewById(R.id.editUpdate_22);
editResert_22 = alert.findViewById(R.id.editResert_22);
btncancel_22 = alert.findViewById(R.id.btncancel_22);
final Item_Khoan_Chi item_khoan_chi = list_khoanchi.get(position);
edittextDanhmuc_22.setText(item_khoan_chi.getDanhmuc_2());
editSotien_22.setText(String.valueOf(item_khoan_chi.getTien_2()));
editSuangay_22.setText(item_khoan_chi.getNgay_2());
editGhichu_22.setText(item_khoan_chi.getGhichu_2());
btnMenuSuaKhoanChi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(getContext());
View mView = getLayoutInflater().inflate(R.layout.dialog_spinner, null);
final Spinner mSpinner = mView.findViewById(R.id.menuSpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item,
getResources().getStringArray(R.array.Spend));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
mBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
if(!mSpinner.getSelectedItem().toString().equalsIgnoreCase("Chọn mục thu")){
Toast.makeText(getContext(),mSpinner.getSelectedItem().toString(),Toast.LENGTH_SHORT).show();
edittextDanhmuc_22.setText(mSpinner.getSelectedItem().toString());
dialog.dismiss();
}
}
});
mBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
dialog.dismiss();
}
});
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
}
});
//sửa ngày
editSuangay_22.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view_2) {
ChonNgay();
}
private void ChonNgay() {
final Calendar calendar = Calendar.getInstance();
int ngay = calendar.get(Calendar.DATE);
int thang = calendar.get(Calendar.MONTH);
int nam = calendar.get(Calendar.YEAR);
DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
// i:năm, i1:tháng, i2:ngày
calendar.set(i, i1, i2);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
editSuangay_22.setText(simpleDateFormat.format(calendar.getTime()));
}
}, nam, thang, ngay);
datePickerDialog.show();
}
});
editUpdate_22.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
item_khoan_chi.setDanhmuc_2(edittextDanhmuc_22.getText().toString());
item_khoan_chi.setTien_2(Float.parseFloat(editSotien_22.getText().toString()));
item_khoan_chi.setNgay_2(editSuangay_22.getText().toString());
item_khoan_chi.setGhichu_2(editGhichu_22.getText().toString());
db_khoanchi.updateKhoanchi(item_khoan_chi);
int result = db_khoanchi.updateKhoanchi(item_khoan_chi);
if (result > 0) {
updateListKhoanchi();
}
Toast.makeText(getContext(), "update successfuly", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
editResert_22.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
editGhichu_22.setText("");
editSotien_22.setText(null);
editSuangay_22.setText("");
edittextDanhmuc_22.setText("");
}
});
editXoa_22.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Item_Khoan_Chi muc = list_khoanchi.get(position);
int result = db_khoanchi.deleteKhoanchi(muc.getId_2());
if (result > 0) {
Toast.makeText(getContext(), "Delete successfuly", Toast.LENGTH_SHORT).show();
updateListKhoanchi();
} else {
Toast.makeText(getContext(), "Delete fail", Toast.LENGTH_SHORT).show();
}
alertDialog.dismiss();
}
});
btncancel_22.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getContext(), "Cancel", Toast.LENGTH_SHORT).show();
alertDialog.dismiss();
}
});
builder.create();
alertDialog = builder.show();
}
});
return view;
}
public void updateListKhoanchi() {
list_khoanchi.clear();
list_khoanchi.addAll(db_khoanchi.getAllKhoanchi());
if (adapterKhoanChi != null) {
adapterKhoanChi.notifyDataSetChanged();
}
}
private void setAdapter() {
if (adapterKhoanChi == null) {
adapterKhoanChi = new AdapterKhoanChi(getContext(), R.layout.item_khoan_chi, list_khoanchi);
rvKhoanchi.setAdapter(adapterKhoanChi);
} else {
adapterKhoanChi.notifyDataSetChanged();
rvKhoanchi.setSelection(adapterKhoanChi.getCount() - 1);
}
}
}
| true
|
4b58034e9455300d6f2bb1060c044b9bb933289d
|
Java
|
zarek-zhao/crm_gra
|
/src/main/java/com/zarek/crm/filter/ResourcesFilter.java
|
UTF-8
| 1,745
| 2.390625
| 2
|
[] |
no_license
|
package com.zarek.crm.filter; /**
* @author zarek
* @version 1.0.0
* @since 1.0.0
*/
import com.zarek.crm.pojo.domain.User;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 资源限定访问:只有登录过的用户才能访问系统的服务
*/
public class ResourcesFilter implements Filter {
@Override
public void init(FilterConfig config) throws ServletException
{
}
@Override
public void destroy()
{
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException
{
long start = System.currentTimeMillis();
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
String servletPath = httpServletRequest.getServletPath();
System.out.println("servletPath = " + servletPath);
if("/login.html".equals(servletPath) || "/settings/user/login.do".equals(servletPath)|| "/login".equals(servletPath) || "/".equals(servletPath)) {
filterChain.doFilter(httpServletRequest,httpServletResponse);
}else{
User user = (User) httpServletRequest.getSession().getAttribute("user");
if(user!=null){
filterChain.doFilter(httpServletRequest,httpServletResponse);
}else{
httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login");
}
}
System.out.println("Execute cost="+(System.currentTimeMillis()-start));
}
}
| true
|
54568e0459d1f406dcae107f64f898e08568ed7e
|
Java
|
Shaojia/ZHCarPocket
|
/MaintainService/src/com/coortouch/maintainservice/activity/Bnuz_GuideDetail2Activity.java
|
GB18030
| 4,337
| 2
| 2
|
[
"MIT"
] |
permissive
|
package com.coortouch.maintainservice.activity;
import com.coortouch.app.entity.BnuzTGuide;
import com.coortouch.app.wcf.BnuzGuideService;
import com.coortouch.app.wcf.listener.GetOneRecordListener;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
public class Bnuz_GuideDetail2Activity extends BaseActivity implements OnClickListener {
private WebView txtContent;
private TextView txtTitle;
private TextView txtTel;
private TextView txtAddress;
private Button btnBack;
private BnuzTGuide entity;
String html="<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><meta name = \"viewport\" content = \"initial-scale = 1.0,user-scalable = no, width = 249\"/><style>@media screen and (max-device-width: 320px){body{-webkit-text-size-adjust:auto;font-family:Helvetica, Arial, Verdana, sans-serif;} div{clear:both!important;display:block!important;width:100%%!important;float:none!important;margin:0!important;padding:0!important;} img{width:100%% !important;height:auto;} table{width:100%% !important;height:auto;}}</style></head><body style=\"margin-top:0px;margin-left:0px;\"><div> %s </div></body></html>";
String contentText="";
BnuzGuideService wcfService;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.bnuz_guide_detail2);
Intent intent = getIntent();
entity = (BnuzTGuide) intent.getExtras().get("Guide");
initView();
setData();
}
private void initView() {
txtContent = (WebView) findViewById(R.id.txtNewsDetContent);
txtContent.setBackgroundColor(0);
txtTitle = (TextView) findViewById(R.id.txtTitle);
txtTel=(TextView) findViewById(R.id.txtTel);
txtAddress=(TextView) findViewById(R.id.txtAddress);
btnBack = (Button) findViewById(R.id.btnBack);
txtTel.setOnClickListener(this);
btnBack.setOnClickListener(this);
findViewById(R.id.imgTel).setOnClickListener(this);
wcfService=new BnuzGuideService(this);
}
private void setData() {
if (entity != null) {
txtTitle.setText(entity.getTitle());
txtTel.setText(entity.getPhone());
wcfService.getGuideID(entity.getPid(), entity.getId(), new GetOneRecordListener<BnuzTGuide>() {
@Override
public void onFinish(BnuzTGuide data) {
// TODO Auto-generated method stub
String content=data.getContent();
// if (content.contains("/jscms/")) {
// content=content.replace("/jscms/", Constant.BaseUrl);
// }
txtContent.loadDataWithBaseURL("",String.format(html,content), "text/html", "utf-8","");
txtAddress.setText(data.getAddress());
}
@Override
public void onFailed(String Message) {
// TODO Auto-generated method stub
}
});
}
}
private void makeTel() {
if (entity.getPhone()!=null&&entity.getPhone().length()>0) {
Dialog dialog = new AlertDialog.Builder(this)
.setTitle("Ƿõ绰")
.setMessage(entity.getPhone())
.setPositiveButton("",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
String tel=entity.getPhone().trim();
if (entity.getPhone().contains("-")) {
tel=entity.getPhone().trim().replaceAll("-", "");
}
Intent intent = new Intent(
Intent.ACTION_CALL,
Uri.parse("tel:" + tel));
startActivity(intent);
}
})
.setNegativeButton("",
null).create();
dialog.show();
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnBack:
finish();
break;
case R.id.txtTel:
makeTel();
break;
case R.id.imgTel:
makeTel();
break;
default:
break;
}
}
}
| true
|
003aa75188aad63ed44dc827fa7b117b33624118
|
Java
|
Imperative2/AdventOfCode
|
/src/Day7.java
|
WINDOWS-1250
| 6,356
| 3.109375
| 3
|
[] |
no_license
|
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
public class Day7
{
private static HashSet<Character> symbolsSet = new HashSet<>();
private static HashMap<Character, MyCharacter> symbolsMap = new HashMap<>();
private static ArrayList<String> messesages = new ArrayList<>();
private static Elf[] elfs = new Elf[5];
public static void main(String[] args)
{
loadData();
for (Character symbol : symbolsSet)
{
MyCharacter myChar = new MyCharacter(symbol);
symbolsMap.put(symbol, myChar);
}
for (String line : messesages)
{
line = line.replaceAll("\\w{2,}|\\s|\\.", " ");
line = line.replaceAll("\\s{1,}", " ");
line = line.trim();
// System.out.println(line);
String[] letters = line.split(" ");
symbolsMap.get(letters[1].charAt(0)).addPredecesor(letters[0].charAt(0));
}
System.out.println(symbolsSet.toString());
orderSteps();
makeElfWork();
}
private static void makeElfWork()
{
for (int i = 0; i < elfs.length; i++)
{
elfs[i] = new Elf();
}
HashSet<Character> copySymbolsSet = (HashSet<Character>) symbolsSet.clone();
HashMap<Character, MyCharacter> copySymbolsMap = (HashMap<Character, MyCharacter>) symbolsMap.clone();
long time = 0;
ArrayList<Character> charsWorkedAt = new ArrayList<>();
while (copySymbolsSet.size() > 0)
{
ArrayList<Character> possibleNext = new ArrayList<>();
for (Character symbol : copySymbolsSet)
{
MyCharacter myChar = copySymbolsMap.get(symbol);
if (myChar.isViable(copySymbolsSet))
{
possibleNext.add(symbol);
}
}
if (possibleNext.size() <= 0)
{
System.out.println("ERROR");
}
Character[] sortedChars = possibleNext.stream().sorted().toArray(Character[]::new);
for (int i = 0; i < elfs.length; i++)
{
Elf elf = elfs[i];
if (elf.isWorking() == false)
{
Iterator<Character> iterator = new ArrayList<Character>(Arrays.asList(sortedChars)).iterator();
while (iterator.hasNext())
{
Character charToWorkOn = iterator.next();
if (charsWorkedAt.contains(charToWorkOn) == false)
{
elf.newWork(copySymbolsMap.get(charToWorkOn));
charsWorkedAt.add(charToWorkOn);
break;
}
}
}
}
System.out.print("\n" + time + ": ");
for (Elf elf : elfs)
{
if (elf.isWorking())
{
System.out.print(elf.getWork().getSymbol());
} else
System.out.print(".");
}
for (Elf elf : elfs)
{
elf.work();
}
time++;
for (Elf elf : elfs)
{
if (elf.isFinished() == true)
{
MyCharacter work = elf.getWork();
// elf.clearWork();
copySymbolsSet.remove(work.getSymbol());
copySymbolsMap.remove(work.getSymbol());
}
}
}
System.out.println("\nWork time for 5 elfs: " + time);
}
private static void orderSteps()
{
HashSet<Character> copySymbolsSet = (HashSet<Character>) symbolsSet.clone();
HashMap<Character, MyCharacter> copySymbolsMap = (HashMap<Character, MyCharacter>) symbolsMap.clone();
String result = "";
while (copySymbolsSet.size() > 0)
{
ArrayList<Character> possibleNext = new ArrayList<>();
for (Character symbol : copySymbolsSet)
{
MyCharacter myChar = copySymbolsMap.get(symbol);
if (myChar.isViable(copySymbolsSet))
{
possibleNext.add(symbol);
}
}
if (possibleNext.size() <= 0)
{
System.out.println("ERROR");
}
Character[] sortedChars = possibleNext.stream().sorted().toArray(Character[]::new);
result += sortedChars[0];
copySymbolsSet.remove(sortedChars[0]);
copySymbolsMap.remove(sortedChars[0]);
}
System.out.println(result);
}
private static void loadData()
{
Scanner sc = new Scanner(System.in);
System.out.println(System.getProperty("user.dir"));
System.out.print("podaj nazw pliku: ");
String fileName;
System.out.println();
fileName = sc.next();
fileName = System.getProperty("user.dir") + "\\" + fileName + ".txt";
File file = new File(fileName);
System.out.println(file.getPath());
System.out.println("file exist: " + file.exists());
Scanner fileScanner;
try
{
fileScanner = new Scanner(file);
while (fileScanner.hasNext())
{
String line = fileScanner.nextLine();
messesages.add(line);
line = line.replaceAll("\\w{2,}|\\s|\\.", " ");
line = line.replaceAll("\\s{1,}", " ");
line = line.trim();
// System.out.println(line);
String[] letters = line.split(" ");
symbolsSet.add(letters[0].charAt(0));
symbolsSet.add(letters[1].charAt(0));
}
fileScanner.close();
} catch (FileNotFoundException e)
{
System.out.println("Error in reading from a file");
return;
}
}
static class Elf
{
private boolean isWorkingFlag = false;
private MyCharacter work;
private int workTime;
private boolean wasWorkingFlag = false;
private boolean isFinishedFlag = false;
public Elf()
{
}
public void newWork(MyCharacter myChar)
{
isWorkingFlag = true;
wasWorkingFlag = true;
isFinishedFlag = false;
workTime = myChar.getSymbolWeight();
work = myChar;
}
public void work()
{
workTime--;
if (workTime == 0 && wasWorkingFlag == true)
{
wasWorkingFlag = false;
isFinishedFlag = true;
isWorkingFlag = false;
}
}
public boolean isWorking()
{
return isWorkingFlag;
}
public boolean isFinished()
{
return isFinishedFlag;
}
public MyCharacter getWork()
{
return work;
}
}
static class MyCharacter
{
private Character symbol;
private ArrayList<Character> predecesors = new ArrayList<>();
private int symbolWeight;
public MyCharacter(char symbol)
{
this.symbol = symbol;
symbolWeight = symbol - 4;
System.out.println(symbol + " Symbol weight: " + symbolWeight);
}
public void addPredecesor(Character otherSymbol)
{
predecesors.add(otherSymbol);
}
public boolean isViable(HashSet<Character> symbols)
{
for (Character predecesor : predecesors)
{
if (symbols.contains(predecesor))
return false;
}
return true;
}
public int getSymbolWeight()
{
return symbolWeight;
}
public Character getSymbol()
{
return symbol;
}
}
}
| true
|
55e7b663a0817c8550d7e658f6bcf624ac836c25
|
Java
|
blizz2night/TestNDK
|
/app/src/main/java/com/github/blizz2inght/testmake/MainActivity.java
|
UTF-8
| 1,111
| 2.953125
| 3
|
[] |
no_license
|
package com.github.blizz2inght.testmake;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Example of a call to a native method
TextView tv = findViewById(R.id.sample_text);
tv.setText(stringFromJNI());
Log.i(TAG, "onCreate: ");
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = addAll(arr);
Log.i(TAG, "onCreate: "+sum);
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
public native int addAll(int[] arr);
}
| true
|
3b1ce25f46a0f462123f37ab3ec6b33a9872b405
|
Java
|
boymask2000/Asset2
|
/Asset2/src/restservice/InterventoRest.java
|
UTF-8
| 4,505
| 2.09375
| 2
|
[] |
no_license
|
package restservice;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import beans.AssetAlca;
import beans.ChecklistIntervento;
import beans.FamigliaAsset;
import beans.Intervento;
import beans.Safety;
import common.IspezioniManager;
import database.dao.AssetAlcaDAO;
import database.dao.AuditDAO;
import database.dao.ChecklistInterventiDAO;
import database.dao.FamigliaAssetDAO;
import database.dao.InterventiDAO;
import database.dao.SafetyDAO;
import restservice.beans.InterventoRestBean;
import restservice.beans.Messaggio;
import restservice.beans.MsgType;
@Path("/intervento")
public class InterventoRest {
@GET
@Path("/getpreviousassets/{date}")
public List<AssetAlca> getPreviousInteAssets(@PathParam("date") String date) {
InterventiDAO dao = new InterventiDAO();
// DEMO inizio
List<AssetAlca> ll = dao.getPreviousInteAssets(date);
ll = filterForDemo(ll);
// DEMO fine
// return dao.getPreviousInteAssets(date);
return ll;
}
private List<AssetAlca> filterForDemo(List<AssetAlca> ll) {
List<AssetAlca> out = new ArrayList<AssetAlca>();
for (AssetAlca as : ll) {
if (as.getFacSystem().toUpperCase().indexOf("D20 PLUMBING") != -1)
out.add(as);
}
return out;
}
@GET
@Path("/getprevious/{date}")
public Integer getPreviousInte(@PathParam("date") String date) {
InterventiDAO dao = new InterventiDAO();
return dao.getPreviousInte(date);
}
@GET
@Path("{interventoId}")
public Intervento getIntervento(@PathParam("interventoId") String interventoId) {
InterventiDAO dao = new InterventiDAO();
long id = Long.parseLong(interventoId);
return dao.getInterventoById(id);
}
@GET
@Path("/getnext/{rfid}")
public Intervento getNextIntervento(@PathParam("rfid") String rfid) {
AssetAlcaDAO asdao = new AssetAlcaDAO();
AssetAlca ass = asdao.searchByRPIE(rfid);
if (ass == null)
return null;
InterventiDAO dao = new InterventiDAO();
List<Intervento> lista = dao.getInterventiForAsset(ass.getId(), false);
if (lista == null || lista.size() == 0)
return null;
return lista.get(0);
}
@GET
@Path("/getsafety/{rfid}")
public List<Safety> getSafety(@PathParam("rfid") String family) {
FamigliaAssetDAO fad = new FamigliaAssetDAO();
FamigliaAsset fam = fad.searchByName(family);
SafetyDAO asdao = new SafetyDAO();
List<Safety> safety = asdao.selectByFamily(fam.getId());
if (safety == null)
safety = asdao.selectByFamily(0);
return safety;
}
@POST
@Path("/updateIntervento")
@Consumes(MediaType.APPLICATION_JSON)
public Response update(InterventoRestBean inter) {
InterventiDAO dao = new InterventiDAO();
dao.update(inter);
IspezioniManager.decideIspezione(inter);
sendMessaggioInte(inter);
return RestUtil.buildOKResponse();
}
private static void sendMessaggioInte(InterventoRestBean inter) {
AssetAlca ass = new AssetAlca();
ass.setId(inter.getAssetId());
AssetAlcaDAO assDao = new AssetAlcaDAO();
AssetAlca asset = assDao.searchById(ass);
Messaggio msg = new Messaggio();
msg.setMsgType(MsgType.INFO);
msg.setUsername(inter.getUser());
msg.setText("Completato intervento su asset " + asset.getRpieIdIndividual());
msg.setMsgCode("INTERVENTO_COMPLETATO");
msg.addParameter(asset.getRpieIdIndividual());
AuditDAO.sendMessaggio(msg);
}
@POST
@Path("/cancelOnSafety")
@Consumes(MediaType.APPLICATION_JSON)
public Response cancelOnSafety(Messaggio msg) {
AuditDAO.sendMessaggioRest(msg);
return RestUtil.buildOKResponse();
}
@POST
@Path("/creaIntervento")
public Response crea(InterventoRestBean inter) {
Intervento u = new Intervento();
u.setId(inter.getId());
ChecklistInterventiDAO ckDao = new ChecklistInterventiDAO();
List<ChecklistIntervento> ll = ckDao.getCheckListForIntervento(u);
InterventiDAO iDao = new InterventiDAO();
u.setData_pianificata(inter.getData_pianificata());
u.setData_effettiva(null);
u.setData_teorica(null);
u.setAssetId(inter.getAssetId());
iDao.insert(u);
for (ChecklistIntervento cli : ll) {
cli.setInterventoId(u.getId());
ckDao.insert(cli);
}
// Intervento intervento = (Intervento) inter;
// intervento.setData_effettiva(TimeUtil.getCurrentDate());
// InterventiDAO dao = new InterventiDAO();
// dao.update(intervento);
return RestUtil.buildOKResponse();
}
}
| true
|
e26b13465411da6e04947d5abf95be2d6d6be136
|
Java
|
Provinite/pillowing-bank
|
/src/main/java/com/clovercoin/pillowing/service/ConstantService.java
|
UTF-8
| 279
| 1.867188
| 2
|
[] |
no_license
|
package com.clovercoin.pillowing.service;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
public interface ConstantService {
Object get(String key);
String getString(String key);
Map<String, Object> getAllWithPrefix(String prefix);
}
| true
|
cc8c48039adc57f08ca50980bfa7cdeaaeb005c1
|
Java
|
Karpikova/artifactTaxi
|
/src/main/dao/DriverImplementation.java
|
UTF-8
| 2,420
| 2.65625
| 3
|
[] |
no_license
|
package main.dao;
import main.DB.ConnectionToDB;
import main.Exception.TaxiException;
import main.pojo.Driver;
import main.pojo.User;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.concurrent.ExecutionException;
/*
* Implemntation of UserInterface for postgressql DB
*/
@Repository
public class DriverImplementation implements DriverInterface {
public void create(Driver driver) throws TaxiException, InterruptedException, ExecutionException, SQLException {
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
String qText = "INSERT INTO public.\"Driver\"" +
"(users_pkey_driver, full_name, car_number, car_description, passport, birth)" +
" VALUES (" +
Long.valueOf(driver.getUsersPkey().getUsersPkey()) +", " +
"'" + driver.getFullName() + "' , " +
"'" + driver.getCarNumber() + "' , " +
"'" + driver.getCarDescription() + "' , " +
"'" + driver.getPassport() + "' , " +
"'" + format.format(driver.getBirth()) +"')";
ConnectionToDB.execute(qText);
}
public Driver read(int users_pkey_driver) {
return null;
}
public Driver read(String login) throws TaxiException, SQLException, ExecutionException, InterruptedException {
Driver driver = null;
ConnectionToDB connectionToDB = new ConnectionToDB();
Connection connection = connectionToDB.toConnect();
Statement st = connection.createStatement();
String qtext = "SELECT * FROM PUBLIC.\"Driver\" Dr LEFT JOIN PUBLIC.\"users\" Us\n" +
"ON Us.users_pkey = Dr.users_pkey_driver\n" +
"WHERE Us.login = '" + login + "' LIMIT 1";
ResultSet resultSet = st.executeQuery(qtext);
if (resultSet.next()) {
driver = new Driver();
User user = new User(resultSet.getLong("users_pkey_driver"), login);
driver.setUsersPkey(user);
driver.setFullName(resultSet.getString("full_name"));
}
return driver;
}
public void update(Driver driver) {
}
public void delete(Driver driver) {
}
public void getAll() {
}
}
| true
|
81c748f3d7789406f8dd71846dbf83292b047c8c
|
Java
|
returncode13/Boxes-using-JavafxDrawers
|
/src/main/java/db/dao/SummaryDAO.java
|
UTF-8
| 1,359
| 2.15625
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package db.dao;
import db.model.Job;
import db.model.Sequence;
import db.model.Subsurface;
import db.model.Summary;
import db.model.Workspace;
import java.util.List;
/**
*
* @author sharath nair <sharath.nair@polarcus.com>
*/
public interface SummaryDAO {
public void createSummary(Summary summary);
public Summary getSummary(Long id);
public void deleteSummary(Long id);
public void updateSummary(Long id,Summary newSummary);
public Summary getSummaryFor(Sequence sequence,Job job);
public Summary getSummaryFor(Subsurface subsurface,Job job);
public List<Long> getDepthsInSummary(Workspace W);
public List<Summary> getSummariesForJobSeq(Job job,Sequence seq,Workspace W);
public List<Summary> getSummariesForJobSeq(Job job,Sequence seq);
public List<Summary> getSummariesForJobSub(Job job,Subsurface sub,Workspace W);
public List<Summary> getSummariesFor(Workspace W);
public void createBulkSummaries(List<Summary> summaries);
public void udpateBulkSummaries(List<Summary> summariesToBeUpdated);
public void deleteAllSummaries(Workspace dbWorkspace);
public void deleteAllSummariesForJob(Job job);
public List<Summary> getSummariesFor(Subsurface sub);
}
| true
|
e6a0429eba105f9c28e7fe118a7f1dc1a6f4488c
|
Java
|
vgarousi/MBTofCOVIDapps
|
/src/test/java/qub/vg05/systemui/nhsmodels/SelectSymptomsModel.java
|
UTF-8
| 7,492
| 1.976563
| 2
|
[] |
no_license
|
package qub.vg05.systemui.nhsmodels;
import nhs.HomePage;
import nhs.Navigation;
import nhs.symptoms.SelectSymptomsPage;
import org.graphwalker.java.annotation.AfterElement;
import org.graphwalker.java.annotation.BeforeElement;
import org.graphwalker.java.annotation.GraphWalker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import qub.vg05.systemui.AndroidBaseTestClass;
import qub.vg05.systemui.utils.CoverageValue;
import qub.vg05.systemui.utils.ExcelMapData;
import qub.vg05.utilities.AndroidCommonMethods;
import qub.vg05.utilities.UIActionHelper;
@GraphWalker(value = CoverageValue.WeightedRandomEdgeCoverage60, groups= "nhs")
public class SelectSymptomsModel extends AndroidBaseTestClass implements qub.vg05.nhs.NHS_Select_Symptoms {
private static final Logger logger = LoggerFactory.getLogger(SelectSymptomsModel.class);
ExcelMapData excelMapData = new ExcelMapData();
@BeforeElement
public void beforeElement() {
logger.info("══════════════════════════════════════════════════════════════════════════════════════════════════════");
excelMapData.setBeforeElementData(getModel(), getCurrentElement());
}
@AfterElement
public void afterElement() {
logger.info("══════════════════════════════════════════════════════════════════════════════════════════════════════");
}
@Override
public void v_Verify_In_Select_Symptoms_Page_SHARED() {
SelectSymptomsPage selectSymptomsPage = new SelectSymptomsPage(driver);
selectSymptomsPage.checkInSelectSymptomsPage();
}
@Override
public void e_Click_I_Dont_Have_Symptoms() {
UIActionHelper uiActionHelper = new UIActionHelper(driver);
SelectSymptomsPage selectSymptomsPage = new SelectSymptomsPage(driver);
uiActionHelper.navigateToBottomOfPage();
selectSymptomsPage.clickIDontHaveSymptoms();
}
@Override
public void e_Click_Cancel() {
AndroidCommonMethods androidCommonMethods = new AndroidCommonMethods(driver);
androidCommonMethods.clickCancel();
}
@Override
public void v_Verify_In_Confirm_No_Symptoms_Message() {
SelectSymptomsPage selectSymptomsPage = new SelectSymptomsPage(driver);
selectSymptomsPage.checkForNoSymptomsMessage();
}
@Override
public void v_Verify_In_Unlikely_To_Have_covid_Page() {
SelectSymptomsPage selectSymptomsPage = new SelectSymptomsPage(driver);
selectSymptomsPage.checkInUnlikelyToHaveCovidPage();
}
@Override
public void v_In_Home_Page_SHARED() {
HomePage homePage = new HomePage(driver);
homePage.checkInHomePage();
}
@Override
public void e_Click_Close_Chrome() {
Navigation navigation = new Navigation(driver);
navigation.clickCloseWebButton();
}
@Override
public void e_Click_Back_To_Home() {
SelectSymptomsPage selectSymptomsPage = new SelectSymptomsPage(driver);
selectSymptomsPage.clickBackToHome();
}
@Override
public void v_Verify_In_Review_Symptoms_Page_SHARED() {
}
@Override
public void e_Click_NHS_111_Online() {
SelectSymptomsPage selectSymptomsPage = new SelectSymptomsPage(driver);
selectSymptomsPage.clickNHS11onlineLink();
}
@Override
public void v_Verify_Chrome_Web_View() {
Navigation navigation = new Navigation(driver);
navigation.checkInChromeWebBrowser();
}
@Override
public void e_Click_Confirm() {
AndroidCommonMethods androidCommonMethods = new AndroidCommonMethods(driver);
androidCommonMethods.clickConfirm();
}
@Override
public void e_Select_Fever_Box() {
UIActionHelper uiActionHelper = new UIActionHelper(driver);
uiActionHelper.scrollToFindElementText("A high temperature (fever)");
SelectSymptomsPage selectSymptomsPage = new SelectSymptomsPage(driver);
selectSymptomsPage.clickFeverCheckBox();
}
@Override
public void e_Click_Continue() {
UIActionHelper uiActionHelper = new UIActionHelper(driver);
uiActionHelper.navigateToBottomOfPage();
SelectSymptomsPage selectSymptomsPage = new SelectSymptomsPage(driver);
selectSymptomsPage.clickContinue();
}
@Override
public void e_No_Action() {
// no action
}
@Override
public void v_Check_Box_Unselected() {
SelectSymptomsPage selectSymptomsPage = new SelectSymptomsPage(driver);
selectSymptomsPage.checkInSelectSymptomsPage();
UIActionHelper uiActionHelper = new UIActionHelper(driver);
uiActionHelper.navigateToTopOfPage();
}
@Override
public void e_Unselect_Fever_Box() {
UIActionHelper uiActionHelper = new UIActionHelper(driver);
uiActionHelper.scrollToFindElementText("A high temperature (fever)");
SelectSymptomsPage selectSymptomsPage = new SelectSymptomsPage(driver);
selectSymptomsPage.clickFeverCheckBox();
}
@Override
public void v_Check_Box_Selected() {
SelectSymptomsPage selectSymptomsPage = new SelectSymptomsPage(driver);
selectSymptomsPage.checkInSelectSymptomsPage();
UIActionHelper uiActionHelper = new UIActionHelper(driver);
uiActionHelper.navigateToTopOfPage();
}
@Override
public void e_Select_Change_Taste() {
UIActionHelper uiActionHelper = new UIActionHelper(driver);
uiActionHelper.scrollToFindElementText("A change to your sense of smell or taste");
SelectSymptomsPage selectSymptomsPage = new SelectSymptomsPage(driver);
selectSymptomsPage.clickTasteCheckbox();
}
@Override
public void e_Select_Cough_Box() {
UIActionHelper uiActionHelper = new UIActionHelper(driver);
uiActionHelper.scrollToFindElementText("A new continuous cough");
SelectSymptomsPage selectSymptomsPage = new SelectSymptomsPage(driver);
selectSymptomsPage.clickCoughCheckBox();
}
@Override
public void e_Unselect_Cough_Box() {
UIActionHelper uiActionHelper = new UIActionHelper(driver);
uiActionHelper.scrollToFindElementText("A new continuous cough");
SelectSymptomsPage selectSymptomsPage = new SelectSymptomsPage(driver);
selectSymptomsPage.clickCoughCheckBox();
}
@Override
public void e_Unselect_Change_Taste() {
UIActionHelper uiActionHelper = new UIActionHelper(driver);
uiActionHelper.scrollToFindElementText("A change to your sense of smell or taste");
SelectSymptomsPage selectSymptomsPage = new SelectSymptomsPage(driver);
selectSymptomsPage.clickTasteCheckbox();
}
@Override
public void v_Verify_Error_Please_Select_An_Option_Message() {
SelectSymptomsPage selectSymptomsPage = new SelectSymptomsPage(driver);
selectSymptomsPage.checkErrorMessageNoOptionsSelected();
}
@Override
public void e_Click_Close() {
Navigation navigation = new Navigation(driver);
navigation.clickCloseX();
}
}
| true
|
2dcf986478e4cc422c0b25a1f0106da0d911b230
|
Java
|
Sincerityzz/SinceUtils
|
/app/src/main/java/com/sincerity/sinceutils/fragment/FoundPage.java
|
UTF-8
| 10,493
| 1.976563
| 2
|
[] |
no_license
|
package com.sincerity.sinceutils.fragment;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import com.sincerity.sinceutils.R;
import com.sincerity.sinceutils.image.BaseImageLoader;
import com.sincerity.utilslibrary.view.RecycleView.adapter.BaseAdapter;
import com.sincerity.utilslibrary.view.RecycleView.adapter.BaseViewHolder;
import com.sincerity.utilslibrary.view.RecycleView.adapter.WrapperRecycleView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by Sincerity on 2019/9/6.
* 描述:
*/
public class FoundPage extends Fragment {
WrapperRecycleView mRecycleView;
private View mView;
private ListView mList;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_found, container, false);
initViews();
return mView;
}
private void initViews() {
mRecycleView = mView.findViewById(R.id.rv_foundMain);
final List<String> list = new ArrayList<>();
for (int i = 0; i < 30; i++) {
list.add(i + "Since");
}
GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 2);
mRecycleView.setLayoutManager(layoutManager);
// mRecycleView.setGridLayoutSpanSizeLookUp(2);
// mRecycleView.addItemDecoration(new GridLayoutDecoration(getActivity(), R.drawable.line_view));
mRecycleView.addItemDecoration(new DividerItemDecoration(getActivity(), 1));
final Adapter mAdapter = new Adapter(getActivity(), R.layout.item_found, list);
mRecycleView.setAdapter(mAdapter);
ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
// @Override
// public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull
// RecyclerView.ViewHolder viewHolder) {
// //移动的标记
// int swipeFlags = 0;
// int dragFlags = 0;
// //GridLayoutManager 是继承 LinearLayoutManager
// if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
// dragFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP | ItemTouchHelper.DOWN;
// } else {
// dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
// swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
// }
// //拖动
// return makeMovementFlags(dragFlags, swipeFlags);
// }
//
// @Override
// public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder viewHolder1) {
// //原来的位置
// int fontPosition = viewHolder.getAdapterPosition();
// //目标位置
// int targetPosition = viewHolder1.getAdapterPosition();
// //数据的替换
// if (fontPosition > targetPosition) {
// for (int i = fontPosition; i < targetPosition; i++) {
// Collections.swap(list, i, i + 1);
// }
// } else {
// for (int i = targetPosition; i < fontPosition; i++) {
// Collections.swap(list, i, i - 1);
// }
// }
// Log.e("admin",fontPosition+"-----------"+targetPosition);
// mAdapter.notifyItemMoved(fontPosition, targetPosition);
// return true;
// }
//
// @Override
// public void onSelectedChanged(@Nullable RecyclerView.ViewHolder viewHolder, int actionState) {
// super.onSelectedChanged(viewHolder, actionState);
// //状态发生改变 正常 侧滑 拖动
// if (actionState != ItemTouchHelper.ACTION_STATE_IDLE)
// viewHolder.itemView.setBackgroundColor(Color.GREEN);
// }
//
// @Override
// public void clearView(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
// super.clearView(recyclerView, viewHolder);
// //消除界面复用的问题 动画执行完毕
// viewHolder.itemView.setBackgroundColor(Color.WHITE);
// }
//
// @Override
// public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
// //侧滑执行删除完成 ,需要更新Adapter
// int position = viewHolder.getAdapterPosition(); //当前侧滑的位置
// mAdapter.notifyItemRemoved(position);
// list.remove(position);
// }
/**
* 这个方法是设置是否滑动时间,以及拖拽的方向,所以在这里需要判断一下是列表布局还是网格布局,
* 如果是列表布局的话则拖拽方向为DOWN和UP,如果是网格布局的话则是DOWN和UP和LEFT和RIGHT
*
* @param recyclerView
* @param viewHolder
* @return
*/
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN |
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
final int swipeFlags = 0;
return makeMovementFlags(dragFlags, swipeFlags);
} else {
final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
final int swipeFlags = 0;
return makeMovementFlags(dragFlags, swipeFlags);
}
}
/**
* onMove()方法则是我们在拖动的时候不断回调的方法,在这里我们需要将正在拖拽的item和集合的item进行交换元素,然后在通知适配器更新数据
*
* @param recyclerView
* @param viewHolder
* @param target
* @return
*/
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
//得到当拖拽的viewHolder的Position
int fromPosition = viewHolder.getAdapterPosition();
//拿到当前拖拽到的item的viewHolder
int toPosition = target.getAdapterPosition();
// if(list.get(fromPosition).getLocked() || list.get(toPosition).getLocked()){
// // 不可拖拽(包括 不可拖拽到其他地方 或者 其他地方拖拽到 这里 )
// return false;
// }else{
if (fromPosition < toPosition) {
for (int i = fromPosition; i < toPosition; i++) {
Collections.swap(list, i, i + 1);
}
} else {
for (int i = fromPosition; i > toPosition; i--) {
Collections.swap(list, i, i - 1);
}
}
mAdapter.notifyItemMoved(fromPosition, toPosition);
return true;
// }
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int actionState) {
/*
ACTION_STATE_IDLE:闲置状态
ACTION_STATE_SWIPE:滑动状态
ACTION_STATE_DRAG:拖拽状态*/
if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
viewHolder.itemView.setBackgroundColor(Color.LTGRAY);
}
super.onSelectedChanged(viewHolder, actionState);
}
/**
* 手指松开的时候还原
*
* @param recyclerView
* @param viewHolder
*/
@Override
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
super.clearView(recyclerView, viewHolder);
viewHolder.itemView.setBackgroundColor(Color.WHITE);
// mEditFinishTabList = datas; // 得到重新排序后最终的元素集合
mAdapter.addAll(list);
// 监听 结束拖拽:
/* mTvTabEdit.setTextColor(getResources().getColor(R.color.colorAccent));
mTabHint.setText(mChannelHint);
mTvTabEdit.setText(mEdit);*/
}
});
//必须绑定RecycleView
helper.attachToRecyclerView(mRecycleView);
final View mHeaderView = LayoutInflater.from(getActivity()).inflate(R.layout.header_view, mRecycleView, false);
mRecycleView.addHeaderView(mHeaderView);
mRecycleView.setGridLayoutSpanSizeLookUp(2);
}
}
class Adapter extends BaseAdapter<String> {
Adapter(Context context, int mLayoutId, List<String> data) {
super(context, mLayoutId, data);
}
@Override
protected void setData(BaseViewHolder baseViewHolder, String s, int i) {
//绑定数据
baseViewHolder.setText(R.id.item_tv_main, s);
baseViewHolder.setImgFromPath(R.id.item_img_main, new BaseImageLoader("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/logo_white_fe6da1ec.png"));
// TextView mTvMain = baseViewHolder.getView(R.id.item_tv_main);
// mTvMain.setText(s);
// ((TextView) baseViewHolder.itemView.findViewById(R.id.item_tv_main)).setText(s);
}
}
| true
|
afeb30ad9b81ac96d51d3fdc09da34234ce83591
|
Java
|
java-july-2021/DylanC-Assignments
|
/01-java-fundamentals/03-fizzbuzz/FizzBuzzTest.java
|
UTF-8
| 141
| 1.710938
| 2
|
[] |
no_license
|
public class FizzBuzzTest{
public static void main(String[] args){
FizzBuzz test = new FizzBuzz();
test.tester();
}
}
| true
|
577f583204cc7bbc92950cb83efc339c8fe7be49
|
Java
|
yufy1989/resConImplement
|
/resConImplement-service/src/test/java/com/asiainfo/resConImplement/askService/InvoiceServiceImplTest.java
|
UTF-8
| 1,318
| 2.03125
| 2
|
[] |
no_license
|
package com.asiainfo.resConImplement.askService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.asiainfo.resConImplement.dto.InvoiceDto;
import com.asiainfo.resConImplement.dto.ResultDto;
import com.asiainfo.resConImplement.interfaces.askInterfaces.GetInvoiceService;
/**
* 类说明:
* @author pankx
* @date 2016年8月27日 上午10:13:52
*/
public class InvoiceServiceImplTest {
GetInvoiceService getInvoiceService;
@Before
public void init() {
System.setProperty("spring.profiles.active", "test");
@SuppressWarnings("resource")
ApplicationContext aCtx = new ClassPathXmlApplicationContext(
new String[] { "classpath*:META-INF/spring/applicationContext.xml",
"classpath*:META-INF/spring/applicationContext-mybatis.xml"});
System.out.println("----------------------INIT CONTEXT-----------------------------");
if (aCtx != null) {
getInvoiceService = (GetInvoiceService) aCtx.getBean("getInvoiceService");
}
}
@Test
public void getInvoice(){
ResultDto<InvoiceDto> invoice = getInvoiceService.getInvoice("100100318","2016-07-02Z", "10000000","getInvoiceTest","ford");
System.out.println("invoice::"+invoice);
}
}
| true
|
00874a4e0767ca29a3e788996169ac40ed9f19c9
|
Java
|
denglitong/proficient_in_4x_spring
|
/15.SpringCache/src/main/java/com/denglitong/initcache/UserService5.java
|
UTF-8
| 2,148
| 2.78125
| 3
|
[] |
no_license
|
package com.denglitong.initcache;
import com.denglitong.domain.Member;
import com.denglitong.domain.User;
import com.denglitong.domain.Visitor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author litong.deng@foxmail.com
* @date 2021/6/24
*/
@Service("userService5")
public class UserService5 {
private static final String USER_CACHE = "users";
private final Map<Integer, User> userMap = new ConcurrentHashMap<>();
{
userMap.put(1, new Member("1", "w1"));
userMap.put(2, new Visitor("2", "w2"));
}
private CacheManager cacheManager;
@Autowired
public void setCacheManager(CacheManager cacheManager) {
this.cacheManager = cacheManager;
}
/**
* 注入 cacheManager 调用 getCache() 获取缓存列表,然后初始化缓存列表
* <p>
* PostConstruct 需要有 component-scan 扫描才能生效的
*/
@PostConstruct
public void init() {
System.out.println("post construct init");
Cache userCache = cacheManager.getCache(USER_CACHE);
userMap.forEach(userCache::put);
}
@Cacheable(cacheNames = USER_CACHE)
public User getUser(int id) {
System.out.println("User with id " + id + " requested.");
return userMap.get(id);
}
public static void main(String[] args) {
String configPath = "classpath:applicationContext.xml";
ApplicationContext context = new ClassPathXmlApplicationContext(configPath);
UserService5 userService5 = context.getBean(UserService5.class);
System.out.println(userService5.getUser(1));
System.out.println(userService5.getUser(2));
System.out.println(userService5.getUser(3));
}
}
| true
|
92ba58070e85b0cf4a129b5cc07992fc82841dc8
|
Java
|
AlexCohenDambros/Problem-Solving-Mechanism-of-Search
|
/AulaPilha/Pilha.java
|
WINDOWS-1252
| 1,073
| 3.78125
| 4
|
[] |
no_license
|
package AulaPilha;
public class Pilha {
public int[] dados;
private int topo;
public int max;
public Pilha(int tam) {
this.max = tam;
this.dados = new int[tam];
this.topo = -1;
}
public boolean cheia() {
return (topo == max-1);
}
public boolean vazia() {
return (topo == -1);
}
public boolean empilhar(int x) {
if (cheia()) {
System.out.println("Pilha Cheia!");
return false;
}
this.dados[++topo] = x;
return true;
}
public int desempilhar() {
if (vazia()) {
System.out.println("Pilha Vazia!");
}
int x = dados[topo];
topo--;
return x;
}
public int retornaTopo() {
if (vazia()) {
System.out.println("Pilha Vazia!");
return 0;
}
return dados[topo];
}
public static void main(String args[]) {
Pilha p = new Pilha(3);
p.empilhar(6);
p.empilhar(12);
p.empilhar(1);
int x = p.desempilhar();
System.out.println("O valor desempilhado foi de: " + x);
System.out.println("O valor do topo : " + p.retornaTopo());
}
}
| true
|
8fde63f42869cf521e12741d1675c9be915652d8
|
Java
|
Jul-must/MUD
|
/Teacher.java
|
UTF-8
| 1,573
| 3.75
| 4
|
[] |
no_license
|
import java.util.*;
public class Teacher extends Creature{
Course course;
String question; //should contain the options.
String correctAnswer; //should have a test if this answer is an option
Random rand = new Random();
Scanner user_input = new Scanner(System.in);
public Teacher(String name, String desc, Course course, String question, String correctAnswer)
{
super(name, desc);
this.course = course;
this.question = question;
this.correctAnswer = correctAnswer;
}
public void Interact(Player player)
{
if(player.HasFinishedCourse(course))
{
if (rand.nextInt(1) == 0)
{
System.out.println("Well hello there ;). Do you still know your stuff?\nHere is a question for you: " + question);
if (user_input.next() == correctAnswer)
{
System.out.println("Correct answer. Your good to go.");
}
else
{
System.out.println("Wrong answer. Now I'll have to fail you.\n-" + course.GetHP() + "HP");
}
}
}
else if (player.HasEnrolledCourse(course)) // this is if the player has this course unfinfished
{
if (rand.nextInt(3) == 0) //1/4 for this to happen. And this is when you dont get any question
{
System.out.println("Im busy. Get outof here!");
}
else
{
System.out.println("Here is a question for you: " + question);
if (user_input.next() == correctAnswer)
{
System.out.println("Correct answer! Good job!\n+" + course.GetHP() + "HP");
player.FinishCourse(course);
}
}
}
}
}
| true
|
d2123290507e2b18ef403fe623644b859341c9c5
|
Java
|
OctavianoDeLaTorre/Consultorio
|
/src/VO/ClienteVO.java
|
UTF-8
| 1,760
| 2.296875
| 2
|
[] |
no_license
|
package VO;
public class ClienteVO {
/*Todo los atributos*/
String curp_Cliente;
String nombre_Cliente;
String primer_Apellido;
String segundo_Apellido;
String direccion_Cliente;
String telefono_Cliente;
String consultorio_Dental;
public ClienteVO(){}
/*Todo los codigos get*/
public String getCurp_Cliente(){
return curp_Cliente;
}
public String getNombre_Cliente(){
return nombre_Cliente;
}
public String getPrimer_Apellido(){
return primer_Apellido;
}
public String getSegundo_Apellido(){
return segundo_Apellido;
}
public String getDireccion_Cliente(){
return direccion_Cliente;
}
public String getTelefono_Cliente(){
return telefono_Cliente;
}
public String getConsultorio_Dental(){
return consultorio_Dental;
}
/*Todo los codigos set*/
public void setCurp_Cliente(String curp_Cliente){
this.curp_Cliente = curp_Cliente;
}
public void setNombre_Cliente(String nombre_Cliente){
this.nombre_Cliente = nombre_Cliente;
}
public void setPrimer_Apellido(String primer_Apellido){
this.primer_Apellido = primer_Apellido;
}
public void setSegundo_Apellido(String segundo_Apellido){
this.segundo_Apellido = segundo_Apellido;
}
public void setDireccion_Cliente(String direccion_Cliente){
this.direccion_Cliente = direccion_Cliente;
}
public void setTelefono_Cliente(String telefono_Cliente){
this.telefono_Cliente = telefono_Cliente;
}
public void setConsultorio_Dental(String consultorio_Dental){
this.consultorio_Dental = consultorio_Dental;
}
}
| true
|
a19279d2ddfc622fa990f2122c5cce146f8a23d2
|
Java
|
Jancly/Novel
|
/app/src/main/java/com/stevefat/novel/Views/FindWebView.java
|
UTF-8
| 4,438
| 1.929688
| 2
|
[] |
no_license
|
package com.stevefat.novel.Views;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ActionMode;
import android.view.ActionMode.Callback;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import com.orhanobut.logger.Logger;
/**
* Author: ngh
* date: 2016/10/13
*/
public class FindWebView extends WebView {
public Callback callback;
private OnScrollChangedListener mOnScrollChangedListener;
@SuppressWarnings("deprecation")
public FindWebView(Context context, AttributeSet attrs, int defStyle,
boolean privateBrowsing) {
super(context, attrs, defStyle, privateBrowsing);
init();
}
public FindWebView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public FindWebView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public FindWebView(Context context) {
super(context);
init();
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@SuppressLint("SetJavaScriptEnabled")
private void init() {
WebSettings setting = getSettings();
setting.setJavaScriptEnabled(true);
setting.setJavaScriptCanOpenWindowsAutomatically(true);
addJavascriptInterface(new SelectedText(), "search");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//支持webview调试
WebView.setWebContentsDebuggingEnabled(true);
}
}
@Override
public ActionMode startActionMode(Callback callback) {
return super.startActionMode(callback);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event);
}
public class CustomizedSelectActionModeCallback implements ActionMode.Callback {
private Callback callback;
public CustomizedSelectActionModeCallback(Callback callback) {
this.callback = callback;
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return callback.onCreateActionMode(mode, menu);
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return callback.onPrepareActionMode(mode, menu);
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
if (item == null || TextUtils.isEmpty(item.getTitle())) {
return callback.onActionItemClicked(mode, item);
}
if (!item.getTitle().toString().contains("搜索")
&& !item.getTitle().toString().contains("search")) {
return callback.onActionItemClicked(mode, item);
}
loadUrl("javascript:window.search.show(window.getSelection().toString());");
clearFocus();
return true;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
callback.onDestroyActionMode(mode);
}
}
public class SelectedText {
@JavascriptInterface
public void show(String data) {
Logger.e(data);
// Intent intent = new Intent(getContext(), SearchActivity.class);
// intent.putExtra(SearchActivity.TAG_SEARCH, data);
// getContext().startActivity(intent);
}
}
private int dY;
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
int dy = t - oldt;
dY += dy;
if (mOnScrollChangedListener != null && Math.abs(dY) > 10) {
dY = 0;
mOnScrollChangedListener.onScroll(l, t, oldl, oldt);
}
}
public interface OnScrollChangedListener {
public void onScroll(int l, int t, int oldl, int oldt);
}
public void setOnScrollChangedListener(OnScrollChangedListener mOnScrollChangedListener) {
this.mOnScrollChangedListener = mOnScrollChangedListener;
}
}
| true
|
62ca1aafccba79dbcdebf8843dee39e9c7a8d320
|
Java
|
ClaudiaAriasH/ProyectoMatriculas
|
/src/proyectomatriculas/Profesor.java
|
UTF-8
| 4,744
| 2.71875
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package proyectomatriculas;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
*
* @author Claudia
*/
public class Profesor {
//Atributos
private List<ProfesorDto> datosProfesor;
//Contructor
public Profesor() {
this.datosProfesor = new ArrayList<>();
datosProfesor.add(new ProfesorDto("Quimico", "Sebastian", "Vega Guitierrez", 1209876554, "1990/08/03", "5982553", "sebas.Vega@hotmail.com", "Carrera 62#34 sur"));
datosProfesor.add(new ProfesorDto("Biologa", "Sara", "Martinez Montenegro", 1308765439, "1994/08/03", "3894057", "sarism@hotmail.com", "Carerra 60B #38-04"));
datosProfesor.add(new ProfesorDto("Administrador de empresas", "Daniel", "Ortiz Mejia", 1037865439, "1989/04/30", "59086542", "dani.ortiz@hotmail.com", "Calle 58#42-4"));
datosProfesor.add(new ProfesorDto("Educación especial", "Kelly", "Londoño Palacio", 39206934, "1985/08/01", "5896420", "kelly85@hotmail.com", "Calle 68 B #73-09"));
}
/**
*
* @param profesion
* @param nombres
* @param apellidos
* @param identificacion
* @param fechaNacimiento
* @param telefono
* @param correo
* @param direccion
*/
public void agregarProfesor(String profesion, String nombres, String apellidos, int identificacion, String fechaNacimiento, String telefono, String correo, String direccion) {
ProfesorDto profesorDto = new ProfesorDto();
profesorDto = new ProfesorDto(profesion, nombres, apellidos, identificacion, fechaNacimiento, telefono, correo, direccion);
datosProfesor.add(profesorDto);
System.out.println("Se guardo de forma exitosa.");
}
/**
*
* @param identificacion
* @return
*/
public int buscarProfesor(int identificacion) {
boolean existe = false;
int indice = 0;
for (int i = 0; i < datosProfesor.size(); i++) {
if (datosProfesor.get(i).getIdentificacion() == identificacion) {
existe = true;
indice = i;
}
}
if (existe) {
System.out.println("************* Datos del Profesor ********** " + "\n");
System.out.println("Nombre: " + datosProfesor.get(indice).getNombres() + " " + datosProfesor.get(indice).getApellidos());
System.out.println("Identificación: " + datosProfesor.get(indice).getIdentificacion());
System.out.println("Fecha de Nacimiento: " + datosProfesor.get(indice).getFechaNacimiento());
System.out.println("Profesión: " + datosProfesor.get(indice).getProfesion());
System.out.println("Telefono: " + datosProfesor.get(indice).getTelefono());
System.out.println("Correo: " + datosProfesor.get(indice).getCorreo());
System.out.println("Dirección: " + datosProfesor.get(indice).getDireccion());
} else {
System.out.println("El profesor no existe en el sistema.");
indice = -1;
}
return indice;
}
/**
*
* @param identificacion
*/
public void eliminarProfesor(int identificacion) {
boolean encontrado = false;
for (int i = 0; i < datosProfesor.size(); i++) {
if (datosProfesor.get(i).getIdentificacion() == identificacion) {
datosProfesor.remove(i);
encontrado = true;
}
}
if (encontrado) {
System.out.println("El profesor con el número de identificación " + identificacion + " fue eliminado exitosamente.");
} else {
System.out.println("El profesor no existe en el sistema.");
}
}
/**
*
* @param valor
* @param existe
* @param opcionseleccionada
*/
public void modificarProfesor(String valor, int existe, int opcionseleccionada) {
switch (opcionseleccionada) {
case 1:
datosProfesor.get(existe).setTelefono(valor);
break;
case 2:
datosProfesor.get(existe).setCorreo(valor);
break;
case 3:
datosProfesor.get(existe).setDireccion(valor);
break;
default:
System.out.println("La opción seleccionada no es válida.");
break;
}
}
public ProfesorDto seleccionarProfesor() {
int cantidadReg = datosProfesor.size();
Random random = new Random();
int indiceAleatorio = random.nextInt((cantidadReg - 1) - 0 + 1) + 0;
return datosProfesor.get(indiceAleatorio);
}
}
| true
|
ca81742291e02c3dbabd6ebb0e4eea47883b81f3
|
Java
|
zkyq05/spider
|
/src/main/java/com/zkyq/spider/NewsScheduled.java
|
UTF-8
| 794
| 2.078125
| 2
|
[] |
no_license
|
package com.zkyq.spider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Spider;
@Component
public class NewsScheduled {
@Autowired
private NewsPipeline newsPipeline;
/**
* 简书
*/
@Scheduled(cron = "*/2 * * * * ?")//0 */1 * * * ?
public void jianShuScheduled() {
System.out.println("----开始执行简书定时任务");
Spider spider = Spider.create(new JianShuProcessor());
spider.addUrl("http://www.jianshu.com");
spider.addPipeline(newsPipeline);
spider.thread(5);
spider.setExitWhenComplete(true);
spider.start();
spider.stop();
}
}
| true
|
a778e1e7d3396718e4277cb30b4d5a30861320e9
|
Java
|
imbkj/BMSbate
|
/src/dal/CoBase/CoBase_SelectDal.java
|
UTF-8
| 71,686
| 1.890625
| 2
|
[] |
no_license
|
/**
* @Classname CoBase_SelectDal
* @ClassInfo 公司基本信息数据库查询类
* @author 林少斌、陈耀家
* @Date 2013-11-27
*/
package dal.CoBase;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.zkoss.zul.ListModelList;
import Conn.dbconn;
import Model.CoBaseModel;
import Model.CoCompactModel;
import Model.CoOfferModel;
import Model.EmHouseUpdateModel;
import Model.EmShebaoUpdateModel;
import Util.UserInfo;
public class CoBase_SelectDal extends dbconn {
/**
* 根据cid查询公积金信息
*
* @param cid
* @return
*/
public List<EmHouseUpdateModel> getGjjInfoByCid(int cid) {
List<EmHouseUpdateModel> list = new ArrayList<EmHouseUpdateModel>();
String sql = " select *,case emhu_ifstop when 0 then '在册' when 1 then '终止' when 2 then '核查失败' end state from emhouseupdate where cid=? ";
PreparedStatement pstmt = getpre(sql);
try {
pstmt.setInt(1, cid);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
EmHouseUpdateModel m = new EmHouseUpdateModel();
m.setGid(rs.getInt("gid"));
m.setOwnmonth(rs.getInt("Ownmonth"));
m.setEmhu_company(rs.getString("emhu_company"));
m.setEmhu_companyid(rs.getString("emhu_companyid"));
m.setEmhu_name(rs.getString("emhu_name"));
m.setEmhu_idcard(rs.getString("emhu_idcard"));
m.setEmhu_idcardclass(rs.getString("emhu_idcardclass"));
m.setEmhu_hj(rs.getString("emhu_hj"));
m.setEmhu_computerid(rs.getString("emhu_computerid"));
m.setEmhu_mobile(rs.getString("emhu_mobile"));
m.setEmhu_title(rs.getString("emhu_title"));
m.setEmhu_wifename(rs.getString("emhu_wifename"));
m.setEmhu_wifeidcard(rs.getString("emhu_wifeidcard"));
m.setEmhu_degree(rs.getString("emhu_degree"));
m.setEmhu_radix(rs.getDouble("emhu_radix"));
m.setEmhu_bonus(rs.getBigDecimal("emhu_bonus"));
m.setEmhu_cpp(rs.getDouble("emhu_cpp"));
m.setEmhu_opp(rs.getDouble("emhu_opp"));
m.setEmhu_cp(rs.getDouble("emhu_cp"));
m.setEmhu_op(rs.getDouble("emhu_op"));
m.setState(rs.getString("state"));
list.add(m);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
/**
* 根据cid查询公积金信息
*
* @param cid
* @return
*/
public List<EmHouseUpdateModel> getGjjInfoByCid(int cid, int type) {
List<EmHouseUpdateModel> list = new ArrayList<EmHouseUpdateModel>();
String sql = " select *,case emhu_ifstop when 0 then '在册' when 1 then '终止' when 2 then '核查失败' "
+ "end state from emhouseupdate where cid=? AND emhu_single=? order by emhu_name";
PreparedStatement pstmt = getpre(sql);
try {
pstmt.setInt(1, cid);
pstmt.setInt(2, type);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
EmHouseUpdateModel m = new EmHouseUpdateModel();
m.setGid(rs.getInt("gid"));
m.setOwnmonth(rs.getInt("Ownmonth"));
m.setEmhu_company(rs.getString("emhu_company"));
m.setEmhu_companyid(rs.getString("emhu_companyid"));
m.setEmhu_name(rs.getString("emhu_name"));
m.setEmhu_idcard(rs.getString("emhu_idcard"));
m.setEmhu_idcardclass(rs.getString("emhu_idcardclass"));
m.setEmhu_hj(rs.getString("emhu_hj"));
m.setEmhu_computerid(rs.getString("emhu_computerid"));
m.setEmhu_mobile(rs.getString("emhu_mobile"));
m.setEmhu_title(rs.getString("emhu_title"));
m.setEmhu_wifename(rs.getString("emhu_wifename"));
m.setEmhu_wifeidcard(rs.getString("emhu_wifeidcard"));
m.setEmhu_degree(rs.getString("emhu_degree"));
m.setEmhu_radix(rs.getDouble("emhu_radix"));
m.setEmhu_bonus(rs.getBigDecimal("emhu_bonus"));
m.setEmhu_cpp(rs.getDouble("emhu_cpp"));
m.setEmhu_opp(rs.getDouble("emhu_opp"));
m.setEmhu_cp(rs.getDouble("emhu_cp"));
m.setEmhu_op(rs.getDouble("emhu_op"));
m.setState(rs.getString("state"));
list.add(m);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
/**
* 根据cid查询公积金信息AllinOne
*
* @param cid
* @return
*/
public List<EmHouseUpdateModel> getGjjInfoByCidAllinOne(int cid,
Integer type) {
List<EmHouseUpdateModel> list = new ArrayList<EmHouseUpdateModel>();
String str = "";
if (type != null && type != 3) {
str = " and emhu_single=" + type;
}
String sql = " select eu.*,state=(case when ec.emhc_change is not null then ec.emhc_change when emhu_ifstop=0 then '正常在册' when emhu_ifstop=1 then '终止' when emhu_ifstop=2 then '核查失败' end) from emhouseupdate eu left join (select * from emhousechange a where exists (select emhc_id from (select gid,cid,MAX(emhc_id)as emhc_id from emhousechange b where b.ownmonth=(select top 1 ownmonth from EmHouseUpdate) group by GID,CID)b where a.emhc_id=b.emhc_id))ec on eu.ownmonth=ec.ownmonth and eu.gid=ec.gid where eu.ownmonth=(select top 1 ownmonth from EmHouseUpdate) and eu.cid=? "
+ str + " order by emhu_name";
PreparedStatement pstmt = getpre(sql);
try {
pstmt.setInt(1, cid);
// pstmt.setInt(2, type);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
EmHouseUpdateModel m = new EmHouseUpdateModel();
m.setGid(rs.getInt("gid"));
m.setOwnmonth(rs.getInt("Ownmonth"));
m.setEmhu_company(rs.getString("emhu_company"));
m.setEmhu_companyid(rs.getString("emhu_companyid"));
m.setEmhu_houseid(rs.getString("emhu_houseid"));
m.setEmhu_name(rs.getString("emhu_name"));
m.setEmhu_idcard(rs.getString("emhu_idcard"));
m.setEmhu_idcardclass(rs.getString("emhu_idcardclass"));
m.setEmhu_hj(rs.getString("emhu_hj"));
m.setEmhu_computerid(rs.getString("emhu_computerid"));
m.setEmhu_mobile(rs.getString("emhu_mobile"));
m.setEmhu_title(rs.getString("emhu_title"));
m.setEmhu_wifename(rs.getString("emhu_wifename"));
m.setEmhu_wifeidcard(rs.getString("emhu_wifeidcard"));
m.setEmhu_degree(rs.getString("emhu_degree"));
m.setEmhu_radix(rs.getDouble("emhu_radix"));
m.setEmhu_bonus(rs.getBigDecimal("emhu_bonus"));
m.setEmhu_cpp(rs.getDouble("emhu_cpp"));
m.setEmhu_opp(rs.getDouble("emhu_opp"));
m.setEmhu_cp(rs.getDouble("emhu_cp"));
m.setEmhu_op(rs.getDouble("emhu_op"));
m.setState(rs.getString("state"));
m.setEmhu_ifstop(rs.getInt("emhu_ifstop"));
list.add(m);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
/**
* 根据cid查询社保信息
*
* @param cid
* @return
*/
public List<EmShebaoUpdateModel> getShebaoInfoByCid(int cid) {
List<EmShebaoUpdateModel> list = new ArrayList<EmShebaoUpdateModel>();
String sql = " select * from emshebaoupdate where cid=? ";
PreparedStatement pstmt = getpre(sql);
try {
pstmt.setInt(1, cid);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
EmShebaoUpdateModel m = new EmShebaoUpdateModel();
m.setGid(rs.getInt("gid"));
m.setOwnmonth(rs.getInt("Ownmonth"));
m.setEsiu_company(rs.getString("esiu_company"));
m.setEsiu_name(rs.getString("esiu_name"));
m.setEsiu_computerid(rs.getString("esiu_computerid"));
m.setEsiu_idcard(rs.getString("esiu_idcard"));
m.setEsiu_hj(rs.getString("esiu_hj"));
m.setEsiu_radix(rs.getInt("esiu_radix"));
m.setEsiu_yl(rs.getString("esiu_yl"));
m.setEsiu_gs(rs.getString("esiu_gs"));
m.setEsiu_sye(rs.getString("esiu_sye"));
m.setEsiu_syu(rs.getString("esiu_syu"));
m.setEsiu_yltype(rs.getString("esiu_yltype"));
m.setEsiu_house(rs.getString("esiu_house"));
m.setEsiu_ylop(rs.getBigDecimal("esiu_ylop"));
m.setEsiu_ylcp(rs.getBigDecimal("esiu_ylcp"));
m.setEsiu_jlop(rs.getBigDecimal("esiu_jlop"));
m.setEsiu_jlcp(rs.getBigDecimal("esiu_jlcp"));
m.setEsiu_syuop(rs.getBigDecimal("esiu_syuop"));
m.setEsiu_syucp(rs.getBigDecimal("esiu_syucp"));
m.setEsiu_syeop(rs.getBigDecimal("esiu_syeop"));
m.setEsiu_syecp(rs.getBigDecimal("esiu_syecp"));
m.setEsiu_gsop(rs.getBigDecimal("esiu_gsop"));
m.setEsiu_gscp(rs.getBigDecimal("esiu_gscp"));
m.setEsiu_houseop(rs.getBigDecimal("esiu_houseop"));
m.setEsiu_housecp(rs.getBigDecimal("esiu_housecp"));
m.setEsiu_totalop(rs.getBigDecimal("esiu_totalop"));
m.setEsiu_totalcp(rs.getBigDecimal("esiu_totalcp"));
list.add(m);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
/**
* 根据cid查询社保信息
*
* @param cid
* @return
*/
public List<EmShebaoUpdateModel> getShebaoInfoByCid(int cid, int type) {
List<EmShebaoUpdateModel> list = new ArrayList<EmShebaoUpdateModel>();
String sql = " select * from emshebaoupdate where cid=? and Esiu_single=? order by esiu_name";
PreparedStatement pstmt = getpre(sql);
try {
pstmt.setInt(1, cid);
pstmt.setInt(2, type);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
EmShebaoUpdateModel m = new EmShebaoUpdateModel();
m.setGid(rs.getInt("gid"));
m.setOwnmonth(rs.getInt("Ownmonth"));
m.setEsiu_company(rs.getString("esiu_company"));
m.setEsiu_name(rs.getString("esiu_name"));
m.setEsiu_computerid(rs.getString("esiu_computerid"));
m.setEsiu_idcard(rs.getString("esiu_idcard"));
m.setEsiu_hj(rs.getString("esiu_hj"));
m.setEsiu_radix(rs.getInt("esiu_radix"));
m.setEsiu_yl(rs.getString("esiu_yl"));
m.setEsiu_gs(rs.getString("esiu_gs"));
m.setEsiu_sye(rs.getString("esiu_sye"));
m.setEsiu_syu(rs.getString("esiu_syu"));
m.setEsiu_yltype(rs.getString("esiu_yltype"));
m.setEsiu_house(rs.getString("esiu_house"));
m.setEsiu_ylop(rs.getBigDecimal("esiu_ylop"));
m.setEsiu_ylcp(rs.getBigDecimal("esiu_ylcp"));
m.setEsiu_jlop(rs.getBigDecimal("esiu_jlop"));
m.setEsiu_jlcp(rs.getBigDecimal("esiu_jlcp"));
m.setEsiu_syuop(rs.getBigDecimal("esiu_syuop"));
m.setEsiu_syucp(rs.getBigDecimal("esiu_syucp"));
m.setEsiu_syeop(rs.getBigDecimal("esiu_syeop"));
m.setEsiu_syecp(rs.getBigDecimal("esiu_syecp"));
m.setEsiu_gsop(rs.getBigDecimal("esiu_gsop"));
m.setEsiu_gscp(rs.getBigDecimal("esiu_gscp"));
m.setEsiu_houseop(rs.getBigDecimal("esiu_houseop"));
m.setEsiu_housecp(rs.getBigDecimal("esiu_housecp"));
m.setEsiu_totalop(rs.getBigDecimal("esiu_totalop"));
m.setEsiu_totalcp(rs.getBigDecimal("esiu_totalcp"));
m.setEsiu_ifstop(rs.getInt("esiu_ifstop"));
list.add(m);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
/**
* 根据cid查询社保信息AllinOne
*
* @param cid
* @return
*/
public List<EmShebaoUpdateModel> getShebaoInfoByCidAllinOne(int cid,
Integer type) {
List<EmShebaoUpdateModel> list = new ArrayList<EmShebaoUpdateModel>();
String str = "";
if (type != null && type != 3) {
str = " and Esiu_single=" + type;
}
String sql = " select es.*,state=(case when ec.emsc_change is not null then ec.emsc_change when efc.emsc_change is not null then efc.emsc_change when esiu_ifstop=2 then '被调走' when esiu_ifstop=3 then '新增调入退回' when esiu_ifstop=1 then '不在册' else '正常在册' end) from EmShebaoUpdate es "
+ " left join (select * from emshebaochange a where exists (select id from (select gid,cid,MAX(id)as id from EmShebaoChange where emsc_ifdeclare<>3 and ownmonth=(select top 1 ownmonth from EmShebaoUpdate) group by GID,CID)b where a.ID=b.id)) ec on es.Ownmonth=ec.Ownmonth and es.GID=ec.GID"
+ " left join (select * from EmShebaoChangeForeigner a where exists (select id from (select gid,cid,MAX(id)as id from EmShebaoChangeForeigner where emsc_ifdeclare<>3 and ownmonth=(select top 1 ownmonth from EmShebaoUpdate) group by GID,CID)b where a.ID=b.id)) efc on es.Ownmonth=efc.Ownmonth and es.GID=efc.GID "
+ " where es.ownmonth=(select top 1 ownmonth from EmShebaoUpdate) and es.cid=? "
+ str + " order by esiu_name";
PreparedStatement pstmt = getpre(sql);
try {
pstmt.setInt(1, cid);
// pstmt.setInt(2, type);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
EmShebaoUpdateModel m = new EmShebaoUpdateModel();
m.setGid(rs.getInt("gid"));
m.setOwnmonth(rs.getInt("Ownmonth"));
m.setEsiu_company(rs.getString("esiu_company"));
m.setEsiu_name(rs.getString("esiu_name"));
m.setEsiu_computerid(rs.getString("esiu_computerid"));
m.setEsiu_idcard(rs.getString("esiu_idcard"));
m.setEsiu_hj(rs.getString("esiu_hj"));
m.setEsiu_radix(rs.getInt("esiu_radix"));
m.setEsiu_yl(rs.getString("esiu_yl"));
m.setEsiu_gs(rs.getString("esiu_gs"));
m.setEsiu_sye(rs.getString("esiu_sye"));
m.setEsiu_syu(rs.getString("esiu_syu"));
m.setEsiu_yltype(rs.getString("esiu_yltype"));
m.setEsiu_house(rs.getString("esiu_house"));
m.setEsiu_ylop(rs.getBigDecimal("esiu_ylop"));
m.setEsiu_ylcp(rs.getBigDecimal("esiu_ylcp"));
m.setEsiu_jlop(rs.getBigDecimal("esiu_jlop"));
m.setEsiu_jlcp(rs.getBigDecimal("esiu_jlcp"));
m.setEsiu_syuop(rs.getBigDecimal("esiu_syuop"));
m.setEsiu_syucp(rs.getBigDecimal("esiu_syucp"));
m.setEsiu_syeop(rs.getBigDecimal("esiu_syeop"));
m.setEsiu_syecp(rs.getBigDecimal("esiu_syecp"));
m.setEsiu_gsop(rs.getBigDecimal("esiu_gsop"));
m.setEsiu_gscp(rs.getBigDecimal("esiu_gscp"));
m.setEsiu_houseop(rs.getBigDecimal("esiu_houseop"));
m.setEsiu_housecp(rs.getBigDecimal("esiu_housecp"));
m.setEsiu_totalop(rs.getBigDecimal("esiu_totalop"));
m.setEsiu_totalcp(rs.getBigDecimal("esiu_totalcp"));
m.setEmsc_s8(rs.getString("state"));
m.setEsiu_ifstop(rs.getInt("esiu_ifstop"));
list.add(m);
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
// 根据cid查询公司信息
public CoBaseModel getCobaseByCid(int cid) {
CoBaseModel cbm = new CoBaseModel();
String sql = " SELECT * FROM CoBase WHERE cid = ? ";
try {
PreparedStatement pstmt = getpre(sql);
pstmt.setInt(1, cid);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
cbm.setCid(cid);
cbm.setCoba_company(rs.getString("coba_company"));
cbm.setCoba_client(rs.getString("coba_client"));
cbm.setCid(rs.getInt("cid"));
// cbm.setPronum(rs.getInt("pronum"));
cbm.setCoba_spell(rs.getString("coba_spell"));// 公司全称首字母
cbm.setCoba_company(rs.getString("coba_company"));// 公司全称
cbm.setCoba_shortspell(rs.getString("coba_shortspell"));// 简称首字母
cbm.setCoba_shortname(rs.getString("coba_shortname"));// 公司简称
cbm.setCoba_namespell(rs.getString("coba_namespell"));// 全称每个文字的首字母
cbm.setCoba_englishname(rs.getString("coba_englishname"));// 英文名
cbm.setCoba_country(rs.getString("coba_country"));// 所在国家
cbm.setCoba_setuptype(rs.getString("coba_setuptype"));// 公司类型
cbm.setCoba_servicearea(rs.getString("coba_servicearea"));// 服务区域
cbm.setCoba_servicestate(rs.getInt("coba_servicestate"));// 服务状态
cbm.setCoba_stopreason(rs.getString("coba_stopreason"));// 解约原因
cbm.setCoba_stopname(rs.getString("coba_stopname"));// 解约客服
cbm.setCoba_stopremark(rs.getString("coba_stopremark"));// 解约备注
cbm.setCoba_stoptime(rs.getString("coba_stoptime"));// 解约时间
cbm.setCoba_industytype(rs.getString("coba_industytype"));// 所属行业
cbm.setCoba_clientsize(rs.getString("coba_clientsize"));// 客户规模
cbm.setCoba_compacttype(rs.getString("coba_compacttype"));// 合同类型
if (rs.getInt("coba_vip") == 1) {
cbm.setCoba_vip("vip");
}
cbm.setCoba_addname(rs.getString("coba_addname"));
cbm.setCoba_address(rs.getString("Coba_address"));// 注册地址/办公地点
cbm.setCoba_area(rs.getString("coba_area"));// 公司位置/所在区域
cbm.setCoba_companymanager(rs.getString("coba_companymanager"));// 法定代表人
cbm.setCoba_manageraddress(rs.getString("coba_manageraddress"));// 法定代表人地址
cbm.setCoba_postcode(rs.getString("coba_postcode"));// 邮政编码
cbm.setCoba_website(rs.getString("coba_website"));// 公司网址
cbm.setCoba_clientsource(rs.getString("coba_clientsource"));// 客户来源
cbm.setCoba_client(rs.getString("coba_client"));// 客服
cbm.setCoba_manager(rs.getString("coba_manager"));// 客服经理
cbm.setCoba_clientmanager(rs.getString("coba_clientmanager"));// 客服部门经理
cbm.setCoba_hzqsr(rs.getString("coba_hzqsr"));// 合作起始日
cbm.setCoba_remark(rs.getString("coba_remark"));// 备注
cbm.setCoba_regagent(rs.getString("coba_regagent"));// 注册代理方
cbm.setCoba_reg_fund(rs.getString("coba_reg_fund"));// 注册资金
cbm.setCoba_certificate(rs.getString("coba_certificate"));// 证件类型
cbm.setCoba_bregdeadline(rs.getString("coba_bregdeadline"));// 工商登记到期日
cbm.setCoba_bregid(rs.getString("coba_bregid"));// 工商登记号
cbm.setCoba_regexpires(rs.getString("coba_regexpires"));// 驻在期限
cbm.setCoba_regtime(rs.getString("coba_regtime"));// 工商局登记时间
cbm.setCoba_reglimit(rs.getString("coba_reglimit"));// 工商登记证有效期
cbm.setCoba_organdeadline(rs.getString("coba_organdeadline"));// 组织机构到期日
cbm.setCoba_orregtime(rs.getString("coba_orregtime"));// 组织机构代码登记日期
cbm.setCoba_organcode(rs.getString("coba_organcode"));// 组织结构代码
cbm.setCoba_ntbank(rs.getString("coba_ntbank"));// 国税开户银行
cbm.setCoba_ntaccount(rs.getString("coba_ntaccount"));// 国税账号
cbm.setCoba_ntid(rs.getString("coba_ntid"));// 国税深字号
cbm.setCoba_ntregtime(rs.getString("coba_ntregtime"));// 国税登记日期
cbm.setCoba_ntlimit(rs.getString("coba_ntlimit"));// 国税有效期
cbm.setCoba_ntdeadline(rs.getString("coba_ntdeadline"));// 国税纳税有效期
cbm.setCoba_ltregid(rs.getString("coba_ltregid"));// 地税登记号
cbm.setCoba_ltregtime(rs.getString("coba_ltregtime"));// 地税登记时间
cbm.setCoba_ltlimit(rs.getString("coba_ltlimit"));// 地税有效期
cbm.setCoba_ltstate(rs.getString("coba_ltstate"));// 地税开户状态
cbm.setCoba_ltid(rs.getString("coba_ltid"));// 地税电脑号
cbm.setCoba_ltdeadline(rs.getString("coba_ltdeadline"));// 地税纳税期限
cbm.setCoba_ltbank(rs.getString("coba_ltbank"));// 地税开户银行
cbm.setCoba_ltaccount(rs.getString("coba_ltaccount"));// 地税账号
cbm.setCoba_gtstate(rs.getString("coba_gtstate"));// 个税开户状态
cbm.setCoba_gtbank(rs.getString("coba_gtbank"));// 个税开户行
cbm.setCoba_gtacc(rs.getString("coba_gtacc"));// 个税纳税账号
cbm.setCoba_gtto(rs.getString("coba_gtto"));// 所属税局
cbm.setCoba_gtdeadline(rs.getString("coba_gtdeadline"));// 个税申报截止日
cbm.setCoba_sistate(rs.getString("coba_sistate"));// 开户状态
cbm.setCoba_siiilimit(rs.getString("coba_siiilimit"));// 工伤比例
cbm.setCoba_sicoding(rs.getString("coba_sicoding"));// 单位编码
cbm.setCoba_sibank(rs.getString("coba_sibank"));// 开户行
cbm.setCoba_siaccount(rs.getString("coba_siaccount"));// 账户
cbm.setCoba_sihospital(rs.getString("coba_sihospital"));// 社康医疗机构
cbm.setCoba_sihosphone(rs.getString("coba_sihosphone"));// 社康电话
cbm.setCoba_sihosadd(rs.getString("coba_sihosadd"));// 社康地址
cbm.setCoba_dept(rs.getString("coba_dept"));
cbm.setCoba_regremark(rs.getString("coba_regremark"));// 公司注册信息备注
cbm.setCoba_addtime(rs.getString("coba_addtime"));// 公司信息添加时间
cbm.setCoba_addname(rs.getString("coba_addname"));// 公司信息添加人
cbm.setCoba_modtime(rs.getString("coba_modtime"));// 公司信息修改时间
cbm.setCoba_modname(rs.getString("coba_modname"));// 公司信息修改人
cbm.setCoba_shebaodeclare(rs.getString("coba_shebaodeclare"));
cbm.setCoba_ufid(rs.getString("coba_ufid"));// 收款中用到的用友编号
cbm.setCoba_ufid2(rs.getString("coba_ufid2"));// 社保和公积金台帐中用到的用友编号
cbm.setCoba_ufclass(rs.getString("coba_ufclass"));
cbm.setCoba_invoicerule(rs.getString("coba_invoicerule"));
cbm.setCoba_invoiceaddress(rs.getString("coba_invoiceaddress"));// 发票邮寄地址
cbm.setCoba_wtco(rs.getString("coba_wtco"));
cbm.setCoba_regdataList(rs.getString("coba_regdataList"));// 注册信息-递交材料
cbm.setCoba_assistant(rs.getString("coba_assistant"));// 客服文员
cbm.setCoba_zytcid(rs.getString("coba_zytcid"));// 智翼通公司编号
cbm.setCoba_zytwtcid(rs.getString("coba_zytwtcid"));// 智翼通委托公司编号
cbm.setCoba_developer(rs.getString("coba_developer"));// 开发人员
cbm.setCoba_gzautoemail(rs.getInt("coba_gzautoemail"));// 系统自动发送Email工资单(是or否)
cbm.setCoba_sign(rs.getInt("coba_sign"));// 是否国内注册
cbm.setCoba_invoice(rs.getString("coba_invoice"));
cbm.setCoba_taxmonth(rs.getString("coba_taxmonth"));// 是否上月个税(个税报表月份)
cbm.setCoba_gzaddname(rs.getString("coba_gzaddname"));// 薪酬负责人(添加人)
cbm.setCoba_gzaudname(rs.getString("coba_gzaudname"));// 薪酬审核人
cbm.setCoba_gzemailtype(rs.getInt("coba_gzemailtype"));// 判断电子工资单发放格式
cbm.setCoba_emfi_paydate(rs.getString("coba_emfi_paydate"));// 付款通知发放时间
cbm.setCoba_emfi_backdate(rs.getString("coba_emfi_backdate"));// 回款时间
cbm.setCoba_gz_paydate(rs.getString("coba_gz_paydate"));// 工资发放时间
cbm.setCoba_emailgz_paydate(rs
.getString("coba_emailgz_paydate"));// 电子工资单发放时间
cbm.setCoba_papergz_paydate(rs
.getString("coba_papergz_paydate"));// 纸质工资单发放时间
cbm.setCoba_emfics_backdate(rs
.getString("coba_emfics_backdate"));// 薪酬回款时间
cbm.setCoba_emfics_deldate(rs.getString("coba_emfics_deldate"));// 薪酬台账明细制作时间
cbm.setCoba_emfics_paydate(rs.getString("coba_emfics_paydate"));// 薪酬付款通知发放时间
cbm.setCoba_gzautoemaildays(rs.getInt("coba_gzautoemaildays"));// 工资发放后几天后自动发送Email工资单
// cbm.setPeopnum(rs.getInt("peopnum")); // 公司人数
cbm.setCoba_fpremark(rs.getString("coba_fpremark"));// 发票开票规则
// if (rs.getString("pactnum") == null
// || rs.getString("pactnum") == ""
// || rs.getString("pactnum").equals("")) {
// cbm.setCoconum("0");
// } else {
// cbm.setCoconum(rs.getString("pactnum")); // 合同数
// }
}
} catch (SQLException e) {
e.printStackTrace();
}
return cbm;
}
// 查询拥有福利项目的公司名单
public List<CoBaseModel> getcobaseFlList(String client) {
List<CoBaseModel> list = new ListModelList<>();
dbconn db = new dbconn();
String sql = "select cid,coba_company"
+ " from CoBase"
+ " where CID in ("
+ "select CID from CoCompact where coco_id in ("
+ "select coof_coco_id from CoOffer where coof_id in ("
+ "select coli_coof_id from CoOfferList where coli_state=1 and coli_pclass ='员工福利'))"
+ "and CID in ( select distinct cid from DataPopedom where log_id="
+ UserInfo.getUserid() + " and Dat_edited=1 )" + ")";
if (client != null && !client.equals("")) {
sql += " and coba_client='" + client + "'";
}
sql += " order by coba_company";
try {
list = db.find(sql, CoBaseModel.class, null);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
// 查询拥有福利项目的公司客服名单
public List<CoBaseModel> getClientFlList() {
List<CoBaseModel> list = new ListModelList<>();
dbconn db = new dbconn();
String sql = "select distinct coba_client"
+ " from CoBase"
+ " where CID in ("
+ "select CID from CoCompact where coco_id in ("
+ "select coof_coco_id from CoOffer where coof_id in ("
+ "select coli_coof_id from CoOfferList where coli_state=1 and coli_pclass ='员工福利'))"
+ "and CID in ( select cid from DataPopedom where log_id="
+ UserInfo.getUserid() + " and Dat_edited=1 )" + ")";
sql += " order by coba_client";
try {
list = db.find(sql, CoBaseModel.class, null);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
// 根据传入的查询条件查询公司,查询条件有cid请表明确cid所在的表
public List<CoBaseModel> getCobaseinfoforall(String sql) {
ResultSet rs = null;
List<CoBaseModel> cobaseinfo = new ArrayList<CoBaseModel>();
if (!cobaseinfo.isEmpty())
cobaseinfo.clear();
try {
dbconn db = new dbconn();
// String sqlstr = "SELECT * from cobase where 1=1 "+sql+"";
// sqlstr=sqlstr+" order by coba_servicestate desc,cid desc";
// String
// sqlstr="select a.*,peopnum,pactnum from CoBase a,(select cid,COUNT(*) peopnum from EmBase group by cid) b,";
// sqlstr=sqlstr+" (select cid ,count(*)pactnum from cocompact where cid >0 group by cid) c where a.CID=b.cid and a.CID=c.cid";
// sqlstr=sqlstr+sql;
String sqls = "select top 100 convert(nvarchar(10),coba_hzqsr,120) coba_hzqsr,"
+ "a.*,peopnum,pactnum,pronum from CoBase a left join (select cid,COUNT(*) peopnum "
+ "from EmBase where emba_state=1 group by cid) b";
sqls = sqls
+ " on a.cid=b.cid left join (select cid ,count(*) pactnum from cocompact where coco_state>3 and cid >0 group by cid) c on a.cid=c.cid"
+ " left join (select cid ,COUNT(*) pronum from CoBaseServePromise group by cid) d on a.CID=d.cid ";
sqls = sqls + " where 1=1" + sql;
sqls = sqls + " order by coba_servicestate desc,a.cid desc";
rs = db.GRS(sqls);
while (rs.next()) {
CoBaseModel model = new CoBaseModel();
model.setCid(rs.getInt("cid"));
model.setPronum(rs.getInt("pronum"));
model.setCoba_spell(rs.getString("coba_spell"));// 公司全称首字母
model.setCoba_company(rs.getString("coba_company"));// 公司全称
model.setCoba_shortspell(rs.getString("coba_shortspell"));// 简称首字母
model.setCoba_shortname(rs.getString("coba_shortname"));// 公司简称
model.setCoba_namespell(rs.getString("coba_namespell"));// 全称每个文字的首字母
model.setCoba_englishname(rs.getString("coba_englishname"));// 英文名
model.setCoba_country(rs.getString("coba_country"));// 所在国家
model.setCoba_setuptype(rs.getString("coba_setuptype"));// 公司类型
model.setCoba_servicearea(rs.getString("coba_servicearea"));// 服务区域
model.setCoba_servicestate(rs.getInt("coba_servicestate"));// 服务状态
model.setCoba_stopreason(rs.getString("coba_stopreason"));// 解约原因
model.setCoba_stopname(rs.getString("coba_stopname"));// 解约客服
model.setCoba_stopremark(rs.getString("coba_stopremark"));// 解约备注
model.setCoba_stoptime(rs.getString("coba_stoptime"));// 解约时间
model.setCoba_industytype(rs.getString("coba_industytype"));// 所属行业
model.setCoba_clientsize(rs.getString("coba_clientsize"));// 客户规模
model.setCoba_compacttype(rs.getString("coba_compacttype"));// 合同类型
if (rs.getInt("coba_vip") == 1) {
model.setCoba_vip("vip");
}
model.setCoba_addname(rs.getString("coba_addname"));
model.setCoba_address(rs.getString("Coba_address"));// 注册地址/办公地点
model.setCoba_area(rs.getString("coba_area"));// 公司位置/所在区域
model.setCoba_companymanager(rs
.getString("coba_companymanager"));// 法定代表人
model.setCoba_manageraddress(rs
.getString("coba_manageraddress"));// 法定代表人地址
model.setCoba_postcode(rs.getString("coba_postcode"));// 邮政编码
model.setCoba_website(rs.getString("coba_website"));// 公司网址
model.setCoba_clientsource(rs.getString("coba_clientsource"));// 客户来源
model.setCoba_client(rs.getString("coba_client"));// 客服
model.setCoba_manager(rs.getString("coba_manager"));// 客服经理
model.setCoba_clientmanager(rs.getString("coba_clientmanager"));// 客服部门经理
model.setCoba_hzqsr(rs.getString("coba_hzqsr"));// 合作起始日
model.setCoba_remark(rs.getString("coba_remark"));// 备注
model.setCoba_regagent(rs.getString("coba_regagent"));// 注册代理方
model.setCoba_reg_fund(rs.getString("coba_reg_fund"));// 注册资金
model.setCoba_certificate(rs.getString("coba_certificate"));// 证件类型
model.setCoba_bregdeadline(rs.getString("coba_bregdeadline"));// 工商登记到期日
model.setCoba_bregid(rs.getString("coba_bregid"));// 工商登记号
model.setCoba_regexpires(rs.getString("coba_regexpires"));// 驻在期限
model.setCoba_regtime(rs.getString("coba_regtime"));// 工商局登记时间
model.setCoba_reglimit(rs.getString("coba_reglimit"));// 工商登记证有效期
model.setCoba_organdeadline(rs.getString("coba_organdeadline"));// 组织机构到期日
model.setCoba_orregtime(rs.getString("coba_orregtime"));// 组织机构代码登记日期
model.setCoba_organcode(rs.getString("coba_organcode"));// 组织结构代码
model.setCoba_ntbank(rs.getString("coba_ntbank"));// 国税开户银行
model.setCoba_ntaccount(rs.getString("coba_ntaccount"));// 国税账号
model.setCoba_ntid(rs.getString("coba_ntid"));// 国税深字号
model.setCoba_ntregtime(rs.getString("coba_ntregtime"));// 国税登记日期
model.setCoba_ntlimit(rs.getString("coba_ntlimit"));// 国税有效期
model.setCoba_ntdeadline(rs.getString("coba_ntdeadline"));// 国税纳税有效期
model.setCoba_ltregid(rs.getString("coba_ltregid"));// 地税登记号
model.setCoba_ltregtime(rs.getString("coba_ltregtime"));// 地税登记时间
model.setCoba_ltlimit(rs.getString("coba_ltlimit"));// 地税有效期
model.setCoba_ltstate(rs.getString("coba_ltstate"));// 地税开户状态
model.setCoba_ltid(rs.getString("coba_ltid"));// 地税电脑号
model.setCoba_ltdeadline(rs.getString("coba_ltdeadline"));// 地税纳税期限
model.setCoba_ltbank(rs.getString("coba_ltbank"));// 地税开户银行
model.setCoba_ltaccount(rs.getString("coba_ltaccount"));// 地税账号
model.setCoba_gtstate(rs.getString("coba_gtstate"));// 个税开户状态
model.setCoba_gtbank(rs.getString("coba_gtbank"));// 个税开户行
model.setCoba_gtacc(rs.getString("coba_gtacc"));// 个税纳税账号
model.setCoba_gtto(rs.getString("coba_gtto"));// 所属税局
model.setCoba_gtdeadline(rs.getString("coba_gtdeadline"));// 个税申报截止日
model.setCoba_sistate(rs.getString("coba_sistate"));// 开户状态
model.setCoba_siiilimit(rs.getString("coba_siiilimit"));// 工伤比例
model.setCoba_sicoding(rs.getString("coba_sicoding"));// 单位编码
model.setCoba_sibank(rs.getString("coba_sibank"));// 开户行
model.setCoba_siaccount(rs.getString("coba_siaccount"));// 账户
model.setCoba_sihospital(rs.getString("coba_sihospital"));// 社康医疗机构
model.setCoba_sihosphone(rs.getString("coba_sihosphone"));// 社康电话
model.setCoba_sihosadd(rs.getString("coba_sihosadd"));// 社康地址
model.setCoba_dept(rs.getString("coba_dept"));
model.setCoba_regremark(rs.getString("coba_regremark"));// 公司注册信息备注
model.setCoba_addtime(rs.getString("coba_addtime"));// 公司信息添加时间
model.setCoba_addname(rs.getString("coba_addname"));// 公司信息添加人
model.setCoba_modtime(rs.getString("coba_modtime"));// 公司信息修改时间
model.setCoba_modname(rs.getString("coba_modname"));// 公司信息修改人
model.setCoba_shebaodeclare(rs.getString("coba_shebaodeclare"));
model.setCoba_ufid(rs.getString("coba_ufid"));// 收款中用到的用友编号
model.setCoba_ufid2(rs.getString("coba_ufid2"));// 社保和公积金台帐中用到的用友编号
model.setCoba_ufclass(rs.getString("coba_ufclass"));
model.setCoba_invoicerule(rs.getString("coba_invoicerule"));
model.setCoba_invoiceaddress(rs
.getString("coba_invoiceaddress"));// 发票邮寄地址
model.setCoba_wtco(rs.getString("coba_wtco"));
model.setCoba_regdataList(rs.getString("coba_regdataList"));// 注册信息-递交材料
model.setCoba_assistant(rs.getString("coba_assistant"));// 客服文员
model.setCoba_zytcid(rs.getString("coba_zytcid"));// 智翼通公司编号
model.setCoba_zytwtcid(rs.getString("coba_zytwtcid"));// 智翼通委托公司编号
model.setCoba_developer(rs.getString("coba_developer"));// 开发人员
model.setCoba_gzautoemail(rs.getInt("coba_gzautoemail"));// 系统自动发送Email工资单(是or否)
model.setCoba_sign(rs.getInt("coba_sign"));// 是否国内注册
model.setCoba_invoice(rs.getString("coba_invoice"));
model.setCoba_taxmonth(rs.getString("coba_taxmonth"));// 是否上月个税(个税报表月份)
model.setCoba_gzaddname(rs.getString("coba_gzaddname"));// 薪酬负责人(添加人)
model.setCoba_gzaudname(rs.getString("coba_gzaudname"));// 薪酬审核人
model.setCoba_gzemailtype(rs.getInt("coba_gzemailtype"));// 判断电子工资单发放格式
model.setCoba_emfi_paydate(rs.getString("coba_emfi_paydate"));// 付款通知发放时间
model.setCoba_emfi_backdate(rs.getString("coba_emfi_backdate"));// 回款时间
model.setCoba_gz_paydate(rs.getString("coba_gz_paydate"));// 工资发放时间
model.setCoba_emailgz_paydate(rs
.getString("coba_emailgz_paydate"));// 电子工资单发放时间
model.setCoba_papergz_paydate(rs
.getString("coba_papergz_paydate"));// 纸质工资单发放时间
model.setCoba_emfics_backdate(rs
.getString("coba_emfics_backdate"));// 薪酬回款时间
model.setCoba_emfics_deldate(rs
.getString("coba_emfics_deldate"));// 薪酬台账明细制作时间
model.setCoba_emfics_paydate(rs
.getString("coba_emfics_paydate"));// 薪酬付款通知发放时间
model.setCoba_gzautoemaildays(rs.getInt("coba_gzautoemaildays"));// 工资发放后几天后自动发送Email工资单
model.setPeopnum(rs.getInt("peopnum")); // 公司人数
model.setCoba_fpremark(rs.getString("coba_fpremark"));// 发票开票规则
if (rs.getString("pactnum") == null
|| rs.getString("pactnum") == ""
|| rs.getString("pactnum").equals("")) {
model.setCoconum("0");
} else {
model.setCoconum(rs.getString("pactnum")); // 合同数
}
cobaseinfo.add(model);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cobaseinfo;
}
// 根据传入的查询条件查询公司,查询条件有cid请表明确cid所在的表
public List<CoBaseModel> getCobaseinfo(String sql) {// all
ResultSet rs = null;
List<CoBaseModel> cobaseinfo = new ArrayList<CoBaseModel>();
if (!cobaseinfo.isEmpty())
cobaseinfo.clear();
try {
dbconn db = new dbconn();
// String sqlstr = "SELECT * from cobase where 1=1 "+sql+"";
// sqlstr=sqlstr+" order by coba_servicestate desc,cid desc";
// String
// sqlstr="select a.*,peopnum,pactnum from CoBase a,(select cid,COUNT(*) peopnum from EmBase group by cid) b,";
// sqlstr=sqlstr+" (select cid ,count(*)pactnum from cocompact where cid >0 group by cid) c where a.CID=b.cid and a.CID=c.cid";
// sqlstr=sqlstr+sql;
String sqls = "select convert(nvarchar(10),coba_hzqsr,120) coba_hzqsr,"
+ "a.*,peopnum,pactnum,pronum from CoBase a left join (select cid,COUNT(*) peopnum "
+ "from EmBase where emba_state=1 group by cid) b";
sqls = sqls
+ " on a.cid=b.cid left join (select cid ,count(*) pactnum from cocompact where coco_state>3 and cid >0 group by cid) c on a.cid=c.cid"
+ " left join (select cid ,COUNT(*) pronum from CoBaseServePromise group by cid) d on a.CID=d.cid ";
sqls = sqls + " where 1=1" + sql;
sqls = sqls
+ " and a.CID in ( select cid from DataPopedom where log_id="
+ UserInfo.getUserid() + " and dat_selected=1 )";
sqls = sqls + " order by coba_servicestate desc,a.cid desc";
System.out.println(sqls);
rs = db.GRS(sqls);
while (rs.next()) {
CoBaseModel model = new CoBaseModel();
model.setCid(rs.getInt("cid"));
model.setPronum(rs.getInt("pronum"));
model.setCoba_spell(rs.getString("coba_spell"));// 公司全称首字母
model.setCoba_company(rs.getString("coba_company"));// 公司全称
model.setCoba_shortspell(rs.getString("coba_shortspell"));// 简称首字母
model.setCoba_shortname(rs.getString("coba_shortname"));// 公司简称
model.setCoba_namespell(rs.getString("coba_namespell"));// 全称每个文字的首字母
model.setCoba_englishname(rs.getString("coba_englishname"));// 英文名
model.setCoba_country(rs.getString("coba_country"));// 所在国家
model.setCoba_setuptype(rs.getString("coba_setuptype"));// 公司类型
model.setCoba_servicearea(rs.getString("coba_servicearea"));// 服务区域
model.setCoba_servicestate(rs.getInt("coba_servicestate"));// 服务状态
model.setCoba_stopreason(rs.getString("coba_stopreason"));// 解约原因
model.setCoba_stopname(rs.getString("coba_stopname"));// 解约客服
model.setCoba_stopremark(rs.getString("coba_stopremark"));// 解约备注
model.setCoba_stoptime(rs.getString("coba_stoptime"));// 解约时间
model.setCoba_industytype(rs.getString("coba_industytype"));// 所属行业
model.setCoba_clientsize(rs.getString("coba_clientsize"));// 客户规模
model.setCoba_compacttype(rs.getString("coba_compacttype"));// 合同类型
if (rs.getInt("coba_vip") == 1) {
model.setCoba_vip("vip");
}
model.setCoba_addname(rs.getString("coba_addname"));
model.setCoba_address(rs.getString("Coba_address"));// 注册地址/办公地点
model.setCoba_area(rs.getString("coba_area"));// 公司位置/所在区域
model.setCoba_companymanager(rs
.getString("coba_companymanager"));// 法定代表人
model.setCoba_manageraddress(rs
.getString("coba_manageraddress"));// 法定代表人地址
model.setCoba_postcode(rs.getString("coba_postcode"));// 邮政编码
model.setCoba_website(rs.getString("coba_website"));// 公司网址
model.setCoba_clientsource(rs.getString("coba_clientsource"));// 客户来源
model.setCoba_client(rs.getString("coba_client"));// 客服
model.setCoba_manager(rs.getString("coba_manager"));// 客服经理
model.setCoba_clientmanager(rs.getString("coba_clientmanager"));// 客服部门经理
model.setCoba_hzqsr(rs.getString("coba_hzqsr"));// 合作起始日
model.setCoba_remark(rs.getString("coba_remark"));// 备注
model.setCoba_regagent(rs.getString("coba_regagent"));// 注册代理方
model.setCoba_reg_fund(rs.getString("coba_reg_fund"));// 注册资金
model.setCoba_certificate(rs.getString("coba_certificate"));// 证件类型
model.setCoba_bregdeadline(rs.getString("coba_bregdeadline"));// 工商登记到期日
model.setCoba_bregid(rs.getString("coba_bregid"));// 工商登记号
model.setCoba_regexpires(rs.getString("coba_regexpires"));// 驻在期限
model.setCoba_regtime(rs.getString("coba_regtime"));// 工商局登记时间
model.setCoba_reglimit(rs.getString("coba_reglimit"));// 工商登记证有效期
model.setCoba_organdeadline(rs.getString("coba_organdeadline"));// 组织机构到期日
model.setCoba_orregtime(rs.getString("coba_orregtime"));// 组织机构代码登记日期
model.setCoba_organcode(rs.getString("coba_organcode"));// 组织结构代码
model.setCoba_ntbank(rs.getString("coba_ntbank"));// 国税开户银行
model.setCoba_ntaccount(rs.getString("coba_ntaccount"));// 国税账号
model.setCoba_ntid(rs.getString("coba_ntid"));// 国税深字号
model.setCoba_ntregtime(rs.getString("coba_ntregtime"));// 国税登记日期
model.setCoba_ntlimit(rs.getString("coba_ntlimit"));// 国税有效期
model.setCoba_ntdeadline(rs.getString("coba_ntdeadline"));// 国税纳税有效期
model.setCoba_ltregid(rs.getString("coba_ltregid"));// 地税登记号
model.setCoba_ltregtime(rs.getString("coba_ltregtime"));// 地税登记时间
model.setCoba_ltlimit(rs.getString("coba_ltlimit"));// 地税有效期
model.setCoba_ltstate(rs.getString("coba_ltstate"));// 地税开户状态
model.setCoba_ltid(rs.getString("coba_ltid"));// 地税电脑号
model.setCoba_ltdeadline(rs.getString("coba_ltdeadline"));// 地税纳税期限
model.setCoba_ltbank(rs.getString("coba_ltbank"));// 地税开户银行
model.setCoba_ltaccount(rs.getString("coba_ltaccount"));// 地税账号
model.setCoba_gtstate(rs.getString("coba_gtstate"));// 个税开户状态
model.setCoba_gtbank(rs.getString("coba_gtbank"));// 个税开户行
model.setCoba_gtacc(rs.getString("coba_gtacc"));// 个税纳税账号
model.setCoba_gtto(rs.getString("coba_gtto"));// 所属税局
model.setCoba_gtdeadline(rs.getString("coba_gtdeadline"));// 个税申报截止日
model.setCoba_sistate(rs.getString("coba_sistate"));// 开户状态
model.setCoba_siiilimit(rs.getString("coba_siiilimit"));// 工伤比例
model.setCoba_sicoding(rs.getString("coba_sicoding"));// 单位编码
model.setCoba_sibank(rs.getString("coba_sibank"));// 开户行
model.setCoba_siaccount(rs.getString("coba_siaccount"));// 账户
model.setCoba_sihospital(rs.getString("coba_sihospital"));// 社康医疗机构
model.setCoba_sihosphone(rs.getString("coba_sihosphone"));// 社康电话
model.setCoba_sihosadd(rs.getString("coba_sihosadd"));// 社康地址
model.setCoba_dept(rs.getString("coba_dept"));
model.setCoba_regremark(rs.getString("coba_regremark"));// 公司注册信息备注
model.setCoba_addtime(rs.getString("coba_addtime"));// 公司信息添加时间
model.setCoba_addname(rs.getString("coba_addname"));// 公司信息添加人
model.setCoba_modtime(rs.getString("coba_modtime"));// 公司信息修改时间
model.setCoba_modname(rs.getString("coba_modname"));// 公司信息修改人
model.setCoba_shebaodeclare(rs.getString("coba_shebaodeclare"));
model.setCoba_ufid(rs.getString("coba_ufid"));// 收款中用到的用友编号
model.setCoba_ufid2(rs.getString("coba_ufid2"));// 社保和公积金台帐中用到的用友编号
model.setCoba_ufclass(rs.getString("coba_ufclass"));
model.setCoba_invoicerule(rs.getString("coba_invoicerule"));
model.setCoba_invoiceaddress(rs
.getString("coba_invoiceaddress"));// 发票邮寄地址
model.setCoba_wtco(rs.getString("coba_wtco"));
model.setCoba_regdataList(rs.getString("coba_regdataList"));// 注册信息-递交材料
model.setCoba_assistant(rs.getString("coba_assistant"));// 客服文员
model.setCoba_zytcid(rs.getString("coba_zytcid"));// 智翼通公司编号
model.setCoba_zytwtcid(rs.getString("coba_zytwtcid"));// 智翼通委托公司编号
model.setCoba_developer(rs.getString("coba_developer"));// 开发人员
model.setCoba_gzautoemail(rs.getInt("coba_gzautoemail"));// 系统自动发送Email工资单(是or否)
model.setCoba_sign(rs.getInt("coba_sign"));// 是否国内注册
model.setCoba_invoice(rs.getString("coba_invoice"));
model.setCoba_taxmonth(rs.getString("coba_taxmonth"));// 是否上月个税(个税报表月份)
model.setCoba_gzaddname(rs.getString("coba_gzaddname"));// 薪酬负责人(添加人)
model.setCoba_gzaudname(rs.getString("coba_gzaudname"));// 薪酬审核人
model.setCoba_gzemailtype(rs.getInt("coba_gzemailtype"));// 判断电子工资单发放格式
model.setCoba_emfi_paydate(rs.getString("coba_emfi_paydate"));// 付款通知发放时间
model.setCoba_emfi_backdate(rs.getString("coba_emfi_backdate"));// 回款时间
model.setCoba_gz_paydate(rs.getString("coba_gz_paydate"));// 工资发放时间
model.setCoba_emailgz_paydate(rs
.getString("coba_emailgz_paydate"));// 电子工资单发放时间
model.setCoba_papergz_paydate(rs
.getString("coba_papergz_paydate"));// 纸质工资单发放时间
model.setCoba_emfics_backdate(rs
.getString("coba_emfics_backdate"));// 薪酬回款时间
model.setCoba_emfics_deldate(rs
.getString("coba_emfics_deldate"));// 薪酬台账明细制作时间
model.setCoba_emfics_paydate(rs
.getString("coba_emfics_paydate"));// 薪酬付款通知发放时间
model.setCoba_gzautoemaildays(rs.getInt("coba_gzautoemaildays"));// 工资发放后几天后自动发送Email工资单
model.setPeopnum(rs.getInt("peopnum")); // 公司人数
model.setCoba_fpremark(rs.getString("coba_fpremark"));// 发票开票规则
if (rs.getString("pactnum") == null
|| rs.getString("pactnum") == ""
|| rs.getString("pactnum").equals("")) {
model.setCoconum("0");
} else {
model.setCoconum(rs.getString("pactnum")); // 合同数
}
model.setCoba_kind(rs.getString("coba_kind"));
model.setCoba_ifhasbribery(rs.getString("coba_ifhasbribery"));
cobaseinfo.add(model);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cobaseinfo;
}
// 获取客服列表
public List<CoBaseModel> getCobaseClient(String sql) {
ResultSet rs = null;
List<CoBaseModel> cobaseinfo = new ArrayList<CoBaseModel>();
if (!cobaseinfo.isEmpty())
cobaseinfo.clear();
try {
dbconn db = new dbconn();
String sqls = "select coba_client from cobase where coba_servicestate=1 and CID in(select cid from DataPopedom where log_id="
+ UserInfo.getUserid()
+ " and dat_selected=1) group by coba_client order by coba_client";
rs = db.GRS(sqls);
while (rs.next()) {
CoBaseModel model = new CoBaseModel();
model.setCoba_client(rs.getString("coba_client"));
cobaseinfo.add(model);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cobaseinfo;
}
// 根据传入的查询条件查询公司,查询条件有cid请表明确cid所在的表
public List<CoBaseModel> getCobaseeditinfo(String sql) {// 所有
ResultSet rs = null;
List<CoBaseModel> cobaseinfo = new ArrayList<CoBaseModel>();
if (!cobaseinfo.isEmpty())
cobaseinfo.clear();
try {
dbconn db = new dbconn();
String sqls = "select a.*,peopnum,pactnum,pronum from CoBase a left join (select cid,COUNT(*) peopnum from EmBase where emba_state=1 group by cid) b";
sqls = sqls
+ " on a.cid=b.cid left join (select cid ,count(*)pactnum from cocompact where cid >0 group by cid) c on a.cid=c.cid"
+ " left join (select cid ,COUNT(*) pronum from CoBaseServePromise group by cid) d on a.CID=d.cid ";
sqls = sqls + " where 1=1" + sql;
sqls = sqls
+ " and a.CID in ( select cid from DataPopedom where log_id="
+ UserInfo.getUserid() + " and Dat_edited=1 )";
sqls = sqls + " order by coba_servicestate desc,a.cid desc";
rs = db.GRS(sqls);
while (rs.next()) {
CoBaseModel model = new CoBaseModel();
model.setCid(rs.getInt("cid"));
model.setPronum(rs.getInt("pronum"));
model.setCoba_spell(rs.getString("coba_spell"));// 公司全称首字母
model.setCoba_company(rs.getString("coba_company"));// 公司全称
model.setCoba_shortspell(rs.getString("coba_shortspell"));// 简称首字母
model.setCoba_shortname(rs.getString("coba_shortname"));// 公司简称
model.setCoba_namespell(rs.getString("coba_namespell"));// 全称每个文字的首字母
model.setCoba_englishname(rs.getString("coba_englishname"));// 英文名
model.setCoba_country(rs.getString("coba_country"));// 所在国家
model.setCoba_setuptype(rs.getString("coba_setuptype"));// 公司类型
model.setCoba_servicearea(rs.getString("coba_servicearea"));// 服务区域
model.setCoba_servicestate(rs.getInt("coba_servicestate"));// 服务状态
model.setCoba_stopreason(rs.getString("coba_stopreason"));// 解约原因
model.setCoba_stopname(rs.getString("coba_stopname"));// 解约客服
model.setCoba_stopremark(rs.getString("coba_stopremark"));// 解约备注
model.setCoba_stoptime(rs.getString("coba_stoptime"));// 解约时间
model.setCoba_industytype(rs.getString("coba_industytype"));// 所属行业
model.setCoba_clientsize(rs.getString("coba_clientsize"));// 客户规模
model.setCoba_compacttype(rs.getString("coba_compacttype"));// 合同类型
model.setCoba_assistant(rs.getString("coba_assistant"));//员服
if (rs.getInt("coba_vip") == 1) {
model.setCoba_vip("vip");
}
model.setCoba_addname(rs.getString("coba_addname"));
model.setCoba_address(rs.getString("Coba_address"));// 注册地址/办公地点
model.setCoba_area(rs.getString("coba_area"));// 公司位置/所在区域
model.setCoba_companymanager(rs
.getString("coba_companymanager"));// 法定代表人
model.setCoba_manageraddress(rs
.getString("coba_manageraddress"));// 法定代表人地址
model.setCoba_postcode(rs.getString("coba_postcode"));// 邮政编码
model.setCoba_website(rs.getString("coba_website"));// 公司网址
model.setCoba_clientsource(rs.getString("coba_clientsource"));// 客户来源
model.setCoba_client(rs.getString("coba_client"));// 客服
model.setCoba_manager(rs.getString("coba_manager"));// 客服经理
model.setCoba_clientmanager(rs.getString("coba_clientmanager"));// 客服部门经理
model.setCoba_hzqsr(rs.getString("coba_hzqsr"));// 合作起始日
model.setCoba_remark(rs.getString("coba_remark"));// 备注
model.setCoba_regagent(rs.getString("coba_regagent"));// 注册代理方
model.setCoba_reg_fund(rs.getString("coba_reg_fund"));// 注册资金
model.setCoba_certificate(rs.getString("coba_certificate"));// 证件类型
model.setCoba_bregdeadline(rs.getString("coba_bregdeadline"));// 工商登记到期日
model.setCoba_bregid(rs.getString("coba_bregid"));// 工商登记号
model.setCoba_regexpires(rs.getString("coba_regexpires"));// 驻在期限
model.setCoba_regtime(rs.getString("coba_regtime"));// 工商局登记时间
model.setCoba_reglimit(rs.getString("coba_reglimit"));// 工商登记证有效期
model.setCoba_organdeadline(rs.getString("coba_organdeadline"));// 组织机构到期日
model.setCoba_orregtime(rs.getString("coba_orregtime"));// 组织机构代码登记日期
model.setCoba_organcode(rs.getString("coba_organcode"));// 组织结构代码
model.setCoba_ntbank(rs.getString("coba_ntbank"));// 国税开户银行
model.setCoba_ntaccount(rs.getString("coba_ntaccount"));// 国税账号
model.setCoba_ntid(rs.getString("coba_ntid"));// 国税深字号
model.setCoba_ntregtime(rs.getString("coba_ntregtime"));// 国税登记日期
model.setCoba_ntlimit(rs.getString("coba_ntlimit"));// 国税有效期
model.setCoba_ntdeadline(rs.getString("coba_ntdeadline"));// 国税纳税有效期
model.setCoba_ltregid(rs.getString("coba_ltregid"));// 地税登记号
model.setCoba_ltregtime(rs.getString("coba_ltregtime"));// 地税登记时间
model.setCoba_ltlimit(rs.getString("coba_ltlimit"));// 地税有效期
model.setCoba_ltstate(rs.getString("coba_ltstate"));// 地税开户状态
model.setCoba_ltid(rs.getString("coba_ltid"));// 地税电脑号
model.setCoba_ltdeadline(rs.getString("coba_ltdeadline"));// 地税纳税期限
model.setCoba_ltbank(rs.getString("coba_ltbank"));// 地税开户银行
model.setCoba_ltaccount(rs.getString("coba_ltaccount"));// 地税账号
model.setCoba_gtstate(rs.getString("coba_gtstate"));// 个税开户状态
model.setCoba_gtbank(rs.getString("coba_gtbank"));// 个税开户行
model.setCoba_gtacc(rs.getString("coba_gtacc"));// 个税纳税账号
model.setCoba_gtto(rs.getString("coba_gtto"));// 所属税局
model.setCoba_gtdeadline(rs.getString("coba_gtdeadline"));// 个税申报截止日
model.setCoba_sistate(rs.getString("coba_sistate"));// 开户状态
model.setCoba_siiilimit(rs.getString("coba_siiilimit"));// 工伤比例
model.setCoba_sicoding(rs.getString("coba_sicoding"));// 单位编码
model.setCoba_sibank(rs.getString("coba_sibank"));// 开户行
model.setCoba_siaccount(rs.getString("coba_siaccount"));// 账户
model.setCoba_sihospital(rs.getString("coba_sihospital"));// 社康医疗机构
model.setCoba_sihosphone(rs.getString("coba_sihosphone"));// 社康电话
model.setCoba_sihosadd(rs.getString("coba_sihosadd"));// 社康地址
model.setCoba_dept(rs.getString("coba_dept"));
model.setCoba_regremark(rs.getString("coba_regremark"));// 公司注册信息备注
model.setCoba_addtime(rs.getString("coba_addtime"));// 公司信息添加时间
model.setCoba_addname(rs.getString("coba_addname"));// 公司信息添加人
model.setCoba_modtime(rs.getString("coba_modtime"));// 公司信息修改时间
model.setCoba_modname(rs.getString("coba_modname"));// 公司信息修改人
model.setCoba_shebaodeclare(rs.getString("coba_shebaodeclare"));
model.setCoba_ufid(rs.getString("coba_ufid"));// 收款中用到的用友编号
model.setCoba_ufid2(rs.getString("coba_ufid2"));// 社保和公积金台帐中用到的用友编号
model.setCoba_ufclass(rs.getString("coba_ufclass"));
model.setCoba_invoicerule(rs.getString("coba_invoicerule"));
model.setCoba_invoiceaddress(rs
.getString("coba_invoiceaddress"));// 发票邮寄地址
model.setCoba_wtco(rs.getString("coba_wtco"));
model.setCoba_regdataList(rs.getString("coba_regdataList"));// 注册信息-递交材料
model.setCoba_assistant(rs.getString("coba_assistant"));// 客服文员
model.setCoba_zytcid(rs.getString("coba_zytcid"));// 智翼通公司编号
model.setCoba_zytwtcid(rs.getString("coba_zytwtcid"));// 智翼通委托公司编号
model.setCoba_developer(rs.getString("coba_developer"));// 开发人员
model.setCoba_gzautoemail(rs.getInt("coba_gzautoemail"));// 系统自动发送Email工资单(是or否)
model.setCoba_sign(rs.getInt("coba_sign"));// 是否国内注册
model.setCoba_invoice(rs.getString("coba_invoice"));
model.setCoba_taxmonth(rs.getString("coba_taxmonth"));// 是否上月个税(个税报表月份)
model.setCoba_gzaddname(rs.getString("coba_gzaddname"));// 薪酬负责人(添加人)
model.setCoba_gzaudname(rs.getString("coba_gzaudname"));// 薪酬审核人
model.setCoba_gzemailtype(rs.getInt("coba_gzemailtype"));// 判断电子工资单发放格式
model.setCoba_emfi_paydate(rs.getString("coba_emfi_paydate"));// 付款通知发放时间
model.setCoba_emfi_backdate(rs.getString("coba_emfi_backdate"));// 回款时间
model.setCoba_gz_paydate(rs.getString("coba_gz_paydate"));// 工资发放时间
model.setCoba_emailgz_paydate(rs
.getString("coba_emailgz_paydate"));// 电子工资单发放时间
model.setCoba_papergz_paydate(rs
.getString("coba_papergz_paydate"));// 纸质工资单发放时间
model.setCoba_emfics_backdate(rs
.getString("coba_emfics_backdate"));// 薪酬回款时间
model.setCoba_emfics_deldate(rs
.getString("coba_emfics_deldate"));// 薪酬台账明细制作时间
model.setCoba_emfics_paydate(rs
.getString("coba_emfics_paydate"));// 薪酬付款通知发放时间
model.setCoba_gzautoemaildays(rs.getInt("coba_gzautoemaildays"));// 工资发放后几天后自动发送Email工资单
model.setPeopnum(rs.getInt("peopnum")); // 公司人数
if (rs.getString("pactnum") == null
|| rs.getString("pactnum") == ""
|| rs.getString("pactnum").equals("")) {
model.setCoconum("0");
} else {
model.setCoconum(rs.getString("pactnum")); // 合同数
}
model.setCoba_kind(rs.getString("coba_kind"));
model.setCoba_ifhasbribery(rs.getString("coba_ifhasbribery"));
model.setCoba_fpremark(rs.getString("coba_fpremark"));// 发票开票规则
model.setCoba_regaccount(rs.getString("coba_regaccount"));
model.setCoba_regaccountpwd(rs.getString("coba_regaccountpwd"));
cobaseinfo.add(model);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return cobaseinfo;
}
/**
* @Title: getCobaseByClient
* @Description: TODO(根据客服查询公司列表)
* @param client
* @return
* @throws SQLException
* @return List<CoBaseModel> 返回类型
* @throws
*/
public List<CoBaseModel> getCobaseByClient(String client, String name)
throws SQLException {
List<CoBaseModel> list = new ListModelList<CoBaseModel>();
dbconn db = new dbconn();
name = name.equals("") ? "%" : name + "%";
client = client.equals("") ? "%" : client.equals("全部") ? "%" : client;
String sql = "select distinct top 10 cid ,'[ '+coba_spell+' ]' + coba_company coba_shortname, coba_company from cobase where coba_serviceState=1 and cid in (select distinct cid from embase where emba_state=1) and coba_client like ? and (coba_company like ? or coba_shortname like ? or cid like ? or coba_namespell like ?) order by coba_company";
list = db.find(sql, CoBaseModel.class,
dbconn.parseSmap(CoBaseModel.class), client, name, name, name,
name);
return list;
}
public List<CoBaseModel> getCoBaseInfo(CoBaseModel cm, String columns,
Boolean disinct, Integer topNum, String order) {
List<CoBaseModel> list = new ListModelList<>();
dbconn db = new dbconn();
String sql = "select ";
if (disinct != null && disinct) {
sql = sql + "distinct ";
}
if (topNum != null && !topNum.equals("")) {
sql = sql + "top " + topNum + " ";
}
if (columns != null && !columns.equals("")) {
sql = sql + columns + " ";
} else {
sql = sql
+ " cid,coba_company,coba_shortname,coba_client,coba_invoicerule,coba_industytype";
}
sql = sql + " from cobase where 1=1";
if (cm != null) {
if (cm.isFuzzy()) {
sql = sql + " and (";
if (cm.getCoba_company() != null) {
sql = sql + "cid like '" + cm.getCoba_company()
+ "%' or coba_shortname like '%"
+ cm.getCoba_company()
+ "%' or coba_company like '%"
+ cm.getCoba_company() + "%'"
+ " or coba_namespell like '%"
+ cm.getCoba_company() + "%'";
}
sql = sql + ")";
} else {
if (cm.getCid() != null) {
sql = sql + " and cid=" + cm.getCid();
}
}
if (cm.getCoba_client() != null && !cm.getCoba_client().equals("")) {
sql = sql + " and coba_client='" + cm.getCoba_client() + "'";
}
if (cm.getCoba_servicestate() > 0) {
sql = sql + " and coba_servicestate="
+ cm.getCoba_servicestate();
}
}
if (order != null && !order.equals("")) {
sql += " order by " + order;
} else {
sql = sql + " order by coba_client,coba_company";
}
try {
list = db.find(sql, CoBaseModel.class, null);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public String[] getcobaList() {
StringBuilder spstr = new StringBuilder();
dbconn db = new dbconn();
try {
ResultSet rs = db.GRS("SELECT top 500 * from cobase where 1=1");
while (rs.next()) {
spstr.append(rs.getString("coba_namespell") + "|"
+ rs.getInt("cid") + "|"
+ rs.getString("coba_shortname") + "|"
+ rs.getString("coba_client"));
spstr.append(",");
}
} catch (Exception e) {
System.out.println(e.toString());
}
return spstr.toString().split(",");
}
/**
* @Title: getClient
* @Description: TODO(查询客服列表)
* @return
* @throws SQLException
* @return List<CoBaseModel> 返回类型
* @throws
*/
public List<CoBaseModel> getClient() {
List<CoBaseModel> list = new ListModelList<CoBaseModel>();
dbconn db = new dbconn();
String sql = "select '全部' coba_client,0 sort union all select distinct coba_client,1 from cobase where coba_serviceState=1 and cid in (select distinct cid from embase where emba_state=1) order by sort,coba_client";
try {
list = db.find(sql, CoBaseModel.class,
dbconn.parseSmap(CoBaseModel.class));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public List<CoBaseModel> getCobase(String str) throws SQLException {
ResultSet rs = null;
List<CoBaseModel> cobaseinfo = new ArrayList<CoBaseModel>();
if (!cobaseinfo.isEmpty())
cobaseinfo.clear();
try {
dbconn db = new dbconn();
String sqls = "select * FROM cobase WHERE 1=1 " + str
+ " order by coba_servicestate desc,coba_shortname";
rs = db.GRS(sqls);
while (rs.next()) {
CoBaseModel model = new CoBaseModel();
model.setCid(rs.getInt("cid"));
model.setCoba_spell(rs.getString("coba_spell"));// 公司全称首字母
model.setCoba_company(rs.getString("coba_company"));// 公司全称
model.setCoba_shortspell(rs.getString("coba_shortspell"));// 简称首字母
model.setCoba_shortname(rs.getString("coba_shortname"));// 公司简称
model.setCoba_namespell(rs.getString("coba_namespell"));// 全称每个文字的首字母
model.setCoba_englishname(rs.getString("coba_englishname"));// 英文名
model.setCoba_client(rs.getString("coba_client"));// 客服
model.setCoba_manager(rs.getString("coba_manager"));// 客服经理
model.setCoba_clientmanager(rs.getString("coba_clientmanager"));// 客服部门经理
model.setCoba_gzautoemail(rs.getInt("coba_gzautoemail"));// 系统自动发送Email工资单(是or否)
model.setCoba_taxmonth(rs.getString("coba_taxmonth"));// 是否上月个税(个税报表月份)
model.setCoba_gzaddname(rs.getString("coba_gzaddname"));// 薪酬负责人(添加人)
model.setCoba_gzaudname(rs.getString("coba_gzaudname"));// 薪酬审核人
model.setCoba_gzemailtype(rs.getInt("coba_gzemailtype"));// 判断电子工资单发放格式
model.setCoba_emfi_paydate(rs.getString("coba_emfi_paydate"));// 付款通知发放时间
model.setCoba_emfi_backdate(rs.getString("coba_emfi_backdate"));// 回款时间
model.setCoba_gz_paydate(rs.getString("coba_gz_paydate"));// 工资发放时间
model.setCoba_kind(rs.getString("coba_kind"));
model.setCoba_ifhasbribery(rs.getString("coba_ifhasbribery"));
model.setCoba_fpremark(rs.getString("coba_fpremark"));// 发票开票规则
cobaseinfo.add(model);
}
} catch (Exception e) {
e.printStackTrace();
}
return cobaseinfo;
}
// 根据CID查询客服
public List<CoBaseModel> getInfoByCid(Integer cid) throws SQLException {
List<CoBaseModel> list = new ListModelList<CoBaseModel>();
dbconn db = new dbconn();
String sql = "select log_id,coba_client from cobase a inner join login b on a.coba_client=b.log_name where cid=?";
list = db.find(sql, CoBaseModel.class,
dbconn.parseSmap(CoBaseModel.class), cid);
return list;
}
// 根据GID查询客服
public List<CoBaseModel> getInfoByGid(Integer gid) throws SQLException {
List<CoBaseModel> list = new ListModelList<CoBaseModel>();
dbconn db = new dbconn();
String sql = "select log_id,coba_client from cobase a inner join login b on a.coba_client=b.log_name where cid in (select cid from embase where gid=?)";
list = db.find(sql, CoBaseModel.class,
dbconn.parseSmap(CoBaseModel.class), gid);
return list;
}
// 查询公司列表
public List<CoBaseModel> getInfoListByName(String name) {
List<CoBaseModel> list = new ListModelList<CoBaseModel>();
dbconn db = new dbconn();
StringBuilder sql = new StringBuilder();
name = name.equals("") ? "%" + name + "%" : name;
sql.append("select top 10 cid,UPPER(coba_spell)coba_spell,coba_company,coba_shortname,coba_client from cobase");
sql.append(" where cid like ? or coba_company like ? or coba_shortname like ? or coba_englishname like ? or coba_namespell like ?");
sql.append(" order by coba_company");
try {
list = db.find(sql.toString(), CoBaseModel.class,
dbconn.parseSmap(CoBaseModel.class), name, name, name,
name, name);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
// 查询独立户公司列表
public List<CoBaseModel> getsingleListByName(String name) {
List<CoBaseModel> list = new ListModelList<CoBaseModel>();
dbconn db = new dbconn();
String sql = "select a.cid,UPPER(coba_spell)coba_spell,coba_company,coba_shortname,coba_client,cohf_houseid "
+ "from cobase a "
+ "inner join CoHousingFund b on a.cid=b.cid "
+ "where (a.cid like ? or coba_company like ? or coba_shortname like ? or coba_englishname like ? or coba_namespell like ?) "
+ "and coba_serviceState=1 and cohf_state=1 "
+ "order by coba_company";
System.out.println(sql);
System.out.println(name);
try {
list = db.find(sql, CoBaseModel.class, null, name, name, name,
name, name);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
// 查询公司列表(体检)
public List<CoBaseModel> getcompanyList(String name) {
List<CoBaseModel> list = new ListModelList<>();
dbconn db = new dbconn();
String sql = "select a.cid,'['+UPPER(coba_spell)+']'+coba_company coba_company,coba_shortname "
+ "from cobase a "
+ "inner join ("
+ " select distinct a.cid from cocompact a"
+ " inner join cooffer b on a.coco_id=b.coof_coco_id"
+ " inner join coofferlist c on b.coof_id=c.coli_coof_id"
+ " where (coli_name like '%体检%' or coli_name like '中智_类' or coli_pclass like '%体检%') and coco_state>3 and coof_state=3 and coli_stoptime is null"
+ ")b on a.cid=b.cid"
+ " where coba_servicestate=1 and a.cid in ("
+ "select cid from DataPopedom a inner join login b on a.log_id=b.log_id"
+ " where b.log_name=?" + ") ";
sql = sql + " order by coba_company";
System.out.println(sql);
try {
list = db.find(sql, CoBaseModel.class, null, name);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
// 查询公司列表(体检)
public List<CoBaseModel> getcompanyEmbodyList(String name) {
List<CoBaseModel> list = new ListModelList<>();
dbconn db = new dbconn();
String sql = "select a.cid,'['+UPPER(coba_spell)+']'+coba_company coba_company,coba_shortname "
+ "from cobase a "
+ " where coba_servicestate=1 and a.cid in ("
+ "select cid from DataPopedom a inner join login b on a.log_id=b.log_id"
+ " where b.log_name=?" + ") and coba_client=? ";
sql = sql + " order by coba_company";
try {
list = db.find(sql, CoBaseModel.class, null, name, name);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public List<CoCompactModel> getcompactList(Integer cid) {
List<CoCompactModel> list = new ListModelList<>();
dbconn db = new dbconn();
String sql = "select coco_id,cid cid2,coco_compactid,coco_compacttype"
+ " from CoCompact where cid=? and coco_state>3";
try {
list = db.find(sql, CoCompactModel.class, null, cid);
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public List<CoCompactModel> getcompactLists(Integer cid) {
List<CoCompactModel> list = new ListModelList<>();
dbconn db = new dbconn();
String sql = "select coco_id,cid cid2,coco_compactid,coco_compacttype"
+ " from CoCompact where cid=?";
try {
list = db.find(sql, CoCompactModel.class, null, cid);
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public List<CoOfferModel> getcoofferList(String str) {
List<CoOfferModel> list = new ListModelList<>();
dbconn db = new dbconn();
String sql = "select coof_id,coof_name,coof_cpct_id,coof_quotemode,coof_quotetime,"
+ "coof_auditing_name,coof_auditing_time,coof_state,coof_filename,coof_addname,"
+ "coof_addtime,coof_modname,coof_modtime,coof_remark,coof_tali_id,coof_register,"
+ "coof_cola_id,b.cid,coof_coco_id,coof_min,coof_max,coof_gm,coof_sum,"
+ "convert(nvarchar(10),coof_addtime,120)addtime,coco_compactid"
+ " from CoOffer a left join (select cid,coco_id,coco_compactid from CoCompact)b"
+ " on a.coof_coco_id=b.coco_id where coof_state=3" + str;
System.out.print(sql);
try {
list = db.find(sql, CoOfferModel.class, null);
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public List<CoOfferModel> getEmbaseList(String str) {
List<CoOfferModel> list = new ListModelList<>();
dbconn db = new dbconn();
String sql = "select distinct a.gid,b.emba_name from CoGList a left join (select gid,emba_name from EmBase)b on a.gid=b.gid"
+ " left join (select coli_id,coli_coof_id from CoOfferList)c on a.cgli_coli_id=c.coli_id"
+ " left join (select coof_id from CoOffer)d on c.coli_coof_id=d.coof_id"
+ " where cgli_state=1 and cgli_stopdate is null" + str;
try {
list = db.find(sql, CoOfferModel.class, null);
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
// 根据查询客户的第一份合同生效时间
public Date getCocoInuredate(Integer cid) {
String sql = "select coco_inuredate,* from CoCompact where cid=" + cid
+ " order by coco_id desc";
Date date = null;
try {
dbconn db = new dbconn();
ResultSet rs = db.GRS(sql);
while (rs.next()) {
date = rs.getDate("coco_inuredate");
}
} catch (Exception e) {
}
return date;
}
// 查询用友编号
public List<CoBaseModel> getUid(Integer cid) {
List<CoBaseModel> list = new ListModelList<>();
dbconn db = new dbconn();
String sql = "select cid,coba_ufid,"
+ "case when b.cpac_id>0 then 'AF' when C.cpac_id>0 then 'FS' END compacttype "
+ " from cobase a"
+ " left join CoPAccount b on a.coba_ufclass=b.cpac_af "
+ " left join CoPAccount c on a.coba_ufclass=c.cpac_fs"
+ " where a.cid=?";
try {
list = db.find(sql, CoBaseModel.class, null, cid);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
}
| true
|
1bde82366bf3e3ba6eedc22bb9a32c8f99bb5db4
|
Java
|
camelcc/leetcode
|
/src/S1416RestoreTheArray.java
|
UTF-8
| 1,010
| 2.96875
| 3
|
[] |
no_license
|
import java.util.Arrays;
public class S1416RestoreTheArray {
public int numberOfArrays(String s, int k) {
int[] dp = new int[s.length()];
Arrays.fill(dp, -1);
return dp(s, k, 0, dp);
}
private int dp(String s, int k, int index, int[] dp) {
if (dp[index] != -1) {
return dp[index];
}
if (s.charAt(index) == '0') {
dp[index] = 0;
return 0;
}
if (index == s.length()-1) {
dp[index] = s.charAt(index)-'0' > k ? 0 : 1;
return dp[index];
}
long res = 0;
int MOD = (int)(Math.pow(10, 9)+7);
int end = index+1;
while (end <= s.length() && Long.parseLong(s, index, end, 10) <= k) {
if (end == s.length()) {
res++;
} else {
res += dp(s, k, end, dp);
}
res = res%MOD;
end++;
}
dp[index] = (int)res;
return dp[index];
}
}
| true
|
d35f4a75c0661573280bf681488806cfaf83eff0
|
Java
|
smarr/AmbientTalk-interpreter
|
/src/edu/vub/at/objects/natives/grammar/AGAssignmentSymbol.java
|
UTF-8
| 3,587
| 2.296875
| 2
|
[] |
no_license
|
/**
* AmbientTalk/2 Project
* AGAssignmentSymbol.java created on 2-jul-2007 at 13:45:32
* (c) Programming Technology Lab, 2006 - 2007
* Authors: Tom Van Cutsem & Stijn Mostinckx
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package edu.vub.at.objects.natives.grammar;
import edu.vub.at.exceptions.InterpreterException;
import edu.vub.at.exceptions.XIllegalOperation;
import edu.vub.at.objects.ATContext;
import edu.vub.at.objects.ATObject;
import edu.vub.at.objects.ATText;
import edu.vub.at.objects.grammar.ATAssignmentSymbol;
import edu.vub.at.objects.grammar.ATSymbol;
import edu.vub.at.objects.natives.NATText;
import edu.vub.util.TempFieldGenerator;
/**
* An assignment symbol is created by suffixing an ordinary symbol with a :=. It can be created
* explicitly through qutoting and is created when assigning a field at base-level to map such
* assignments onto a method invocation. Also it can be created when explicitly defining accessor
* methods.
*
* @author smostinc
*/
public class AGAssignmentSymbol extends AGSymbol implements ATAssignmentSymbol {
/**
* @param name a string with a ':=' suffix
*/
public static AGSymbol jAlloc(String name) {
synchronized (_STRINGPOOL_) {
AGSymbol existing = (AGSymbol) _STRINGPOOL_.get(name);
if (existing == null) {
existing = new AGAssignmentSymbol(name);
_STRINGPOOL_.put(name, existing);
}
return existing;
}
}
protected AGAssignmentSymbol(String txt) {
// cut the := part of the symbol name, e.g. foo:= -> foo
super(txt.substring(0,txt.length()-2));
}
public boolean isAssignmentSymbol() {
return true;
}
public AGAssignmentSymbol asAssignmentSymbol() {
return this;
}
public ATText base_text() {
return NATText.atValue(toString());
}
/**
* It is illegal to evaluate an assignment symbol in base-level code
*/
public ATObject meta_eval(ATContext ctx) throws InterpreterException {
throw new XIllegalOperation("Cannot evaluate an assignment symbol as an ordinary symbol");
}
public NATText meta_print() {
return NATText.atValue(toString());
}
public NATText impl_asCode(TempFieldGenerator objectMap) throws InterpreterException {
return NATText.atValue(toString());
}
public ATObject meta_resolve() throws InterpreterException {
return AGAssignmentSymbol.jAlloc(toString());
}
public String toString() {
return super.toString() + ":=";
}
/**
* @return the field name being assigned by this assignment symbol
*/
public ATSymbol base_fieldName() {
return AGSymbol.jAlloc(super.toString());
}
}
| true
|
5c641202f9702dd6de21f074ce94c6a2e076ff0a
|
Java
|
wardatulhisaniah/IntentRegistrasiMahasiswa
|
/app/src/main/java/id/ac/poliban/mi/atul/intentregistrasimahasiswa/activity_data_mahasiswa.java
|
UTF-8
| 1,297
| 1.976563
| 2
|
[] |
no_license
|
package id.ac.poliban.mi.atul.intentregistrasimahasiswa;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
public class activity_data_mahasiswa extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_mahasiswa);
EditText etnim = findViewById(R.id.etNim);
EditText etnama = findViewById(R.id.etNama);
EditText etAlamat = findViewById(R.id.etAlamat);
EditText ettelp = findViewById(R.id.etTelp);
Button btSend = findViewById(R.id.btSend);
btSend.setOnClickListener(v -> {
Intent intent = new Intent();
intent.putExtra("nama", etnama.getText().toString());
intent.putExtra("nim", etnim.getText().toString());
intent.putExtra("alamat", etAlamat.getText().toString());
intent.putExtra("telp", ettelp.getText().toString());
setResult(RESULT_OK, intent);
finish();
});
if(getSupportActionBar() != null)
getSupportActionBar().setTitle("Input Data");
}
}
| true
|
4411dfd99441832b255cecd53ad5e265b5a8c108
|
Java
|
forestbaba/shop-spring
|
/src/main/java/com/forestsoftware/usershop/service/UserService.java
|
UTF-8
| 3,598
| 2.109375
| 2
|
[] |
no_license
|
package com.forestsoftware.usershop.service;
import com.forestsoftware.usershop.exceptions.EmailAlreadyExistException;
import com.forestsoftware.usershop.exceptions.PhoneAlreadyExistException;
import com.forestsoftware.usershop.model.ERole;
import com.forestsoftware.usershop.model.Role;
import com.forestsoftware.usershop.model.User;
import com.forestsoftware.usershop.model.request.SignupRequest;
import com.forestsoftware.usershop.repository.RoleRepository;
import com.forestsoftware.usershop.repository.UserRepository;
import com.forestsoftware.usershop.utility.Workerclass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
private Workerclass workerclass;
@Autowired
private RoleRepository roleRepository;
public User createUser(User user, SignupRequest signupRequest){
userRepository.findByEmail(signupRequest.getEmail());
try {
user.setEmail(signupRequest.getEmail());
user.setFirstname(signupRequest.getFirstname());
user.setLastname(signupRequest.getLastname());
user.setPassword(bCryptPasswordEncoder.encode(signupRequest.getPassword()));
user.setImageUrl(workerclass.getGravatar80pxUrl(signupRequest.getEmail()));
user.setApiKey(workerclass.randomString(50));
// user.setRoles(getUserRole(user, signupRequest));
return userRepository.save(user);
}catch (EmailAlreadyExistException e){
throw new EmailAlreadyExistException("Email '"+user.getEmail()+" ' already exist");
}catch(NullPointerException ex){
System.out.println("ERR: ====="+ex.getCause());
throw new EmailAlreadyExistException("Email '"+user.getEmail()+" ' already exist");
}
}
public Set<Role>getUserRole(User user, SignupRequest signupRequest){
Set<String> stRoles = signupRequest.getRole();
Set<Role> roles = new HashSet<>();
if(user.getRoles() == null){
Role role = roleRepository.findByName(ERole.ROLE_USER)
.orElseThrow(() -> new NullPointerException("Error: Role is not found"));
System.out.println("MMM; "+role);
roles.add(role);
}else {
stRoles.forEach(role -> {
switch (role) {
case "admin":
Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN).orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(adminRole);
break;
case "mod":
Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR).orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(modRole);
break;
default:
Role roleanon = roleRepository.findByName(ERole.ROLE_USER).orElseThrow(() -> new RuntimeException("Error: Role not found"));
roles.add(roleanon);
}
});
}
// user.setRoles(roles);
return roles;
}
}
| true
|
2806f9f01f8ed7fd130dcf7aaee93cf81b443371
|
Java
|
GroupJ/SIMS
|
/src/IO/ListIO.java
|
UTF-8
| 2,760
| 2.9375
| 3
|
[] |
no_license
|
/*
* This file is part of S:SIMS.
*
* S:SIMS 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.
*
* S:SIMS 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 S:SIMS. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package IO;
import DataStructure.DataHouse;
import java.util.*;
import java.io.*;
/**
* ListIO is used to save and load the user's file list.
* @author 20378332
*/
public class ListIO {
/**
* Save the absolute path of each datahouse in the list.
* Each datahouse location is saved in order as passed in the list.
* #WARNING - the output file will be overwritten if it already exist.
* @param list An arraylist of datahouses
* @param outputDest the output file.
*/
public static void saveFileList(ArrayList<DataHouse> list, String outputDest) {
try {
PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(new File(outputDest))));
int size = list.size();
for (int i = 0; i < size; i++)
ps.printf("%s\n", list.get(i).absolutePath);
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Load a file containing the absolute path of one or more input files
* with each file path seperated on a single line.
* @param source The config file location
* @return Datahouse[] an array of datahouses. A null entry refers to a
* file that cannot be loaded.
*/
public static DataHouse[] loadFileList(String source) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File(source))));
ArrayList<String> files = new ArrayList<String> ();
String temp;
while ((temp = br.readLine()) != null) {
files.add(temp);
}
DataHouse[] dh = new DataHouse[files.size()];
for (int i = 0; i < dh.length; i++) {
dh[i] = ReadInput.readInput(new File(files.get(i)));
}
return dh;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
| true
|
4a421a24c0c10b40f76bbf4a2095553567d4d1a1
|
Java
|
Konyaka1/aem-authoring-toolkit
|
/plugin/src/main/java/com/exadel/aem/toolkit/plugin/utils/MemberUtil.java
|
UTF-8
| 3,401
| 2.703125
| 3
|
[
"Apache-2.0"
] |
permissive
|
/*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.exadel.aem.toolkit.plugin.utils;
import java.lang.reflect.Field;
import java.lang.reflect.MalformedParameterizedTypeException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ClassUtils;
/**
* Contains utility methods for retrieving info about Java class members
*/
public class MemberUtil {
/**
* Default (instantiation-restricting) constructor
*/
private MemberUtil() {
}
/**
* Retrieves the type represented by the provided Java class {@code Member}. If the method is designed to provide
* a primitive value or a singular object, its "direct" type is returned. If the method represents a collection,
* type of array's element is returned
* @param member The member to analyze, a {@link Field} or {@link Method} reference expected
* @return Appropriate {@code Class} instance or null if an invalid {@code Member} provided
*/
public static Class<?> getPlainType(Member member) {
if (!(member instanceof Field) && !(member instanceof Method)) {
return null;
}
Class<?> result = member instanceof Field
? ((Field) member).getType()
: ((Method) member).getReturnType();
if (result.isArray()) {
result = result.getComponentType();
}
if (ClassUtils.isAssignable(result, Collection.class)) {
return getGenericType(member, result);
}
return result;
}
/**
* Retrieves the underlying parameter type of the provided Java class {@code Member}. If the method is an array
* or a collection, the item (parameter) type is returned; otherwise, the mere method type is returned
* @param member The member to analyze, a {@link Field} or {@link Method} reference expected
* @param defaultValue The value to return if parameter type extraction fails
* @return Extracted {@code Class} instance, or the {@code defaultValue}
*/
private static Class<?> getGenericType(Member member, Class<?> defaultValue) {
try {
ParameterizedType fieldGenericType = member instanceof Field
? (ParameterizedType) ((Field) member).getGenericType()
: (ParameterizedType) ((Method) member).getGenericReturnType();
Type[] typeArguments = fieldGenericType.getActualTypeArguments();
if (ArrayUtils.isEmpty(typeArguments)) {
return defaultValue;
}
return (Class<?>) typeArguments[0];
} catch (TypeNotPresentException | MalformedParameterizedTypeException e) {
return defaultValue;
}
}
}
| true
|
ec4ec0b8ffb9a882a248c58f726165839f788d16
|
Java
|
vrnsky/java-a-to-z
|
/chapter5/List/src/test/java/collection/QueueTest.java
|
UTF-8
| 1,841
| 3.3125
| 3
|
[] |
no_license
|
package collection;
import org.junit.Test;
import static org.junit.Assert.assertThat;
import static org.hamcrest.core.Is.is;
/**
* Unit test for Queue.java.
*/
public class QueueTest {
/**
* When try push to the queue should check that value was added.
*/
@Test
public void whenTryPushToTheQueueShouldCheckThatValueWasAddedToTheQueue() {
Queue<String> queue = new Queue<>();
String expected = "value";
queue.add(expected);
assertThat(queue.poll(), is(expected));
}
/**
* When try push value and call method peek should check that value was not removed.
*/
@Test
public void whenTryPushValueToTheQueueAndCallPeekMethodShouldCheckThat() {
Queue<String> queue = new Queue<>();
String expected = "value";
queue.add(expected);
queue.peek();
assertThat(queue.poll(), is(expected));
}
/**
* When try check that queue is empty should check that method return true.
*/
@Test
public void whenTryCheckThatQueueIsEmptyShouldCheckThatMethodReturnTrue() {
Queue<String> queue = new Queue<>();
assertThat(queue.isEmpty(), is(true));
}
/**
* When try poll element from empty queue should check that throw exception.
*/
@Test(expected = IllegalArgumentException.class)
public void whenTryPollElementFromEmptyCollectionShouldCheckThatQueueThrowException() {
Queue<String> queue = new Queue<>();
queue.peek();
}
/**
* When try peek element from empty queue should check that queue throw exception.
*/
@Test(expected = IllegalArgumentException.class)
public void whenTryPeekElementFromEmptyCollectionShouldCheckThatQueueThrowException() {
Queue<String> strings = new Queue<>();
strings.peek();
}
}
| true
|
94075da4dff140a98cdb914ab1e447a9557a6f2c
|
Java
|
gitter-badger/adeptj-modules
|
/jaxrs/resteasy/src/main/java/com/adeptj/modules/jaxrs/resteasy/plugin/validation/GeneralValidatorContextResolver.java
|
UTF-8
| 2,791
| 1.78125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* =============================================================================
*
* Copyright (c) 2016 AdeptJ
* Copyright (c) 2016 Rakesh Kumar <irakeshk@outlook.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
package com.adeptj.modules.jaxrs.resteasy.plugin.validation;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Set;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.ValidatorFactory;
import javax.validation.executable.ExecutableType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.HibernateValidatorConfiguration;
import org.hibernate.validator.parameternameprovider.ReflectionParameterNameProvider;
import org.jboss.resteasy.plugins.validation.GeneralValidatorImpl;
import org.jboss.resteasy.plugins.validation.i18n.Messages;
import org.jboss.resteasy.spi.validation.GeneralValidator;
/**
* GeneralValidatorContextResolver.
*
* @author Rakesh.Kumar, AdeptJ.
*/
@Provider
public class GeneralValidatorContextResolver implements ContextResolver<GeneralValidator> {
private volatile ValidatorFactory validatorFactory;
private static final Set<ExecutableType> ALL_VALIDATED_EXECUTABLE_TYPES = Collections.unmodifiableSet(
EnumSet.complementOf(EnumSet.of(ExecutableType.ALL, ExecutableType.NONE, ExecutableType.IMPLICIT)));
@Override
public GeneralValidator getContext(Class<?> type) {
try {
if (this.validatorFactory == null) {
this.validatorFactory = ValidatorFactoryInitializer.INSTANCE.getValidatorFactory();
}
return new GeneralValidatorImpl(this.validatorFactory, true, ALL_VALIDATED_EXECUTABLE_TYPES);
} catch (Exception e) {
throw new ValidationException(Messages.MESSAGES.unableToLoadValidationSupport(), e);
}
}
private enum ValidatorFactoryInitializer {
INSTANCE;
private ValidatorFactory getValidatorFactory() {
HibernateValidatorConfiguration config = Validation.byProvider(HibernateValidator.class).configure();
config.parameterNameProvider(new ReflectionParameterNameProvider());
return config.buildValidatorFactory();
}
}
}
| true
|
242a65969a075aa20dccd83272d68871289260aa
|
Java
|
Decooo/CarService
|
/SpringBoot/src/main/java/com/serwis/services/PartsService.java
|
UTF-8
| 706
| 2.078125
| 2
|
[] |
no_license
|
package com.serwis.services;
import com.serwis.entity.Parts;
import com.serwis.repository.PartsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by jakub on 18.05.2018.
*/
@Service
public class PartsService {
@Autowired
private PartsRepository partsRepository;
public void save(Parts part) {
partsRepository.save(part);
}
public List<Parts> findAll() {
return partsRepository.findAll();
}
public Parts findByIdParts(int idParts) {
return partsRepository.findByIdparts(idParts);
}
public void deleteInBatch(List<Parts> parts) {
partsRepository.deleteInBatch(parts);
}
}
| true
|
041fc62f1bce9f34e3329ec4d00018330328e308
|
Java
|
ksh901016/java-study
|
/소스코드/collection/sort/AscendingComparator.java
|
UTF-8
| 322
| 3.046875
| 3
|
[] |
no_license
|
package collection.sort;
import java.util.Comparator;
public class AscendingComparator implements Comparator<Fruit> {
@Override
public int compare(Fruit o1, Fruit o2) {
if(o1.getPrice() < o2.getPrice()) return -1;
else if(o1.getPrice() == o2.getPrice()) return 0;
else return 1;
}
}
| true
|
bb8a2ad33f2370c5761410cb8cb64976a618da53
|
Java
|
mbellamk/BIPractice
|
/src/com/bellinfo/assignments/assignment3/InterfaceAndAbstractClassExample.java
|
UTF-8
| 2,730
| 3.375
| 3
|
[] |
no_license
|
package com.bellinfo.assignments.assignment3;
public class InterfaceAndAbstractClassExample {
final static Nexus5 nexus5 = new Nexus5();
public static void main(String args[]) {
Nexus5 nexus = new Nexus5();
Iphone5 i5 = new Iphone5();
Iphone6S i6s = new Iphone6S();
nexus5.setBatteryLife(500);
System.out.println(nexus5.getBatteryLife());
}
}
interface Phone {
void pickUpCall();
void rejectCall();
void dialNumber();
void installApps();
void display();
}
abstract class AndroidPhone implements Phone {
@Override
public void dialNumber() {
System.out.println("Click on the phone icon and dial Number");
}
public void pickUpCall() {
System.out.println("Swipe Right to pickup the call");
}
public void rejectCall() {
System.out.println("Swipe Left to reject the call");
}
@Override
public void installApps() {
System.out.println("Open PlayStore and select the applicaiton");
}
}
abstract class IPhone implements Phone {
public void pickUpCall() {
System.out.println("Press Green button to pick up call");
}
public void rejectCall() {
System.out.println("Press Red button to reject the call");
}
@Override
public void dialNumber() {
System.out
.println("click on the phone icon and go to keypad and dial Number");
}
@Override
public void installApps() {
System.out
.println("Open the AppStore and search for the desired applicationa and install it");
}
}
class Nexus5 extends AndroidPhone {
int batteryLife = 600;
public void display() {
System.out.println("Display with pixels 1920*1080");
}
public int getBatteryLife() {
return batteryLife;
}
public void setBatteryLife(int batteryLife) {
this.batteryLife = batteryLife;
}
}
class LGPhone extends AndroidPhone {
public void pickUpCall() {
System.out.println("Swipe left to pickup the call");
}
public void rejectCall() {
System.out.println("Swipe Right to reject the call");
}
public void display() {
System.out.println("Display with pixels 1720*1080");
}
}
class Iphone5 extends IPhone {
int batteryLife = 800;
public void display() {
System.out.println("Display in screen size 640*1136");
}
public int getBatteryLife() {
return batteryLife;
}
public void setBatteryLife(int batteryLife) {
this.batteryLife = batteryLife;
}
}
class Iphone6S extends IPhone {
int battteryLife = 1000;
public void display() {
System.out.println("Display with screen size 640*1300");
}
void fingerPrintScanner() {
System.out
.println("Plece your thumb on Home button to unlock your screen");
}
public int getBattteryLife() {
return battteryLife;
}
public void setBattteryLife(int battteryLife) {
this.battteryLife = battteryLife;
}
}
| true
|
781364aac2c033ff13fae6d9290ed158a96256a4
|
Java
|
zgyxvxiao/LeetCode
|
/linkedlist/IntersectionOfTwoLinkedLists.java
|
UTF-8
| 520
| 2.75
| 3
|
[] |
no_license
|
package linkedlist;
public class IntersectionOfTwoLinkedLists {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
while (headA != null){
while(headB != null){
if(headA != headB){
headB = headB.next;
}else{
return headA;
}
}
headA = headA.next;
}
return headA;
}
public static void main(String[] args) {
// write your code here
}
}
| true
|
9587e3901f693e4a63552166e93d445b02d1787e
|
Java
|
jaemin2682/YangpaGo
|
/back/src/main/java/com/papple/blog/controllers/UserBehaviorController.java
|
UTF-8
| 1,750
| 1.84375
| 2
|
[] |
no_license
|
package com.papple.blog.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.papple.blog.payload.response.UserBehavior;
import com.papple.blog.payload.response.UserLike;
import com.papple.blog.repository.UserBehaviorRepository;
import com.papple.blog.repository.UserLikeRepository;
import io.swagger.annotations.ApiOperation;
//http://localhost:8081/swagger-ui.html
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/userbehavior")
public class UserBehaviorController {
@Autowired
private UserBehaviorRepository userBehaviorRepository;
@GetMapping("/test")
@ApiOperation(value = "유저 아이디로 행동 데이터 조회")
public ResponseEntity<String> search(int user_id, int product_id, int rating, String email) throws Exception {
// userBehaviorRepository.InsertBehavior(1, 10, 5);
System.out.println(userBehaviorRepository.SelectBehavior(user_id, product_id));
userBehaviorRepository.DeleteBehavior(user_id, product_id);
System.out.println(userBehaviorRepository.SearchUserId(email));
return new ResponseEntity<String>("success", HttpStatus.OK);
}
}
| true
|
baf5bbaba59e4e1d0ddb83229ccd0cf59a84a644
|
Java
|
manrovich/algorithmsAndDataStructuresLessons
|
/Lesson3/ДЗ/src/queue/MyQueue.java
|
UTF-8
| 2,259
| 3.5
| 4
|
[] |
no_license
|
package queue;
import java.util.Arrays;
import java.util.NoSuchElementException;
public class MyQueue<T> implements MyQueueInterface<T> {
private static final int DEFAULT_CAPACITY = 10;
T[] list;
int capacity;
int begin;
int end;
public MyQueue(int capacity) {
this.capacity = capacity;
list = (T[]) new Object[capacity];
}
public MyQueue() {
this(DEFAULT_CAPACITY);
}
@Override
public void insert(T item) {
if (isFull()) {
increaseCapacity();
}
list[end] = item;
end = nextIndex(end);
}
@Override
public T remove() {
if (isEmpty()) {
throw new NoSuchElementException("Queue is empty");
}
T temp = peek();
list[begin] = null;
begin = nextIndex(begin);
return temp;
}
@Override
public T peek() {
return list[begin];
}
private int nextIndex(int index) {
return nextIndex(index, 1);
}
private int nextIndex(int index, int shift) {
return (index + shift) % capacity;
}
private void increaseCapacity() {
int oldCapacity = capacity;
int newCapacity = oldCapacity + (oldCapacity / 2 + 1);
capacity = newCapacity;
T[] tempList = (T[]) new Object[newCapacity];
System.arraycopy(list, begin, tempList, begin + newCapacity - oldCapacity, oldCapacity - begin);
System.arraycopy(list, 0, tempList, 0, end);
begin = nextIndex(begin, newCapacity - oldCapacity);
list = tempList;
}
private boolean isEmpty() {
return list[begin] == null;
}
private boolean isFull() {
return !isEmpty() && begin == end;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
int i = begin;
if (isFull()) {
sb.append(list[i]).append(", ");
i++;
}
while (i != end) {
sb.append(list[i]);
i = nextIndex(i);
sb.append(i != end ? ", " : "");
}
sb.append("]");
return sb.toString();
//Arrays.toString(list) + " begin: " + begin + " end: " + end;
}
}
| true
|
d0feeff042b2fecdea02eb081949db9aa39cf453
|
Java
|
tallesan/MyPublicJava
|
/feignClient/src/main/java/com/example/feignClient/controller/defaultController.java
|
UTF-8
| 2,377
| 1.960938
| 2
|
[] |
no_license
|
package com.example.feignClient.controller;
import com.example.feignClient.model.UserResponse;
import com.example.feignClient.service.ServiceClientImpl;
import com.example.feignClient.service.ServiceGiphy;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "/")
public class defaultController {
private ServiceClientImpl serviceClient;
private ServiceGiphy serviceGiphy;
@Autowired
public defaultController(ServiceClientImpl serviceClient, ServiceGiphy serviceGiphy) {
this.serviceClient = serviceClient;
this.serviceGiphy = serviceGiphy;
}
@RequestMapping("/index")
public String initClient(Model model) {
UserResponse userResponceThisDay = serviceClient.getThisDay();
UserResponse userResponceHistoryDay = serviceClient.getHistoryDay();
boolean comparison = serviceClient
.getCompareMoney(userResponceThisDay.getRates(), userResponceHistoryDay.getRates(), "USD");
String img;
if (comparison) {
img = serviceGiphy.getUrlGiphy("rich");
} else {
img = serviceGiphy.getUrlGiphy("broke");
}
model.addAttribute("img",img);
model.addAttribute("searchFalse", comparison);
return "index";
}
@GetMapping("/")
public String getStartProg(Model model) {
return "redirect:/index";
}
@GetMapping("/commentRub")
public String getRubChange(Model model) {
UserResponse userResponceThisDay = serviceClient.getThisDay();
UserResponse userResponceHistoryDay = serviceClient.getHistoryDay();
Map<String, Double> currencyThis = serviceClient
.changeMoney(userResponceThisDay.getRates(), "RUB");
Map<String, Double> currencyHistoryDay = serviceClient
.changeMoney(userResponceHistoryDay.getRates(), "RUB");
boolean comparison = serviceClient
.getCompareMoney(currencyThis, currencyHistoryDay, "RUB");
String img;
if (comparison) {
img = serviceGiphy.getUrlGiphy("rich");
} else {
img = serviceGiphy.getUrlGiphy("broke");
}
model.addAttribute("img", img);
model.addAttribute("searchFalse", comparison);
return "rub_compare";
}
}
| true
|
4a2b2f4da2757aef7888d002b59ebd14d2bcc9a1
|
Java
|
maliangnansheng/bbs-ssm
|
/src/main/java/com/liang/dao/CollectMapper.java
|
UTF-8
| 622
| 2.03125
| 2
|
[
"AGPL-3.0-only"
] |
permissive
|
package com.liang.dao;
import java.util.List;
import java.util.Map;
import com.liang.bean.Collect;
public interface CollectMapper {
// 新增收藏信息
void insert(Collect record);
// 按sid删除收藏信息
void deleteByKey(String sid);
// 按userid和fid删除收藏
void deleteByUF(Collect collect);
// 按fid删除收藏信息
void deleteByFid(String fid);
// 删除某用户对应的收藏信息
void deleteByUserid(String userid);
// 查询所有收藏信息
List<Collect> selectCollect();
// 按收藏者id和被收藏文章id进行查询
Collect selectCollectByUF(Collect collect);
}
| true
|
c767829e343b5a64b9cb1d7caa3f2c86fdb5b0ff
|
Java
|
genius1wjc/TestAndroidApp
|
/app/src/main/java/com/example/myapplication/activity/GenericsActi.java
|
UTF-8
| 4,423
| 3.171875
| 3
|
[] |
no_license
|
package com.example.myapplication.activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.example.myapplication.R;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GenericsActi extends AppCompatActivity {
@Override
// @SuppressWarnings("unchecked")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_generics);
Box1 box1 = new Box1("Text 1");
Object text1 = box1.getT();
if (text1 instanceof CharSequence) {
TextView tv1 = (TextView) findViewById(R.id.tv1);
tv1.setText((CharSequence)text1);
}
Box2<String> box2 = new Box2<>();
box2.set("Text 2");
TextView tv2 = (TextView) findViewById(R.id.tv2);
tv2.setText(box2.toString());
Box3<String, Integer> box3 = new Box3<>();
box3.setK("Hello").setInteger(2);
TextView tv3 = (TextView) findViewById(R.id.tv3);
tv3.setText(box3.toString());
Box3 rawBox = box3; // For backward compatibility, assigning a parameterized type to its raw type is allowed
rawBox.setInteger(1).setK("text");
String text4 = "Am I valid?";
TextView tv4 = (TextView) findViewById(R.id.tv4);
tv4.setText("Text is " + isValidText(text4)); // Using type inference
// The inference algorithm tries to find the most specific type that works with all of the arguments
Serializable s = pick("d", new ArrayList<String>());
if (s instanceof Serializable) {
TextView tv5 = (TextView) findViewById(R.id.tv5);
tv5.setText("Serializable");
}
Box4 box4 = new Box4(false);
TextView tv6 = (TextView) findViewById(R.id.tv6);
tv6.setText(box4.getMessage());
Double[] doubles = {1.1, 2.2, 3.3};
List<Double> list = Arrays.asList(doubles);
double sum = sumOfList(list);
TextView tv7 = (TextView) findViewById(R.id.tv7);
tv7.setText("Sum of doubles is " + sum);
List<Object> objects = new ArrayList<>();
int sum2 = addNumbers(objects);
TextView tv8 = (TextView) findViewById(R.id.tv8);
tv8.setText("Size of objects is " + sum2);
}
// Generic class
class Box1<T> {
private T t;
Box1(T t) {
this.t = t;
}
T getT() {
return t;
}
}
// Generic class with upper bounded type parameter
class Box2<T extends String> {
private T t;
void set(T t) {
this.t = t;
}
@Override
public String toString() {
return t;
}
}
// Generic class with multiple upper bounded type parameter
class Box3<K extends CharSequence, V extends Integer> {
private K k;
private Integer i;
Box3 setK(K k) {
this.k = k;
return this;
}
Box3 setInteger(V v) {
i = v;
return this;
}
@Override
public String toString() {
if (k instanceof String)
return "K is " + (String)k + " and integer is" + i;
else
return "Integer is" + i;
}
}
// Generic method
private static <T extends CharSequence> boolean isValidText(T t) {
return t != null && !t.equals("");
}
static <T> T pick(T a1, T a2) {
return a2;
}
class Box4<T> {
String message = "";
// Constructors can be generic (in other words, declare their own formal type parameters)
// in both generic and non-generic classes
<X extends Boolean> Box4(X x) {
if (x != null)
message = "Not null";
}
String getMessage() {
return message;
}
}
// Upper bounded wildcard
public static double sumOfList(List<? extends Number> list) {
double s = 0.0;
for (Number n : list)
s += n.doubleValue();
return s;
}
// Lower bounded wildcard
public static int addNumbers(List<? super Integer> list) {
for (int i = 1; i <= 10; i++) {
list.add(i);
}
return list.size();
}
}
| true
|
1c1bcc8473e097e6fe6b048d751665dc3815ad48
|
Java
|
joaocelso172/StrongEyeMlKitFaceTracking
|
/app/src/main/java/com/example/googlemlkitdemo/Model/User.java
|
UTF-8
| 1,295
| 2.375
| 2
|
[] |
no_license
|
package com.example.googlemlkitdemo.Model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class User {
@SerializedName("id_pessoa_fisica")
@Expose
private int idPessoaFisica;
@SerializedName("id_empresa")
@Expose
private int idEmpresa;
@SerializedName("nome")
@Expose
private String nome;
@SerializedName("foto")
@Expose
private String foto;
public User() {
}
public User (int idPessoaFisica, int idEmpresa, String nome, String foto) {
this.idPessoaFisica = idPessoaFisica;
this.idEmpresa = idEmpresa;
this.nome = nome;
this.foto = foto;
}
public int getIdPessoaFisica() {
return idPessoaFisica;
}
public void setIdPessoaFisica(int idPessoaFisica) {
this.idPessoaFisica = idPessoaFisica;
}
public int getIdEmpresa() {
return idEmpresa;
}
public void setIdEmpresa(int idEmpresa) {
this.idEmpresa = idEmpresa;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getFoto() {
return foto;
}
public void setFoto(String foto) {
this.foto = foto;
}
}
| true
|
6386ff09e96ce210d12d97ba146bd2e9c2628ad4
|
Java
|
naharrison/CCDBtools3
|
/src/ccdbTools/CNDAnalysis.java
|
UTF-8
| 8,731
| 2.203125
| 2
|
[] |
no_license
|
package ccdbTools;
import org.jlab.groot.base.GStyle;
import org.jlab.groot.data.GraphErrors;
import org.jlab.groot.data.H1F;
import org.jlab.groot.fitter.DataFitter;
import org.jlab.groot.math.F1D;
import org.jlab.groot.ui.TCanvas;
import java.util.Date;
public class CNDAnalysis {
public static void main(String[] args) {
GStyle.getAxisAttributesX().setTitleFontSize(18);
GStyle.getAxisAttributesX().setLabelFontSize(18);
GStyle.getAxisAttributesY().setTitleFontSize(18);
GStyle.getAxisAttributesY().setLabelFontSize(18);
ConstantsComparer cc = new ConstantsComparer();
TCanvas can = new TCanvas("can", 900, 850);
can.divide(2, 3);
can.getCanvas().setTitleSize(18);
can.getCanvas().getPad(0).getAxisY().setRange(-15, 15);
can.getCanvas().getPad(2).getAxisY().setRange(-20, 20);
can.getCanvas().getPad(4).getAxisY().setRange(5, 28);
/// left_right timing offset ///
CcdbData data_LR_ideal = new CcdbData("mysql://clas12reader@clasdb.jlab.org/clas12", "default", 11, new Date(), "/calibration/cnd/time_offsets_LR");
CcdbData data_LR_smeared = new CcdbData("sqlite:///../../../clas12.smeared_constants_final.sqlite", "default", 17, new Date(), "/calibration/cnd/time_offsets_LR");
CcdbData data_LR_extracted = new CcdbData(-1, "mysql://clas12reader@clasdb.jlab.org/clas12", "default", 17, new Date(), "/calibration/cnd/time_offsets_LR");
// using negative values: ----------------^^
GraphErrors g_LR_ideal = cc.getColumnGraphErrors(data_LR_ideal, 3, -1, 0, 0);
GraphErrors g_LR_smeared = cc.getColumnGraphErrors(data_LR_smeared, 3, -1, 0, 0);
GraphErrors g_LR_extracted = cc.getColumnGraphErrors(data_LR_extracted, 3, -1, 0, 0);
g_LR_ideal.setMarkerColor(1);
g_LR_ideal.setTitle("CND LR");
g_LR_ideal.setTitleX("component");
g_LR_ideal.setTitleY("ns");
g_LR_smeared.setMarkerColor(2);
g_LR_smeared.setTitle("CND LR");
g_LR_smeared.setTitleX("component");
g_LR_smeared.setTitleY("ns");
g_LR_extracted.setMarkerColor(3);
g_LR_extracted.setMarkerSize(4);
g_LR_extracted.setTitle("CND LR");
g_LR_extracted.setTitleX("component");
g_LR_extracted.setTitleY("ns");
F1D f_LR_ideal = new F1D("f_LR_ideal", "[b] + [m]*x", 0, 73);
f_LR_ideal.setParameter(0, 0.0);
f_LR_ideal.setParameter(1, 0.0);
f_LR_ideal.setLineColor(1);
f_LR_ideal.setLineWidth(2);
H1F h_LR_compare = cc.compareDiffH1D(data_LR_smeared, data_LR_extracted, 3, 0, 0, 25, -10.0, 10.0);
h_LR_compare.setTitle("CND LR");
h_LR_compare.setTitleX("difference (ns)");
F1D ff_LR = new F1D("ff_LR", "[amp]*gaus(x, [mean], [sigma])", -10.0, 10.0);
ff_LR.setParameter(0, h_LR_compare.getBinContent(h_LR_compare.getMaximumBin()));
ff_LR.setParameter(1, h_LR_compare.getMean());
ff_LR.setParameter(2, h_LR_compare.getRMS());
ff_LR.setLineColor(2);
ff_LR.setLineWidth(2);
DataFitter.fit(ff_LR, h_LR_compare, "RNQ");
h_LR_compare.setLineWidth(2);
h_LR_compare.setOptStat("1101001110");
h_LR_compare.getStatBox().setFontSize(18);
can.cd(0);
//can.draw(g_LR_ideal);
//can.draw(g_LR_smeared, "same");
can.draw(g_LR_smeared);
can.draw(g_LR_extracted, "same");
can.draw(f_LR_ideal, "same");
can.cd(1);
can.draw(h_LR_compare);
/// time offsets layer ///
/// have to fill graphs manually for this one
CcdbData data_layer_smeared = new CcdbData("sqlite:///../../../clas12.smeared_constants_final.sqlite", "default", 17, new Date(), "/calibration/cnd/time_offsets_layer");
CcdbData data_layer_extracted = new CcdbData(-1, "mysql://clas12reader@clasdb.jlab.org/clas12", "default", 17, new Date(), "/calibration/cnd/time_offsets_layer");
// using negative values: -------------------^^
GraphErrors g_layer_smeared = new GraphErrors();
GraphErrors g_layer_extracted = new GraphErrors();
H1F h_layer_compare = new H1F("h_layer_compare", 25, -6.0, 6.0);
F1D ff_layer = new F1D("ff_layer", "[amp]*gaus(x, [mean], [sigma])", -6.0, 6.0);
int counter = 1;
for(int isec = 1; isec <= 24; isec++) // 24 sectors (3 layers per sector, no components)
{
double L1_smeared = data_layer_smeared.getConstantBySLCDouble(3, isec, 1, 0);
double L2_smeared = data_layer_smeared.getConstantBySLCDouble(3, isec, 2, 0);
double L3_smeared = data_layer_smeared.getConstantBySLCDouble(3, isec, 3, 0);
double L1_extracted = data_layer_extracted.getConstantBySLCDouble(3, isec, 1, 0);
double L2_extracted = data_layer_extracted.getConstantBySLCDouble(3, isec, 2, 0);
double L3_extracted = data_layer_extracted.getConstantBySLCDouble(3, isec, 3, 0);
g_layer_smeared.addPoint(counter, L1_smeared - L3_smeared, 0.0, 0.0);
g_layer_extracted.addPoint(counter, L1_extracted - L3_extracted, 0.0, 0.0);
counter++;
g_layer_smeared.addPoint(counter, L2_smeared - L3_smeared, 0.0, 0.0);
g_layer_extracted.addPoint(counter, L2_extracted - L3_extracted, 0.0, 0.0);
counter++;
h_layer_compare.fill((L1_smeared - L3_smeared) - (L1_extracted - L3_extracted));
h_layer_compare.fill((L2_smeared - L3_smeared) - (L2_extracted - L3_extracted));
}
g_layer_smeared.setMarkerColor(2);
g_layer_smeared.setTitle("CND layer");
g_layer_smeared.setTitleX("component");
g_layer_smeared.setTitleY("ns");
g_layer_extracted.setMarkerColor(3);
g_layer_extracted.setMarkerSize(4);
g_layer_extracted.setTitle("CND layer");
g_layer_extracted.setTitleX("component");
g_layer_extracted.setTitleY("ns");
h_layer_compare.setTitle("CND layer");
h_layer_compare.setTitleX("difference (ns)");
F1D f_layer_ideal = new F1D("f_layer_ideal", "[b] + [m]*x", 0, 49);
f_layer_ideal.setParameter(0, 0.0);
f_layer_ideal.setParameter(1, 0.0);
f_layer_ideal.setLineColor(1);
f_layer_ideal.setLineWidth(2);
ff_layer.setParameter(0, h_layer_compare.getBinContent(h_layer_compare.getMaximumBin()));
ff_layer.setParameter(1, h_layer_compare.getMean());
ff_layer.setParameter(2, h_layer_compare.getRMS());
ff_layer.setLineColor(2);
ff_layer.setLineWidth(2);
DataFitter.fit(ff_layer, h_layer_compare, "RNQ");
h_layer_compare.setLineWidth(2);
h_layer_compare.setOptStat("1101001110");
h_layer_compare.getStatBox().setFontSize(18);
can.cd(2);
can.draw(g_layer_smeared);
can.draw(g_layer_extracted, "same");
can.draw(f_layer_ideal, "same");
can.cd(3);
can.draw(h_layer_compare);
/// veff ///
CcdbData data_veff_ideal = new CcdbData("mysql://clas12reader@clasdb.jlab.org/clas12", "default", 11, new Date(), "/calibration/cnd/veff");
CcdbData data_veff_smeared = new CcdbData("sqlite:///../../../clas12.smeared_constants_final.sqlite", "default", 17, new Date(), "/calibration/cnd/veff");
CcdbData data_veff_extracted = new CcdbData("mysql://clas12reader@clasdb.jlab.org/clas12", "default", 17, new Date(), "/calibration/cnd/veff");
GraphErrors g_veff_ideal = cc.getColumnGraphErrors(data_veff_ideal, 3, -1, 0, 0);
GraphErrors g_veff_smeared = cc.getColumnGraphErrors(data_veff_smeared, 3, -1, 0, 0);
GraphErrors g_veff_extracted = cc.getColumnGraphErrors(data_veff_extracted, 3, -1, 0, 0);
g_veff_ideal.setMarkerColor(1);
g_veff_ideal.setTitle("CND veff");
g_veff_ideal.setTitleX("component");
g_veff_ideal.setTitleY("cm/ns");
g_veff_smeared.setMarkerColor(2);
g_veff_smeared.setTitle("CND veff");
g_veff_smeared.setTitleX("component");
g_veff_smeared.setTitleY("cm/ns");
g_veff_extracted.setMarkerColor(3);
g_veff_extracted.setMarkerSize(4);
g_veff_extracted.setTitle("CND veff");
g_veff_extracted.setTitleX("component");
g_veff_extracted.setTitleY("cm/ns");
F1D f_veff_ideal = new F1D("f_veff_ideal", "[b] + [m]*x", 0, 145);
f_veff_ideal.setParameter(0, 16.0);
f_veff_ideal.setParameter(1, 0.0);
f_veff_ideal.setLineColor(1);
f_veff_ideal.setLineWidth(2);
H1F h_veff_compare = cc.compareDiffPercentH1D(data_veff_smeared, data_veff_extracted, 3, 0, 0, 25, -10.0, 10.0);
h_veff_compare.setTitle("CND veff");
h_veff_compare.setTitleX("percent difference (%)");
F1D ff_veff = new F1D("ff_veff", "[amp]*gaus(x, [mean], [sigma])", -10.0, 10.0);
ff_veff.setParameter(0, h_veff_compare.getBinContent(h_veff_compare.getMaximumBin()));
ff_veff.setParameter(1, h_veff_compare.getMean());
ff_veff.setParameter(2, h_veff_compare.getRMS());
ff_veff.setLineColor(2);
ff_veff.setLineWidth(2);
DataFitter.fit(ff_veff, h_veff_compare, "RNQ");
h_veff_compare.setLineWidth(2);
h_veff_compare.setOptStat("1101001110");
h_veff_compare.getStatBox().setFontSize(18);
can.cd(4);
//can.draw(g_veff_ideal);
//can.draw(g_veff_smeared, "same");
can.draw(g_veff_smeared);
can.draw(g_veff_extracted, "same");
can.draw(f_veff_ideal, "same");
can.cd(5);
can.draw(h_veff_compare);
}
}
| true
|
84097bd1af000e2c238eb917048696c7131ba52e
|
Java
|
sssssuzy/semi-project-ICIA-
|
/src/model/ProductDAO.java
|
UHC
| 4,688
| 2.46875
| 2
|
[] |
no_license
|
package model;
import java.sql.*;
import org.apache.catalina.filters.CsrfPreventionFilter;
import org.json.simple.*;
public class ProductDAO {
//ǰ
public void delete(String prod_id) {
try {
String sql = "delete from product where prod_id=?";
PreparedStatement ps=DB.con.prepareStatement(sql);
ps.setString(1, prod_id);
ps.execute();
}catch(Exception e) {
System.out.println(":"+e.toString());
}
}
//ǰ
public void update(ProductVO vo) {
try {
String sql="update product set prod_name=?,company=?,prod_item=?,mall_id=?,price1=?,price2=?,prod_del=?,detail=?,image=? where prod_id=?";
PreparedStatement ps = DB.con.prepareStatement(sql);
ps.setString(10, vo.getProd_id());
ps.setString(1, vo.getProd_name());
ps.setString(3, vo.getProd_item());
ps.setString(4, vo.getMall_id());
ps.setString(2, vo.getCompany());
ps.setInt(5, vo.getPrice1());
ps.setInt(6, vo.getPrice2());
ps.setString(8, vo.getDetail());
ps.setString(9, vo.getImage());
ps.setString(7, vo.getProd_del());
ps.execute();
}catch(Exception e) {
System.out.println(":"+ e.toString());
}
}
//ǰ
public ProductVO read(String prod_id) {
ProductVO vo = new ProductVO();
try {
String sql="select * from productMall where prod_id=?";
PreparedStatement ps = DB.con.prepareStatement(sql);
ps.setString(1, prod_id);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
vo.setProd_id(rs.getString("prod_id"));
vo.setProd_name(rs.getString("prod_name"));
vo.setProd_item(rs.getString("prod_item"));
vo.setMall_id(rs.getString("mall_id"));
vo.setProd_del(rs.getString("prod_del"));
vo.setMall_name(rs.getString("mall_name"));
vo.setPrice1(rs.getInt("price1"));
vo.setPrice2(rs.getInt("price2"));
vo.setCompany(rs.getString("company"));
vo.setDetail(rs.getString("detail"));
vo.setImage(rs.getString("image"));
}
}catch(Exception e) {
System.out.println(":"+ e.toString());
}return vo;
}
//ǰڵ
public String getCode() {
String prod_id="P001";
try {
String sql = "select max(prod_id) from product";
PreparedStatement ps = DB.con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
String lastId=rs.getString("max(prod_id)");
prod_id="P"+(Integer.parseInt(lastId.substring(1))+1);
}
}catch(Exception e) {
System.out.println(":"+e.toString());
}
return prod_id;
}
//ǰ
public void insert(ProductVO vo) {
try {
String sql="insert into product(prod_id,prod_name,prod_item,mall_id,company,price1,price2,detail,image,prod_del) values (?,?,?,?,?,?,?,?,?,?)";
PreparedStatement ps = DB.con.prepareStatement(sql);
ps.setString(1, vo.getProd_id());
ps.setString(2, vo.getProd_name());
ps.setString(3, vo.getProd_item());
ps.setString(4, vo.getMall_id());
ps.setString(5, vo.getCompany());
ps.setInt(6, vo.getPrice1());
ps.setInt(7, vo.getPrice2());
ps.setString(8, vo.getDetail());
ps.setString(9, vo.getImage());
ps.setString(10, "0");
ps.execute();
}catch(Exception e) {
System.out.println(":"+ e.toString());
}
}
//ĸ
public JSONObject list(SqlVO vo) {
JSONObject jObject = new JSONObject();
System.out.println(vo.toString());
try {
String sql= "{call list(?,?,?,?,?,?,?,?,?)}";
CallableStatement cs=DB.con.prepareCall(sql);
cs.setString(1, "product");
cs.setString(2, vo.getKey());
cs.setString(3, vo.getWord());
cs.setInt(4, vo.getPage());
cs.setInt(5, vo.getPerpage());
cs.setString(6, vo.getOrder());
cs.setString(7, vo.getDesc());
cs.registerOutParameter(8, oracle.jdbc.OracleTypes.CURSOR);
cs.registerOutParameter(9, oracle.jdbc.OracleTypes.INTEGER);
cs.execute();
ResultSet rs=(ResultSet)cs.getObject(8);
JSONArray array=new JSONArray();
while(rs.next()) {
JSONObject obj= new JSONObject();
obj.put("prod_id", rs.getString("prod_id"));
obj.put("prod_name", rs.getString("prod_name"));
obj.put("prod_item", rs.getString("prod_item"));
obj.put("mall_id", rs.getString("mall_id"));
obj.put("company", rs.getString("company"));
obj.put("price1", rs.getInt("price1"));
obj.put("price2", rs.getInt("price2"));
obj.put("detail", rs.getString("detail"));
obj.put("image", rs.getString("image"));
obj.put("prod_del", rs.getString("prod_del"));
array.add(obj);
}
jObject.put("productList", array);
int count= cs.getInt(9);
jObject.put("count", count);
}catch(Exception e) {
System.out.println(":"+e.toString());
}return jObject;
}
}
| true
|
d4478c10634e6ad6df7879fd4978e873e1534bb2
|
Java
|
CeterisAGarcia/CodigoFase1AG
|
/Microservicio/García/JDAAPIApp/JDAAPICore/src/mx/agarcia/ea/jda/config/ConfigEntries.java
|
UTF-8
| 2,049
| 2.625
| 3
|
[] |
no_license
|
package mx.agarcia.ea.jda.config;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
/**
*
* @author Sol4IT Mexico 2019 - Todos los derechos reservados
* @category Almacenes Garcia / Ceteris- JDA API
*/
public class ConfigEntries {
private String id;
private boolean list;
private HashMap<String, ConfigEntry> configMap = new HashMap();
private List<ConfigEntry> configList = new ArrayList();
public void addConfigEntry(ConfigEntry pConfig) {
if (isList()) {
this.configList.add(pConfig);
} else {
this.configMap.put(pConfig.getId(), pConfig);
}
}
public ConfigEntry getEntry(String pId) {
Iterator itKey = this.configMap
.keySet()
.iterator();
String keyNext;
/*System.out.println(" ***** <" + pId + ">getEntry CONFIGS *****");
while (itKey.hasNext()) {
keyNext = (String) itKey.next();
System.out.println(" Tiene esta llave -----------> " + keyNext);
}*/
return (ConfigEntry) this.configMap.get(pId);
}
public List<ConfigEntry> getEntries() {
return this.configList;
}
public boolean containEntry(String pId) {
boolean contained = false;
if (!isList()) {
contained = this.configMap.containsKey(pId);
} else {
Iterator<ConfigEntry> itKeys = this.configList.iterator();
while (itKeys.hasNext()) {
if ((pId != null) && (pId.equals(((ConfigEntry) itKeys.next()).getId()))) {
contained = true;
break;
}
}
}
return contained;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public boolean isList() {
return this.list;
}
public void setList(boolean list) {
this.list = list;
}
}
| true
|
78a20405dde544bbf34a0ea57bdb742ceb94638f
|
Java
|
wowwowster/AlgoliaConnector
|
/src/main/java/com/sword/batch/config/CustomBatchConfigurer.java
|
UTF-8
| 3,234
| 2.125
| 2
|
[] |
no_license
|
package com.sword.batch.config;
import org.springframework.batch.core.configuration.annotation.BatchConfigurer;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.explore.support.MapJobExplorerFactoryBean;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManagerFactory;
public class CustomBatchConfigurer implements BatchConfigurer {
private final EntityManagerFactory entityManagerFactory;
private PlatformTransactionManager transactionManager;
private JobRepository jobRepository;
private JobLauncher jobLauncher;
private JobExplorer jobExplorer;
@Autowired
private TaskExecutor taskExecutor;
public CustomBatchConfigurer(EntityManagerFactory entityManagerFactory ) {
this.entityManagerFactory = entityManagerFactory;
}
@Override
public JobRepository getJobRepository() {
return this.jobRepository;
}
@Override
public PlatformTransactionManager getTransactionManager() {
return this.transactionManager;
}
@Override
public JobLauncher getJobLauncher() {
return this.jobLauncher;
}
@Override
public JobExplorer getJobExplorer() throws Exception {
return this.jobExplorer;
}
private JobLauncher createJobLauncher() throws Exception {
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(jobRepository);
jobLauncher.setTaskExecutor(taskExecutor);
jobLauncher.afterPropertiesSet();
return jobLauncher;
}
@PostConstruct
public void initialize() throws Exception {
try {
// transactionManager:
if( this.entityManagerFactory == null ){
throw new Exception("Unable to initialize batch configurer : entityManagerFactory must not be null");
}
this.transactionManager = new JpaTransactionManager( this.entityManagerFactory );
// jobRepository:
MapJobRepositoryFactoryBean jobRepositoryFactory = new MapJobRepositoryFactoryBean( this.transactionManager );
jobRepositoryFactory.afterPropertiesSet();
this.jobRepository = jobRepositoryFactory.getObject();
// jobExplorer:
MapJobExplorerFactoryBean jobExplorerFactory = new MapJobExplorerFactoryBean(jobRepositoryFactory);
jobExplorerFactory.afterPropertiesSet();
this.jobExplorer = jobExplorerFactory.getObject();
}
catch (Exception ex) {
throw new IllegalStateException("Unable to initialize Spring Batch", ex);
}
this.jobLauncher = createJobLauncher();
}
}
| true
|
bc077cd3e93a073b7f2c4fe3c086680a30d4248f
|
Java
|
eothmal/example
|
/annotations/src/com/mycompany/c/custom/k/eleventh/notnull/Main.java
|
UTF-8
| 393
| 1.84375
| 2
|
[] |
no_license
|
package com.mycompany.c.custom.k.eleventh.notnull;
public class Main {
public static void main(String[] args) {
@NotNull ExtractTransformLoadJob etlJob = new ExtractTransformLoadJob("sale_data");
@NotNull WeeklyReportJob weeklyJob = new WeeklyReportJob("trend_reports");
System.out.println(etlJob);
System.out.println(weeklyJob);
}
}
| true
|
84265e1cd60b16d7c1c1dd4bbc0cac41cd7dce1e
|
Java
|
micuvld/RIW_PROIECT_Job_Dispatcher
|
/src/main/java/socket/SocketType.java
|
UTF-8
| 121
| 1.953125
| 2
|
[] |
no_license
|
package socket;
/**
* Created by vlad on 28.03.2017.
*/
public enum SocketType {
MASTER,
WORKER,
BOARD;
}
| true
|
43d8177ad029ffd53d693c1ca1decc47a9d47edd
|
Java
|
gkech/Invasive-Species
|
/InvasiveAgent.java
|
UTF-8
| 9,835
| 2.421875
| 2
|
[] |
no_license
|
/*
Authors: Majid Alkaee Taleghan, Mark Crowley, Thomas Dietterich
Invasive Species Project
2012 Oregon State University
Send code issues to: alkaee@gmail.com
Date: 3/17/13:7:48 PM
I used some of Brian Tanner's Sarsa agent code for the demo version of invasive agent.
*/
import java.util.*;
import org.apache.commons.lang3.ArrayUtils;
import org.rlcommunity.rlglue.codec.AgentInterface;
import org.rlcommunity.rlglue.codec.types.Action;
import org.rlcommunity.rlglue.codec.types.Observation;
import org.rlcommunity.rlglue.codec.util.AgentLoader;
import org.rlcommunity.rlglue.codec.taskspec.TaskSpec;
public class InvasiveAgent implements AgentInterface {
private Random randGenerator = new Random();
private Action lastAction;
private Observation lastObservation;
private double sarsa_stepsize = 0.1;
private double sarsa_epsilon = 0.1;
private double sarsa_gamma = 1.0;
private boolean policyFrozen = false;
private boolean exploringFrozen = false;
private String edges;
private double budget;
private int habitatSize;
private double Bad_Action_Penalty;
private HashMap<Integer, Vector<Double>> Q_value_function;
private int nbrReaches;
private double rewardRangeMin;
private double rewardRangeMax;
private HashMap<Integer, List<List<Integer>>> all_allowed_actions;
/**
* Parse the task spec, make sure it is only 1 integer observation and
* action, and then allocate the valueFunction.
*
* @param taskSpecification
*/
public void agent_init(String taskSpecification) {
TaskSpec theTaskSpec = new TaskSpec(taskSpecification);
//Assume the message is valid
nbrReaches = theTaskSpec.getNumDiscreteActionDims();
Bad_Action_Penalty = theTaskSpec.getRewardRange().getMin();
rewardRangeMin = theTaskSpec.getRewardRange().getMin();
rewardRangeMax = theTaskSpec.getRewardRange().getMax();
habitatSize = theTaskSpec.getNumDiscreteObsDims() / this.nbrReaches;
sarsa_gamma = theTaskSpec.getDiscountFactor();
String[] theExtra=theTaskSpec.getExtraString().split("BUDGET");
edges=theExtra[0];
budget= Double.parseDouble(theExtra[1].split("by")[0]);
sarsa_gamma = theTaskSpec.getDiscountFactor();
Q_value_function = new HashMap<Integer, Vector<Double>>();
all_allowed_actions = new HashMap<Integer, List<List<Integer>>>();
}
/**
* Choose an action e-greedily from the value function and store the action
* and observation.
*
* @param observation
* @return
*/
public Action agent_start(Observation observation) {
int[] theState = observation.intArray;
int[] thisIntAction = this.egreedy(theState);
Action returnAction = new Action();
if (thisIntAction.length > 0) {
returnAction.intArray = thisIntAction;
this.lastAction = returnAction;
this.lastObservation = observation;
}
return returnAction;
}
/**
* Choose an action e-greedily from the value function and store the action
* and observation. Update the valueFunction entry for the last
* state,action pair.
*
* @param reward
* @param observation
* @return
*/
public Action agent_step(double reward, Observation observation) {
int[] lastState = this.lastObservation.intArray;
int[] lastAction_ = this.lastAction.intArray;
int lastStateId = Utilities.getStateId(lastState);
List<Integer> lastActionList = Arrays.asList(ArrayUtils.toObject(lastAction_));
int lastActionIdx = this.all_allowed_actions.get(lastStateId).indexOf(lastActionList);
if (reward == this.Bad_Action_Penalty) {
this.all_allowed_actions.get(lastStateId).remove(lastActionIdx);
this.Q_value_function.get(lastStateId).remove(lastActionIdx);
int[] newAction = this.egreedy(this.lastObservation.intArray);
Action returnAction = new Action();
returnAction.intArray = newAction;
this.lastAction = returnAction;
return returnAction;
}
int[] newState = observation.intArray;
int[] newAction = this.egreedy(newState);
List<Integer> newActionList = Arrays.asList(ArrayUtils.toObject(newAction));
double Q_sa = this.Q_value_function.get(lastStateId).get(lastActionIdx);
double Q_sprime_aprime = this.Q_value_function.get(Utilities.getStateId(newState)).get(this.all_allowed_actions.get(Utilities.getStateId(newState)).indexOf(newActionList));
double new_Q_sa = Q_sa + this.sarsa_stepsize * (reward + this.sarsa_gamma * Q_sprime_aprime - Q_sa);
if (!this.policyFrozen) {
this.Q_value_function.get(Utilities.getStateId(lastState)).set(this.all_allowed_actions.get(Utilities.getStateId(lastState)).indexOf(lastActionList), new_Q_sa);
}
Action returnAction = new Action();
returnAction.intArray = newAction;
this.lastAction = returnAction;
this.lastObservation = observation;
return returnAction;
}
/**
* The episode is over, learn from the last reward that was received.
*
* @param reward
*/
public void agent_end(double reward) {
int[] lastState = this.lastObservation.intArray;
int[] lastAction_ = this.lastAction.intArray;
List<Integer> newActionList = Arrays.asList(ArrayUtils.toObject(lastAction_));
double Q_sa = this.Q_value_function.get(Utilities.getStateId(lastState)).get(
this.all_allowed_actions.get(Utilities.getStateId(lastState)).indexOf(newActionList));
double new_Q_sa = (Q_sa + this.sarsa_stepsize * (reward - Q_sa));
if (!this.policyFrozen) {
this.Q_value_function.get(Utilities.getStateId(lastState)).set(
this.all_allowed_actions.get(Utilities.getStateId(lastState)).indexOf(newActionList), new_Q_sa);
}
}
/**
* Release memory that is no longer required/used.
*/
public void agent_cleanup() {
lastAction = null;
lastObservation = null;
Q_value_function = null;
all_allowed_actions = null;
}
/**
* This agent responds to some simple messages for freezing learning and
* saving/loading the value function to a file.
*
* @param inMessage
* @return
*/
public String agent_message(String inMessage) {
// Message Description
// 'freeze learning'
// Action{ Set flag to stop updating policy
//
if (inMessage.startsWith("freeze learning")) {
this.policyFrozen = true;
return "message understood, policy frozen";
}
// Message Description
// unfreeze learning
// Action{ Set flag to resume updating policy
//
if (inMessage.startsWith("unfreeze learning")) {
this.policyFrozen = false;
return "message understood, policy unfrozen";
}
//Message Description
// freeze exploring
// Action{ Set flag to stop exploring (greedy actions only)
//
if (inMessage.startsWith("freeze exploring")) {
this.exploringFrozen = true;
return "message understood, exploring frozen";
}
//Message Description
// unfreeze exploring
// Action{ Set flag to resume exploring (e-greedy actions)
//
if (inMessage.startsWith("unfreeze exploring")) {
this.exploringFrozen = false;
return "message understood, exploring frozen";
}
return "Invasive agent does not understand your message.";
}
/**
* Selects a random action with probability 1-sarsa_epsilon,
* and the action with the highest value otherwise. This is a
* quick'n'dirty implementation, it does not do tie-breaking.
*
* @param theState
* @return
*/
private int[] egreedy(int[] theState) {
int stateId = Utilities.getStateId(theState);
if (this.Q_value_function.isEmpty() || !this.Q_value_function.containsKey(stateId)) {
this.all_allowed_actions.put(stateId, Utilities.getActions(theState, this.nbrReaches, this.habitatSize));
Vector<Double> vector = new Vector<Double>(Collections.nCopies(this.all_allowed_actions.get(stateId).size(), 0.0));
this.Q_value_function.put(stateId, vector);
}
int index;
if (!this.exploringFrozen && this.randGenerator.nextDouble() < this.sarsa_epsilon) {
index = this.randGenerator.nextInt(this.all_allowed_actions.get(stateId).size());
} else {
Double max = Collections.max(this.Q_value_function.get(stateId));
index = this.Q_value_function.get(stateId).indexOf(max);
}
final int[] result = new int[this.all_allowed_actions.get(stateId).get(index).size()];
for (int i = 0; i < this.all_allowed_actions.get(stateId).get(index).size(); i++) {
result[i] = this.all_allowed_actions.get(stateId).get(index).get(i).intValue();
}
return result;
}
/**
* This is a trick we can use to make the agent easily loadable. Using this
* trick you can directly execute the class and it will load itself through
* AgentLoader and connect to the rl_glue server.
*
* @param args
*/
public static void main(String[] args) {
AgentLoader theLoader = new AgentLoader(new InvasiveAgent());
theLoader.run();
}
}
| true
|
67fdb32fbc782018d601202c3acc55c62e2dfa96
|
Java
|
fabiofrc/ofertasbv-api
|
/src/main/java/com/example/algamoney/api/repository/subcategoria/SubCategoriaRepositoryQuery.java
|
UTF-8
| 535
| 1.710938
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.algamoney.api.repository.subcategoria;
import com.example.algamoney.api.model.SubCategoria;
import java.util.List;
/**
*
* @author fabio
*/
public interface SubCategoriaRepositoryQuery {
public List<SubCategoria> filtrarSubcategorias();
public List<SubCategoria> filtrarSubcategoriasByCategoriaById(Long codigo);
}
| true
|
19e29576bc4972d2cf01069f2427584517c6a31c
|
Java
|
scottrick/agl
|
/app/src/main/java/com/hatfat/agl/shaders/AglShaderProgram.java
|
UTF-8
| 1,039
| 2.5
| 2
|
[] |
no_license
|
package com.hatfat.agl.shaders;
import android.content.Context;
import android.opengl.GLES20;
/**
* Created by scottrick on 8/8/14.
*/
public class AglShaderProgram {
private int shaderProgram;
private AglShader vertShader;
private AglShader fragShader;
public AglShaderProgram(String vertShaderFilename, String fragShaderFilename, Context context) {
vertShader = new AglShader(vertShaderFilename, context);
fragShader = new AglShader(fragShaderFilename, context);
shaderProgram = GLES20.glCreateProgram();
GLES20.glAttachShader(shaderProgram, vertShader.getShader());
GLES20.glAttachShader(shaderProgram, fragShader.getShader());
GLES20.glLinkProgram(shaderProgram);
}
public int getShaderProgram() {
return shaderProgram;
}
void destroy() {
GLES20.glDeleteProgram(shaderProgram);
shaderProgram = 0;
vertShader.destroy();
vertShader = null;
fragShader.destroy();
fragShader = null;
}
}
| true
|
4be483a97f2ddbea01373682b6f0bd2b7b9106ec
|
Java
|
Amandhi/Real_Estate_App
|
/app/src/main/java/com/example/myrealestateagency/service/PropertyStatusService.java
|
UTF-8
| 630
| 2.28125
| 2
|
[] |
no_license
|
package com.example.myrealestateagency.service;
import com.example.myrealestateagency.bo.Agent;
import com.example.myrealestateagency.bo.Property;
import com.example.myrealestateagency.bo.PropertyStatus;
import java.util.ArrayList;
import java.util.List;
final public class PropertyStatusService implements IPropertyStatusService {
private final List<PropertyStatus> propertyStatus = new ArrayList<>() ;
@Override
public List<PropertyStatus> getStatus()
{
return propertyStatus;
}
@Override
public void addStatus(PropertyStatus pStatus)
{
propertyStatus.add(pStatus);
}
}
| true
|
88a79c53533250b685be75b9f1ef7a2e674ea322
|
Java
|
SimingZheng/Shopping_System
|
/src/shopping/bundling/bundlingItem.java
|
UTF-8
| 145
| 2.203125
| 2
|
[] |
no_license
|
package shopping.bundling;
public interface bundlingItem {
public String name();
public bundling packing();
public float price();
}
| true
|
fadd54df35bd56841abed5af9f341f3a72897b1d
|
Java
|
Jonathandlm/B1-Programmeren-3
|
/Eindwerk/src/main/be/leerstad/eindwerk/service/InteractionDAOImpl.java
|
UTF-8
| 5,819
| 2.328125
| 2
|
[] |
no_license
|
package be.leerstad.eindwerk.service;
import be.leerstad.eindwerk.model.Interaction;
import be.leerstad.eindwerk.model.Logfile;
import be.leerstad.eindwerk.model.Session;
import be.leerstad.eindwerk.model.Visit;
import be.leerstad.eindwerk.util.MySqlUtil;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class InteractionDAOImpl extends BaseDAO implements InteractionDAO<Interaction> {
private static final Logger LOG = Logger.getLogger(InteractionDAOImpl.class.getName());
private static final String GET_ALL_SESSIONS = "SELECT * FROM sessions, users, sites " +
"WHERE sessions.UserID = users.UserID AND sessions.SiteID = sites.SiteId";
private static final String GET_ALL_VISITS = "SELECT * FROM visits, siteapplications, schools " +
"WHERE visits.SiteApplicationID = siteapplications.ApplicationID AND visits.IPSchool = schools.IPAddress";
private static final String DELETE_SESSION = "DELETE FROM sessions WHERE LogFile = ?";
private static final String DELETE_VISIT = "DELETE FROM visits WHERE LogFile = ?";
private static InteractionDAOImpl instance;
private InteractionDAOImpl() {
}
public synchronized static InteractionDAOImpl getInstance() {
if (instance == null) {
instance = new InteractionDAOImpl();
}
return instance;
}
@Override
public List<Interaction> getInteractions() {
List<Interaction> interactions = new ArrayList<>();
int counter;
try (
Connection connection = getConnection();
PreparedStatement preparedStatementVisits = connection.prepareStatement(GET_ALL_VISITS);
ResultSet resultSetVisits = preparedStatementVisits.executeQuery();
PreparedStatement preparedStatementSessions = connection.prepareStatement(GET_ALL_SESSIONS);
ResultSet resultSetSessions = preparedStatementSessions.executeQuery()
) {
counter = 0;
while (resultSetVisits.next()) {
interactions.add(MySqlUtil.getVisitResult(resultSetVisits));
counter++;
}
LOG.log(Level.DEBUG, "Successfully retrieved all " + counter + " visits");
counter = 0;
while (resultSetSessions.next()) {
interactions.add(MySqlUtil.getSessionResult(resultSetSessions));
counter++;
}
LOG.log(Level.DEBUG, "Successfully retrieved all " + counter + " sessions");
} catch (SQLException e) {
LOG.log(Level.ERROR, "Unable to execute statement ", e);
} catch (DAOException e) {
LOG.log(Level.ERROR, "Unable to get connection ", e);
}
return interactions;
}
public void insertInteractions(List<Interaction> interactions) {
SessionDAOImpl.getInstance().insertSessions(filterSessions(interactions));
VisitDAOImpl.getInstance().insertVisits(filterVisits(interactions));
}
@Override
public void deleteInteraction(Logfile logfile) {
try (
Connection connection = getConnection();
PreparedStatement preparedStatementSessions = connection.prepareStatement(DELETE_SESSION);
PreparedStatement preparedStatementVisits = connection.prepareStatement(DELETE_VISIT)
) {
preparedStatementSessions.setString(1, logfile.getLogfile());
preparedStatementSessions.executeUpdate();
preparedStatementVisits.setString(1, logfile.getLogfile());
preparedStatementVisits.executeUpdate();
LOG.log(Level.DEBUG, "Successfully deleted all interactions from " + logfile);
} catch (SQLException e) {
LOG.log(Level.ERROR, "Unable to execute statement(s) ", e);
} catch (DAOException e) {
LOG.log(Level.ERROR, "Unable to get connection ", e);
}
}
public void deleteInteraction(String fileName) {
deleteInteraction(new Logfile(fileName));
}
@Override
public void deleteInteractions(List<Logfile> logfiles) {
try (
Connection connection = getConnection();
PreparedStatement preparedStatementSessions = connection.prepareStatement(DELETE_SESSION);
PreparedStatement preparedStatementVisits = connection.prepareStatement(DELETE_VISIT)
) {
for (Logfile logfile : logfiles) {
preparedStatementSessions.setString(1, logfile.getLogfile());
preparedStatementSessions.executeUpdate();
preparedStatementVisits.setString(1, logfile.getLogfile());
preparedStatementVisits.executeUpdate();
}
LOG.log(Level.DEBUG, "Successfully deleted interactions from " + logfiles.size() + " logfiles");
} catch (SQLException e) {
LOG.log(Level.ERROR, "Unable to execute statement(s) ", e);
} catch (DAOException e) {
LOG.log(Level.ERROR, "Unable to get connection ", e);
}
}
private List<Session> filterSessions(List<Interaction> interactions) {
return interactions.stream()
.filter(Session.class::isInstance)
.map(Session.class::cast)
.collect(Collectors.toList());
}
private List<Visit> filterVisits(List<Interaction> interactions) {
return interactions.stream()
.filter(Visit.class::isInstance)
.map(Visit.class::cast)
.collect(Collectors.toList());
}
}
| true
|
4faaa51c96e81f1a36ca5910e6041db1bcd2b05e
|
Java
|
joslynSmall/yq-xocde
|
/src/main/java/com/yq/xcode/aop/event/PublicEventListener.java
|
UTF-8
| 596
| 1.945313
| 2
|
[] |
no_license
|
package com.yq.xcode.aop.event;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
public class PublicEventListener implements ApplicationListener {
private static Log LOG = LogFactory.getLog(PublicEventListener.class);
@Override
public void onApplicationEvent(ApplicationEvent event) {
//LOG.info("event-->"+event.getClass());
if (event instanceof BaseEvent) {
BaseEvent wfEvent = (BaseEvent) event;
wfEvent.run();
}
}
}
| true
|
f0bbfb2de3b268f92197633ef334fefb81d57b32
|
Java
|
gonggf/GongWorkTest1
|
/src/test/java/demo/day2/TestModel.java
|
UTF-8
| 1,001
| 2.3125
| 2
|
[] |
no_license
|
package demo.day2;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
/**
* Created by thinkpad on 2016/12/28.
*/
public class TestModel {
WebDriver Driver;
@BeforeTest
public void openFireFox(){
//指定Firefox安装路径
System.setProperty("webdriver.firefox.bin","D:\\Software\\FireFox\\firefox.exe"); //setProperty相当于设置为静态变量,存在于内存里面
//启动Firefox浏览器
Driver = new FirefoxDriver();
System.out.println("打开浏览器成功");
}
@AfterTest
public void close() throws InterruptedException {
Thread.sleep(4000);
Driver.quit();
System.out.println("关闭浏览器成功");
}
}
| true
|
77c9624ff430846570f59d2974f6677cab4ea756
|
Java
|
chendeng/loan-weixin
|
/src/main/java/com/hwc/wx/controller/BaseController.java
|
UTF-8
| 3,921
| 2.203125
| 2
|
[] |
no_license
|
/**
* Copyright (c) 2018 All Rights Reserved.
*/
package com.hwc.wx.controller;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.fastjson.JSONObject;
import com.hwc.wx.base.BaseBizContants;
import com.hwc.wx.base.BaseResponse;
import com.hwc.wx.dto.UserContext;
import com.hwc.wx.service.UserService;
import com.hwc.wx.utils.HttpClient;
import com.hwc.wx.utils.JedisUtil;
import com.hwc.wx.utils.StringUtil;
/**
*
* @author jinlilong
* @version $Id: BaseController.java, v 0.1 2018年1月19日 下午4:40:04 jinlilong Exp $
*/
public class BaseController {
/** */
@Autowired
private UserService userService;
/** */
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
*
* @param request
* @param map
* @param callback
* @return
*/
public void httpExecute(String openId, HttpServletResponse response,
ControllerCallback callback) {
String restData = null;
try {
UserContext context = getUserContext(openId);
restData = callback.execute(context);
restData = handleSuccessMap(restData);
} catch (Exception e) {
restData = JSONObject.toJSONString(BaseResponse.getFailResponse());
logger.error("系统发生异常", e);
} finally {
HttpClient.writeJson(response, restData);
}
}
/**
*
* @param map
*/
public String handleSuccessMap(String restData) {
if (StringUtil.isEmpty(restData)) {
logger.error("restData is null");
}
logger.info("restData=>" + restData);
JSONObject json = JSONObject.parseObject(restData);
if (json.containsKey(BaseBizContants.RESPONSE_STATE_KEY)) {
Object state = json.get(BaseBizContants.RESPONSE_STATE_KEY);
if (state == null) {
return JSONObject.toJSONString(BaseResponse.getFailResponse());
} else {
return restData;
}
}
return JSONObject.toJSONString(BaseResponse.getFailResponse());
}
/**
*
* @param openId
* @return
*/
public UserContext getUserContext(String openId) {
if (StringUtil.isEmpty(openId)) {
return new UserContext();
}
JedisUtil jedisUtil = JedisUtil.getInstance();
JedisUtil.Strings strings = jedisUtil.new Strings();
String data = strings.get(openId);
if (StringUtil.isEmpty(data)) {
return initUserContext(openId);
}
try {
UserContext userContext = JSONObject.parseObject(data, UserContext.class);
if (userContext.getUserId() == 0) {
return initUserContext(openId);
} else {
return userContext;
}
} catch (Exception e) {
logger.error("获取用户上下文json转换失败", e);
}
return null;
}
/**
* 初始化上下文
*/
public UserContext initUserContext(String openId) {
UserContext userContext = userService.getUserContext(openId);
if (userContext != null) {
JedisUtil jedisUtil = JedisUtil.getInstance();
JedisUtil.Strings strings = jedisUtil.new Strings();
strings.set(openId, JSONObject.toJSONString(userContext));
} else {
userContext = new UserContext();
}
return userContext;
}
/**
*
* @author jinlilong
* @version $Id: BaseController.java, v 0.1 2018年1月23日 下午8:17:30 jinlilong Exp $
*/
public abstract class ControllerCallback {
public abstract String execute(UserContext context) throws Exception;
}
}
| true
|
1fc272cabf38f908bc954b1bcada55ed267cf281
|
Java
|
carmitt/MyProject
|
/src/JunitLesson2/StepAction.java
|
UTF-8
| 167
| 1.710938
| 2
|
[] |
no_license
|
package JunitLesson2;
public class StepAction {
String actionTime;
String actionDesc;
String actionScreenShot;
boolean actionStatus;
String linkText;
}
| true
|
1fc824677c6db08313237db96a21703bcbd253d9
|
Java
|
MiroslavStefanov/travel-together
|
/src/main/java/org/softuni/traveltogether/services/CloudService.java
|
UTF-8
| 388
| 1.898438
| 2
|
[] |
no_license
|
package org.softuni.traveltogether.services;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
public interface CloudService {
String uploadImage(MultipartFile multipartFile) throws IOException;
String uploadImage(MultipartFile multipartFile, String imageId) throws IOException;
boolean deleteImage(String imageId) throws IOException;
}
| true
|
fe5b182d79621a0adfe8cae569f9af0bd1819871
|
Java
|
annoymousGiraf/health-checker
|
/src/main/java/com/tufin/health/check/PluginService.java
|
UTF-8
| 4,283
| 2.125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.tufin.health.check;
import com.google.common.collect.Maps;
import com.tufin.health.check.groovy.GroovyRunner;
import com.tufin.health.check.groovy.PythonRunner;
import com.tufin.health.check.groovy.ScriptRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class PluginService {
private static final Logger LOGGER = LoggerFactory.getLogger(GroovyRunner.class);
private PluginTable pluginTable = new PluginTable();
private final String GROOVY_TYPE = "groovy";
private final String PYTHON_TYPE = "py";
private HashMap<String, ScriptRunner> supportedTypeTpRunner = Maps.newHashMap();
PluginService() {
initializePlugins();
}
public void initializePlugins() {
pluginTable.clean();
File pluginDirectory = new File("/usr/local/st/healthcheck/plugins");
File[] pluginFiles = pluginDirectory.listFiles();
GroovyRunner g = new GroovyRunner();
supportedTypeTpRunner.put(GROOVY_TYPE, g);
PythonRunner p = new PythonRunner();
supportedTypeTpRunner.put(PYTHON_TYPE, p);
/*
if(pluginFiles != null) {
List<File> scriptFiles = Arrays.asList(pluginFiles).stream()
.filter(file -> file.getName().contains(GROOVY_TYPE))
.collect(Collectors.toList());
*/
if (pluginFiles != null) {
List<File> scriptFiles = Arrays.asList(pluginFiles).stream().filter(File::isFile).collect(Collectors.toList());
if (scriptFiles == null) {
LOGGER.error("scriptFiles is null");
}
scriptFiles.stream()
.forEach(file -> {
// String pluginName = file.getName().substring(0, file.getName().lastIndexOf(GROOVY_TYPE));
// pluginTable.addPluginObject( pluginName, new PluginObject(pluginName, file.getName()));
String fileName = file.getName();
String fileSuffix = getSuffix(fileName);
LOGGER.info("fileName:" + fileName);
if (isSupportedType(fileSuffix)) {
ScriptRunner runner = getRunner(fileSuffix);
if (runner == null) {
LOGGER.error("runner is null");
}
String description = runner.getDescription(file.getPath());
String pluginName = getPluginName(fileName);
pluginTable.addPluginObject(pluginName, new PluginObject(pluginName, file.getPath(), description, fileSuffix));
} else if (isPythonType(fileName)){
}
});
}
}
private String getPluginName(String fileName) {
return fileName.split("\\.")[0];
}
private ScriptRunner getRunner(String fileSuffix) {
return supportedTypeTpRunner.get(fileSuffix);
}
private String getSuffix(String fileName) {
return fileName.split("\\.")[1];
}
private boolean isSupportedType(String fileSuffix) {
return supportedTypeTpRunner.containsKey(fileSuffix);
}
private boolean isPythonType(String fileName) {
return false;
}
private boolean isGroovyFile(String fileName) {
return fileName.contains(GROOVY_TYPE);
}
public List<PluginObject> getListOfAllPlugins() {
return pluginTable.getListOfAllPlugins();
}
public PluginResult runPlugin(String pluginName, String arguments) {
PluginObject pluginObject = pluginTable.getPluginByName(pluginName);
if (pluginObject != null) {
ScriptRunner r = getRunner(pluginObject.getFileType());
Map<String, String> result = r.executeScriptFile(pluginObject.getFileName());
return new PluginResult(result);
} else {
return new PluginResult("Failed", "No such plugin: " + pluginName, "arguments: " + arguments);
}
}
}
| true
|
fdf296486c97c38c226569d2e1b3626bf23ab406
|
Java
|
anthonyprudhomme/HarpeMessenger
|
/HarpeMessenger/app/src/main/java/com/harpe/harpemessenger/services/HEUploadService.java
|
UTF-8
| 8,963
| 2.046875
| 2
|
[] |
no_license
|
package com.harpe.harpemessenger.services;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.harpe.harpemessenger.DownloadActivity;
import com.harpe.harpemessenger.R;
import com.harpe.harpemessenger.httprequest.HTTPRequestInterface;
import com.harpe.harpemessenger.httprequest.HTTPRequestManager;
import com.harpe.harpemessenger.models.HEPicture;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Harpe-e on 14/05/2017.
*/
public class HEUploadService extends HEBaseTaskService implements HTTPRequestInterface {
/**
* Intent Actions
**/
public static final String ACTION_UPLOAD = "action_upload";
public static final String UPLOAD_COMPLETED = "upload_completed";
public static final String UPLOAD_ERROR = "upload_error";
/**
* Intent Extras
**/
public static final String EXTRA_FILE_URI = "extra_file_uri";
public static final String EXTRA_DOWNLOAD_URL = "extra_download_url";
public static final String TO = "to";
public static final String TOPIC = "/topics/Pictures";
public static final String DATA = "data";
public static final String PLACE = "place";
public static final String DATE = "date";
public static final String ALTITUDE = "altitude";
public static final String LATITUDE = "latitude";
public static final String LONGITUDE = "longitude";
public static final String PICTURES = "Pictures";
public static final String LAST_PATH_SEGMENT = "lastPathSegment";
private static final String TAG = "HELog";
private static final String MESSAGE_ID = "message_id";
public static final String HE_PICTURE = "hePicture";
// [START declare_ref]
private StorageReference storageReference;
// [END declare_ref]
public static IntentFilter getIntentFilter() {
IntentFilter filter = new IntentFilter();
filter.addAction(UPLOAD_COMPLETED);
filter.addAction(UPLOAD_ERROR);
return filter;
}
@Override
public void onCreate() {
super.onCreate();
// [START get_storage_ref]
storageReference = FirebaseStorage.getInstance().getReference();
// [END get_storage_ref]
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Log.d(TAG, "onStartCommand:" + intent + ":" + startId);
if (ACTION_UPLOAD.equals(intent.getAction())) {
Uri fileUri = intent.getParcelableExtra(EXTRA_FILE_URI);
uploadFromUri(fileUri,intent.getExtras());
}
return START_REDELIVER_INTENT;
}
// [END upload_from_uri]
// [START upload_from_uri]
private void uploadFromUri(final Uri fileUri, final Bundle extras) {
//Log.d(TAG, "uploadFromUri:src:" + fileUri.toString());
// [START_EXCLUDE]
taskStarted();
showProgressNotification(getString(R.string.progress_uploading), 0, 0);
// [END_EXCLUDE]
// [START get_child_ref]
// Get a reference to store file at photos/<FILENAME>.jpg
final StorageReference photoRef = storageReference.child("pictures")
.child(fileUri.getLastPathSegment());
// [END get_child_ref]
// Upload file to Firebase Storage
//Log.d(TAG, "uploadFromUri:dst:" + photoRef.getPath());
photoRef.putFile(fileUri).
addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
showProgressNotification(getString(R.string.progress_uploading),
taskSnapshot.getBytesTransferred(),
taskSnapshot.getTotalByteCount());
}
})
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Upload succeeded
//Log.d(TAG, "uploadFromUri:onSuccess");
// Get the public download URL
Uri downloadUri = taskSnapshot.getMetadata().getDownloadUrl();
// [START_EXCLUDE]
broadcastUploadFinished(downloadUri, fileUri);
showUploadFinishedNotification(downloadUri, fileUri);
taskCompleted();
HEPicture hePicture = extras.getParcelable(HE_PICTURE);
sendNotification(hePicture);
// [END_EXCLUDE]
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Upload failed
Log.w(TAG, "uploadFromUri:onFailure", exception);
// [START_EXCLUDE]
broadcastUploadFinished(null, fileUri);
showUploadFinishedNotification(null, fileUri);
taskCompleted();
// [END_EXCLUDE]
}
});
}
/**
* Broadcast finished upload (success or failure).
*
* @return true if a running receiver received the broadcast.
*/
private boolean broadcastUploadFinished(@Nullable Uri downloadUrl, @Nullable Uri fileUri) {
boolean success = downloadUrl != null;
String action = success ? UPLOAD_COMPLETED : UPLOAD_ERROR;
Intent broadcast = new Intent(action)
.putExtra(EXTRA_DOWNLOAD_URL, downloadUrl)
.putExtra(EXTRA_FILE_URI, fileUri);
return LocalBroadcastManager.getInstance(getApplicationContext())
.sendBroadcast(broadcast);
}
/**
* Show a notification for a finished upload.
*/
private void showUploadFinishedNotification(@Nullable Uri downloadUrl, @Nullable Uri fileUri) {
// Hide the progress notification
dismissProgressNotification();
// Make Intent to HomePageActivity
Intent intent = new Intent(this, DownloadActivity.class)
.putExtra(EXTRA_DOWNLOAD_URL, downloadUrl)
.putExtra(EXTRA_FILE_URI, fileUri)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
boolean success = downloadUrl != null;
String caption = success ? getString(R.string.upload_success) : getString(R.string.upload_failure);
showFinishedNotification(caption, intent, success);
}
private void sendNotification(HEPicture hePicture) {
JSONObject jsonObject = new JSONObject();
try {
JSONObject data = new JSONObject();
data.put(PLACE, hePicture.getPlace());
data.put(DATE, hePicture.getDate());
data.put(ALTITUDE, hePicture.getAltitude());
data.put(LATITUDE, hePicture.getLatitude());
data.put(LONGITUDE, hePicture.getLongitude());
data.put(LAST_PATH_SEGMENT, hePicture.getLastPathSegment());
jsonObject.put(TO, TOPIC);
jsonObject.put(DATA, data);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(TAG, "sendNotification: " + jsonObject.toString());
HTTPRequestManager.doPostRequest("", jsonObject.toString(), this, HTTPRequestManager.SEND_NOTIFICATION);
}
@Override
public void onRequestDone(String result, int requestId) {
switch (requestId) {
case HTTPRequestManager.SEND_NOTIFICATION:
JSONObject jsonObject;
try {
jsonObject = new JSONObject(result);
int messageId = jsonObject.getInt(MESSAGE_ID);
if (messageId >= 0) {
Toast.makeText(getApplicationContext(), R.string.picture_sent, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
break;
}
}
}
| true
|
4daf939a6984ce85d89235eeecad6b2a785b1eca
|
Java
|
mmarvinedge/POP3-Cardapio
|
/src/main/java/com/popsales/model/ProductDay.java
|
UTF-8
| 1,929
| 1.976563
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.popsales.model;
import java.io.Serializable;
/**
*
* @author Renato
*/
public class ProductDay implements Serializable{
private Boolean naoVenderDom = false;
private Boolean naoVenderSeg = false;
private Boolean naoVenderTer = false;
private Boolean naoVenderQua = false;
private Boolean naoVenderQui = false;
private Boolean naoVenderSex = false;
private Boolean naoVenderSab = false;
public Boolean getNaoVenderDom() {
return naoVenderDom;
}
public void setNaoVenderDom(Boolean naoVenderDom) {
this.naoVenderDom = naoVenderDom;
}
public Boolean getNaoVenderSeg() {
return naoVenderSeg;
}
public void setNaoVenderSeg(Boolean naoVenderSeg) {
this.naoVenderSeg = naoVenderSeg;
}
public Boolean getNaoVenderTer() {
return naoVenderTer;
}
public void setNaoVenderTer(Boolean naoVenderTer) {
this.naoVenderTer = naoVenderTer;
}
public Boolean getNaoVenderQua() {
return naoVenderQua;
}
public void setNaoVenderQua(Boolean naoVenderQua) {
this.naoVenderQua = naoVenderQua;
}
public Boolean getNaoVenderQui() {
return naoVenderQui;
}
public void setNaoVenderQui(Boolean naoVenderQui) {
this.naoVenderQui = naoVenderQui;
}
public Boolean getNaoVenderSex() {
return naoVenderSex;
}
public void setNaoVenderSex(Boolean naoVenderSex) {
this.naoVenderSex = naoVenderSex;
}
public Boolean getNaoVenderSab() {
return naoVenderSab;
}
public void setNaoVenderSab(Boolean naoVenderSab) {
this.naoVenderSab = naoVenderSab;
}
}
| true
|
02100df28bda99b03c8a9f8d4200c756f9089986
|
Java
|
TruthABC/AACloudDisk
|
/app/src/main/java/hk/hku/cs/aaclouddisk/main/TabPagerAdapter.java
|
UTF-8
| 1,388
| 2.484375
| 2
|
[] |
no_license
|
package hk.hku.cs.aaclouddisk.main;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import hk.hku.cs.aaclouddisk.main.tab.MP3Fragment;
import hk.hku.cs.aaclouddisk.main.tab.FilesFragment;
import hk.hku.cs.aaclouddisk.main.tab.MeFragment;
public class TabPagerAdapter extends FragmentPagerAdapter {
public static final String[] TITLES = {"Music", "Files", "Me"};
private Fragment[] fragments;
public TabPagerAdapter(FragmentManager fm) {
super(fm);
fragments = new Fragment[TITLES.length];
}
public MP3Fragment getMP3Fragment() { return (MP3Fragment)fragments[0]; }
public FilesFragment getFilesFragment() { return (FilesFragment)fragments[1]; }
@Override
public int getCount() {
return TITLES.length;
}
@Override
public Fragment getItem(int position) {
if (fragments[position] == null) {
switch (position) {
case 0: fragments[position] = new MP3Fragment(); break;
case 1: fragments[position] = new FilesFragment(); break;
case 2: fragments[position] = new MeFragment(); break;
}
}
return fragments[position];
}
@Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
}
| true
|
4459c39fa3a831c26e690b603b5dfabd851e3be4
|
Java
|
caprit/pro-netty
|
/src/main/java/com/itjoin/pro_netty/test/TestProxyRpc.java
|
UTF-8
| 916
| 2.25
| 2
|
[] |
no_license
|
package com.itjoin.pro_netty.test;
import com.itjoin.pro_netty.controller.LoginController;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestProxyRpc {
public static void main(String[] args) throws InterruptedException {
//注意,此处扫描包名,不能包含服务器的启动类所在的包
//只能包含具体测试类,以及代理类所在的包
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(
new String[]{"com.itjoin.pro_netty.controller",
"com.itjoin.pro_netty.proxy"});
LoginController loginController= context.
getBean(LoginController.class);
Object result = loginController.getUserByName("张三");
System.out.println(result);
Thread.sleep(100000000);
}
}
| true
|
503f8e6981c910d8639cb7f9d6ffb5deb2aadf69
|
Java
|
thobho/console-game
|
/src/com/thobho/ConsoleColor.java
|
UTF-8
| 754
| 2.8125
| 3
|
[] |
no_license
|
package com.thobho;
public class ConsoleColor {
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m";
static String red(String input){
return ANSI_RED + input + ANSI_RESET;
}
static String green(String input){
return ANSI_GREEN + input + ANSI_GREEN;
}
}
| true
|
28a7ebecedfdc95cd74552538a7fc39a73db1aa1
|
Java
|
septangle/onwingtech
|
/onwing-comm-api/src/main/java/com/onwing/household/biz/dto/AccessRecordDto.java
|
UTF-8
| 886
| 2.109375
| 2
|
[] |
no_license
|
package com.onwing.household.biz.dto;
import java.util.Date;
public class AccessRecordDto {
private Long id;
private Long householdId;
private Date outOffTime;
private String outOff;
private String photoUrl;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getHouseholdId() {
return householdId;
}
public void setHouseholdId(Long householdId) {
this.householdId = householdId;
}
public Date getOutOffTime() {
return outOffTime;
}
public void setOutOffTime(Date outOffTime) {
this.outOffTime = outOffTime;
}
public String getOutOff() {
return outOff;
}
public void setOutOff(String outOff) {
this.outOff = outOff == null ? null : outOff.trim();
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
}
| true
|
36417d06b69001736e90dff3240b98cf6bfadbea
|
Java
|
f0xJu/2018.07.12_pagrindai
|
/src/Thourth/ConstrucorExample.java
|
UTF-8
| 281
| 2.59375
| 3
|
[] |
no_license
|
package Thourth;
public class ConstrucorExample {
public ConstrucorExample (){
this(4);
}
public ConstrucorExample (int a){
System.out.println(a);
printData();
}
private void printData(){
System.out.println("Sveiki");
}
}
| true
|
e1879278f90f87ead5aaa72cf3fef4df495396d8
|
Java
|
ernestoMartineze/METAL
|
/frisa-servicios/frisa-servicios-ejb/src/main/java/mx/frisa/tic/datos/entidades/XxfrLineaCaptura.java
|
UTF-8
| 12,555
| 1.726563
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mx.frisa.tic.datos.entidades;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author soultech
*/
@Entity
@Table(name = "XXFR_LINEA_CAPTURA")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "XxfrLineaCaptura.findAll", query = "SELECT x FROM XxfrLineaCaptura x")
, @NamedQuery(name = "XxfrLineaCaptura.findByIdlineacaptura", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.idlineacaptura = :idlineacaptura")
, @NamedQuery(name = "XxfrLineaCaptura.findByLineacapturaref", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.lineacapturaref = :lineacapturaref")
, @NamedQuery(name = "XxfrLineaCaptura.findBySistemaorigen", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.sistemaorigen = :sistemaorigen")
, @NamedQuery(name = "XxfrLineaCaptura.findByLineacaptura", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.lineacaptura = :lineacaptura")
, @NamedQuery(name = "XxfrLineaCaptura.findByReferencia", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.referencia = :referencia")
, @NamedQuery(name = "XxfrLineaCaptura.findByFechacreacion", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.fechacreacion = :fechacreacion")
, @NamedQuery(name = "XxfrLineaCaptura.findByFechavigencia", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.fechavigencia = :fechavigencia")
, @NamedQuery(name = "XxfrLineaCaptura.findByMontolineacaptura", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.montolineacaptura = :montolineacaptura")
, @NamedQuery(name = "XxfrLineaCaptura.findByEstatuslc", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.estatuslc = :estatuslc")
, @NamedQuery(name = "XxfrLineaCaptura.findByBanco", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.banco = :banco")
, @NamedQuery(name = "XxfrLineaCaptura.findByCuentabancaria", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.cuentabancaria = :cuentabancaria")
, @NamedQuery(name = "XxfrLineaCaptura.findByEntidadlegal", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.entidadlegal = :entidadlegal")
, @NamedQuery(name = "XxfrLineaCaptura.findByUnidadnegocio", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.unidadnegocio = :unidadnegocio")
, @NamedQuery(name = "XxfrLineaCaptura.findByDivision", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.division = :division")
, @NamedQuery(name = "XxfrLineaCaptura.findByCentrocostosproyecto", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.centrocostosproyecto = :centrocostosproyecto")
, @NamedQuery(name = "XxfrLineaCaptura.findByNumerorecibo", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.numerorecibo = :numerorecibo")
, @NamedQuery(name = "XxfrLineaCaptura.findByTipocobranza", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.tipocobranza = :tipocobranza")
, @NamedQuery(name = "XxfrLineaCaptura.findByFolioacuerdocobranza", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.folioacuerdocobranza = :folioacuerdocobranza")
, @NamedQuery(name = "XxfrLineaCaptura.findByMontoacuerdocobranza", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.montoacuerdocobranza = :montoacuerdocobranza")
, @NamedQuery(name = "XxfrLineaCaptura.findByInteresmoratoriocondonado", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.interesmoratoriocondonado = :interesmoratoriocondonado")
, @NamedQuery(name = "XxfrLineaCaptura.findByOrdinariocondonado", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.ordinariocondonado = :ordinariocondonado")
, @NamedQuery(name = "XxfrLineaCaptura.findByCapitalrentacondonada", query = "SELECT x FROM XxfrLineaCaptura x WHERE x.capitalrentacondonada = :capitalrentacondonada")})
public class XxfrLineaCaptura implements Serializable {
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idlineacaptura", fetch = FetchType.LAZY)
private List<XxfrLineaCapturaFactura> xxfrLineaCapturaFacturaList;
private static final long serialVersionUID = 1L;
// @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
@Id
@Basic(optional = false)
@NotNull
@Column(name = "IDLINEACAPTURA")
private BigDecimal idlineacaptura;
@Size(max = 20)
@Column(name = "LINEACAPTURAREF")
private String lineacapturaref;
@Size(max = 20)
@Column(name = "SISTEMAORIGEN")
private String sistemaorigen;
@Size(max = 50)
@Column(name = "LINEACAPTURA")
private String lineacaptura;
@Size(max = 20)
@Column(name = "REFERENCIA")
private String referencia;
@Column(name = "FECHACREACION")
@Temporal(TemporalType.TIMESTAMP)
private Date fechacreacion;
@Column(name = "FECHAVIGENCIA")
@Temporal(TemporalType.TIMESTAMP)
private Date fechavigencia;
@Column(name = "MONTOLINEACAPTURA")
private BigDecimal montolineacaptura;
@Size(max = 20)
@Column(name = "ESTATUSLC")
private String estatuslc;
@Size(max = 20)
@Column(name = "BANCO")
private String banco;
@Size(max = 20)
@Column(name = "CUENTABANCARIA")
private String cuentabancaria;
@Size(max = 20)
@Column(name = "ENTIDADLEGAL")
private String entidadlegal;
@Size(max = 20)
@Column(name = "UNIDADNEGOCIO")
private String unidadnegocio;
@Size(max = 20)
@Column(name = "DIVISION")
private String division;
@Size(max = 20)
@Column(name = "CENTROCOSTOSPROYECTO")
private String centrocostosproyecto;
@Size(max = 20)
@Column(name = "NUMERORECIBO")
private String numerorecibo;
@Size(max = 20)
@Column(name = "TIPOCOBRANZA")
private String tipocobranza;
@Size(max = 20)
@Column(name = "FOLIOACUERDOCOBRANZA")
private String folioacuerdocobranza;
@Size(max = 20)
@Column(name = "MONTOACUERDOCOBRANZA")
private String montoacuerdocobranza;
@Size(max = 20)
@Column(name = "INTERESMORATORIOCONDONADO")
private String interesmoratoriocondonado;
@Size(max = 20)
@Column(name = "ORDINARIOCONDONADO")
private String ordinariocondonado;
@Size(max = 20)
@Column(name = "CAPITALRENTACONDONADA")
private String capitalrentacondonada;
public XxfrLineaCaptura() {
}
public XxfrLineaCaptura(BigDecimal idlineacaptura) {
this.idlineacaptura = idlineacaptura;
}
public BigDecimal getIdlineacaptura() {
return idlineacaptura;
}
public void setIdlineacaptura(BigDecimal idlineacaptura) {
this.idlineacaptura = idlineacaptura;
}
public String getLineacapturaref() {
return lineacapturaref;
}
public void setLineacapturaref(String lineacapturaref) {
this.lineacapturaref = lineacapturaref;
}
public String getSistemaorigen() {
return sistemaorigen;
}
public void setSistemaorigen(String sistemaorigen) {
this.sistemaorigen = sistemaorigen;
}
public String getLineacaptura() {
return lineacaptura;
}
public void setLineacaptura(String lineacaptura) {
this.lineacaptura = lineacaptura;
}
public String getReferencia() {
return referencia;
}
public void setReferencia(String referencia) {
this.referencia = referencia;
}
public Date getFechacreacion() {
return fechacreacion;
}
public void setFechacreacion(Date fechacreacion) {
this.fechacreacion = fechacreacion;
}
public Date getFechavigencia() {
return fechavigencia;
}
public void setFechavigencia(Date fechavigencia) {
this.fechavigencia = fechavigencia;
}
public BigDecimal getMontolineacaptura() {
return montolineacaptura;
}
public void setMontolineacaptura(BigDecimal montolineacaptura) {
this.montolineacaptura = montolineacaptura;
}
public String getEstatuslc() {
return estatuslc;
}
public void setEstatuslc(String estatuslc) {
this.estatuslc = estatuslc;
}
public String getBanco() {
return banco;
}
public void setBanco(String banco) {
this.banco = banco;
}
public String getCuentabancaria() {
return cuentabancaria;
}
public void setCuentabancaria(String cuentabancaria) {
this.cuentabancaria = cuentabancaria;
}
public String getEntidadlegal() {
return entidadlegal;
}
public void setEntidadlegal(String entidadlegal) {
this.entidadlegal = entidadlegal;
}
public String getUnidadnegocio() {
return unidadnegocio;
}
public void setUnidadnegocio(String unidadnegocio) {
this.unidadnegocio = unidadnegocio;
}
public String getDivision() {
return division;
}
public void setDivision(String division) {
this.division = division;
}
public String getCentrocostosproyecto() {
return centrocostosproyecto;
}
public void setCentrocostosproyecto(String centrocostosproyecto) {
this.centrocostosproyecto = centrocostosproyecto;
}
public String getNumerorecibo() {
return numerorecibo;
}
public void setNumerorecibo(String numerorecibo) {
this.numerorecibo = numerorecibo;
}
public String getTipocobranza() {
return tipocobranza;
}
public void setTipocobranza(String tipocobranza) {
this.tipocobranza = tipocobranza;
}
public String getFolioacuerdocobranza() {
return folioacuerdocobranza;
}
public void setFolioacuerdocobranza(String folioacuerdocobranza) {
this.folioacuerdocobranza = folioacuerdocobranza;
}
public String getMontoacuerdocobranza() {
return montoacuerdocobranza;
}
public void setMontoacuerdocobranza(String montoacuerdocobranza) {
this.montoacuerdocobranza = montoacuerdocobranza;
}
public String getInteresmoratoriocondonado() {
return interesmoratoriocondonado;
}
public void setInteresmoratoriocondonado(String interesmoratoriocondonado) {
this.interesmoratoriocondonado = interesmoratoriocondonado;
}
public String getOrdinariocondonado() {
return ordinariocondonado;
}
public void setOrdinariocondonado(String ordinariocondonado) {
this.ordinariocondonado = ordinariocondonado;
}
public String getCapitalrentacondonada() {
return capitalrentacondonada;
}
public void setCapitalrentacondonada(String capitalrentacondonada) {
this.capitalrentacondonada = capitalrentacondonada;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idlineacaptura != null ? idlineacaptura.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof XxfrLineaCaptura)) {
return false;
}
XxfrLineaCaptura other = (XxfrLineaCaptura) object;
if ((this.idlineacaptura == null && other.idlineacaptura != null) || (this.idlineacaptura != null && !this.idlineacaptura.equals(other.idlineacaptura))) {
return false;
}
return true;
}
@Override
public String toString() {
return "mx.frisa.tic.datos.entidades.XxfrLineaCaptura[ idlineacaptura=" + idlineacaptura + " ]";
}
@XmlTransient
public List<XxfrLineaCapturaFactura> getXxfrLineaCapturaFacturaList() {
return xxfrLineaCapturaFacturaList;
}
public void setXxfrLineaCapturaFacturaList(List<XxfrLineaCapturaFactura> xxfrLineaCapturaFacturaList) {
this.xxfrLineaCapturaFacturaList = xxfrLineaCapturaFacturaList;
}
}
| true
|
d049cc13062ff5ee632261cce9da48971dd10437
|
Java
|
gewuxy/jx_backend
|
/yaya/jbms/src/main/java/cn/medcn/jbms/controller/UserController.java
|
UTF-8
| 1,148
| 2
| 2
|
[] |
no_license
|
package cn.medcn.jbms.controller;
import cn.medcn.common.ctrl.BaseController;
import cn.medcn.common.excptions.SystemException;
import cn.medcn.jbms.security.Principal;
import cn.medcn.jbms.utils.SubjectUtils;
import cn.medcn.sys.model.SystemUser;
import cn.medcn.sys.service.SystemUserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by lixuan on 2017/5/3.
*/
@Controller
@RequestMapping(value="/sys/user")
public class UserController extends BaseController {
@Autowired
private SystemUserService systemUserService;
@RequestMapping(value="/list")
public String list(){
return "";
}
@RequestMapping(value="/info")
public String info(Model model) throws SystemException{
Integer userid = SubjectUtils.getCurrentUserid();
SystemUser user = systemUserService.findUserHasRole(userid);
model.addAttribute("user", user);
return "/sys/userInfo";
}
}
| true
|
34d8eea2f477e029e78ee0fabf7ae69775128e0c
|
Java
|
edgardleal/r2d2
|
/src/main/java/br/com/r2d2/controller/FileController.java
|
UTF-8
| 1,612
| 2.3125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
*
*/
package br.com.r2d2.controller;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.r2d2.infra.Config;
/**
* Última compilação: 01/01/2013 00:00
*
* @author Edgard Leal
* @since 29/11/2013 09:03:13
* @version 0.0.0.0
*
*/
@Resource
public class FileController {
private Result result;
private Config config;
public FileController(Result result, Config config) {
super();
this.config = config;
this.result = result;
}
@Path("/file")
public void navigate() {
result.redirectTo(getClass()).navigate(null);
}
@Path("file/{path*}")
public void navigate(String path) {
try {
File file;
if (path != null && !path.isEmpty())
file = new File(config.repositoryFolder(), path);
else
file = config.repositoryFolder();
List<File> files = Arrays.asList(file.listFiles());
String folderPath = file.getAbsolutePath().replace(
config.repositoryFolder().getAbsolutePath(), "");
result.include("status", "ok");
result.include("paths", folderPath.split("/"));
result.include("folder", folderPath);
result.include("files", files);
} catch (Exception ex) {
result.redirectTo(ErrorController.class).view(ex);
}
}
public void list(File file) {
List<File> files = Arrays.asList(file.listFiles());
result.include("status", "ok");
result.include(
"folder",
file.getAbsolutePath().replace(
config.repositoryFolder().getAbsolutePath(), ""));
result.include("files", files);
}
}
| true
|
32d6911a8e7b34b50b8a051b686d0337bef5fa27
|
Java
|
eagledeveloper/Learning
|
/learning/src/ch/gmtech/learning/lesson3/Course.java
|
UTF-8
| 447
| 2.8125
| 3
|
[] |
no_license
|
package ch.gmtech.learning.lesson3;
public class Course {
private String name, description;
private int number;
public Course(String name, int number, String description) {
this.name = name;
this.number = number;
this.description = description;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
public String getDescription() {
return description;
}
}
| true
|
155390234968b6d7f9f12ef63f28c4db9ae2d3c1
|
Java
|
SofianeCDL/Projet_Supernova_Creation_Numerique
|
/src/Nuage.java
|
UTF-8
| 4,695
| 3
| 3
|
[] |
no_license
|
import processing.core.PApplet;
import processing.core.PVector;
import java.util.ArrayList;
public class Nuage extends PApplet {
private ArrayList listeElementsNuage; //Liste des éléments du nuage.
private int nbElementNuage; //Nombre d'élément dans le nuage.
private ElementNuage elementNuageZero; //Element zero.
private int iterateurFin; //Itérateur de fin des éléments utilisés.
private int iterateurDebut; //Itérateur de début des éléments utilisés.
private ArrayList particuleZero; //Liste des éléments zero.
private int alpha; //Alpha des éléménents.
//Constructeur
public Nuage (int nbParticuleNuage) {
this.listeElementsNuage = new ArrayList();
this.nbElementNuage = nbParticuleNuage;
//génération de la ParticuleNuage zero.
this.elementNuageZero = new ElementNuage(Test.processing.width / 2.f, Test.processing.height / 2.f);
this.listeElementsNuage.add(this.elementNuageZero);
this.iterateurDebut = 0;
this.iterateurFin = 0;
this.particuleZero = new ArrayList<>();
this.alpha = 0;
}
//************************************************** CREATION *************************************************
/** ROLE : création des nouvelles particules entre itérateurDebut et itérateurFin.
* PRECONDITION : Nombre de particules doit être > 150.
*/
public void creationParticule() {
if (this.nbElementNuage > 150) {
for (int i = iterateurDebut; i <= iterateurFin; ++i) {
ElementNuage p = (ElementNuage) this.listeElementsNuage.get(i);
if (p.isfinAcceleration()) { //si l'acceleration est terminé.
if (p.isElementZero()) { //si la ParticuleNuage, génère pleins de nouvelles ParticuleNuage.
for (int j = 0; j < this.nbElementNuage; ++j) {
this.listeElementsNuage.add(p.nouvPoint());
}
}else { //sinon génère qu'un seul point.
this.listeElementsNuage.add(p.nouvPoint());
}
if (!p.isElementZero() && random(1) < 0.01) { //de temps en temps génère un nouveau point.
this.listeElementsNuage.add(p.nouvPoint());
}
}
}
this.iterateurDebut = this.iterateurFin + 1;
this.iterateurFin = this.listeElementsNuage.size();
}
this.nbElementNuage--;
}
//************************************************** VIE *************************************************
/** ROLE : update des particules, renvois "True" quand toutes les particules ont bougé.
* @return boolean : "true" quand toutes les particules ont fini de bouger.
*/
public boolean updateParticules() {
boolean finis = false;
this.etoileNeutron(); //etoile à neutron central.
for(int i = 0; i < this.listeElementsNuage.size(); ++i) { //Pour tout les éléments de nuage.
ElementNuage p = (ElementNuage) this.listeElementsNuage.get(i);
p.update();
p.drawElement();
finis = p.isfinAcceleration(); //Tant que toutes les particules n'ont pas fini de bouger, finis = false.
}
return finis; //"false" quand toutes les particules n'ont pas bougé. "true" quand elles ont toutes bougés.
}
//-------------------------------------------------
/** ROLE : condition d'arrêt de la classe nuage.
*
* @return boolean : "true" si le compteur d'éléments descend en dessous de 150.
*/
public boolean conditionArret() {
return this.nbElementNuage <= 150;
}
//******************************************* ETOILE A NEUTRONS ****************************************************
/** ROLE : étoile à neutron au centre du nuage. */
private void etoileNeutron() {
if (this.alpha <= 255) { //Test si l'alpha n'est pas au maximum.
this.alpha++;
}
PVector centreEtoile = new PVector(Test.processing.width / 2.f, Test.processing.height / 2.f); //L'étoile est rencentré.
float angle = random(0,2) * PI; //Choix d'un angle de direction.
PVector mouvement = new PVector(cos(angle)*2, sin(angle*2)); //Mouvement de deplacement.
Test.processing.fill(216,191,216, this.alpha);
Test.processing.circle(centreEtoile.x, centreEtoile.y, 20);
centreEtoile.add(mouvement); //Bouge l'etoile, créer un effet de sursaut.
Test.processing.circle(centreEtoile.x, centreEtoile.y, 20);
}
} //FIN DE CLASSE
| true
|
2bf46443c5c71439e9588e18fb98c7d85c0fb6aa
|
Java
|
ddalcino/eCommerceWebApp
|
/src/main/java/edu/csueb/cs6320/bean/SaleItemOffer.java
|
UTF-8
| 2,190
| 2.40625
| 2
|
[] |
no_license
|
package edu.csueb.cs6320.bean;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Entity
public class SaleItemOffer implements Serializable {
private static final long serialVersionUID = 1L;
/////////////////////////////////////////////////////////////////
// DATA MEMBERS
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
// this should be an actual saleitem
// @Column(name="saleItem_id")
// private long saleItemId;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="SaleItem_id")
private SaleItem saleItem;
private double price;
@Column(name="qtyAvailable")
private int quantityAvailable;
// @Column(name="seller_id")
// private long sellerId;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="Seller_id")
private User seller;
// @ManyToOne(fetch = FetchType.EAGER)
// @JoinColumn(name="SaleItem_id")
// private SaleItem saleItem;
/////////////////////////////////////////////////////////////////
// MEMBER METHODS
public SaleItemOffer() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
// public long getSaleItemId() {
// return saleItemId;
// }
// public void setSaleItemId(long saleItemId) {
// this.saleItemId = saleItemId;
// }
// public long getSellerId() {
// return sellerId;
// }
// public void setSellerId(long sellerId) {
// this.sellerId = sellerId;
// }
public double getPrice() {
return price;
}
public User getSeller() {
return seller;
}
public void setSeller(User seller) {
this.seller = seller;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantityAvailable() {
return quantityAvailable;
}
public void setQuantityAvailable(int quantityAvailable) {
this.quantityAvailable = quantityAvailable;
}
public SaleItem getSaleItem() {
return saleItem;
}
public void setSaleItem(SaleItem saleItem) {
this.saleItem = saleItem;
}
}
| true
|
601e8cfe302028165196e5db389c96cf92305f6f
|
Java
|
zxk1997/xypx
|
/xypx-cloud-api/src/main/java/com/zxk1997/px/api/consumer/Models/ActContainer.java
|
UTF-8
| 4,251
| 2.375
| 2
|
[] |
no_license
|
package com.zxk1997.px.api.consumer.Models;
import java.util.Date;
import java.util.HashMap;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
public class ActContainer {
private String id;
private String title;//标题
private String address;//活动地点
private String phone;//主办方手机
@DateTimeFormat( pattern = "yyyy-MM-dd HH:mm" )
private Date s,e;//活动开始/结束时间
@DateTimeFormat( pattern = "yyyy-MM-dd HH:mm" )
private Date ps,pe;//报名开始/结束时间
private String placard;//海报链接
private int plimit;//人数上限
private String describe;//活动/讲座内容简述
private String content;//活动/讲座内容
private String[] tags1,tags2;//活动/讲座标签,人群标签
private String rm;//报名成功后提示信息
private int joincnt;
public HashMap<String, Object> getMap() {
return map;
}
public void setMap(HashMap<String, Object> map) {
this.map = map;
}
private HashMap<String, Object> map=new HashMap<>();
private String stirngCheck(String value,String key,String name,int maxLen){
if(value!=null){
int len = value.length();
if(len>0)
if(maxLen>=len){
map.put(key, value);
return "";
}else return name+"的长度不能超过"+maxLen+" ";
}
return name+"不能为空 ";
}
private String dateCheck(Date sdate,String sname,Date edate,String ename,String name){
if(sdate!=null && edate!=null && sdate.getTime()<edate.getTime() && edate.getTime()>new Date().getTime()){
map.put(sname, sdate);
map.put(ename, edate);
return "";
}
return name+" ";
}
public String check(){
String str="";
str+=stirngCheck(title,"title","标题",50);
str+=stirngCheck(address,"address","地点",200);
str+=stirngCheck(phone,"phone","手机号码",11);
str+=dateCheck(s,"s",e,"e","活动/讲座时间设置错误");
str+=dateCheck(ps,"ps",pe,"pe","报名时间设置错误");
str+=stirngCheck(placard,"placard","海报",100);
if(plimit<0)str+="人数上限设置错误 ";
else map.put("plimit", plimit);
str+=stirngCheck(describe,"summary","描述",100);
if(content!=null)map.put("content", content);
else str+="内容错误 ";
if(tags1!=null && tags2!=null && tags1.length>0&& tags2.length>0){
map.put("tags1", tags1);
map.put("tags2", tags2);
}else str+="标签不能为空 ";
if(rm==null || rm.length()<100)map.put("rm", rm);
else str+="报名成功提示信息过长 ";
return str;
}
public int getJoincnt() {
return joincnt;
}
public void setJoincnt(int joincnt) {
this.joincnt = joincnt;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getRm() {
return rm;
}
public void setRm(String rm) {
this.rm = rm;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Date getS() {
return s;
}
public void setS(Date s) {
this.s = s;
}
public Date getE() {
return e;
}
public void setE(Date e) {
this.e = e;
}
public Date getPs() {
return ps;
}
public void setPs(Date ps) {
this.ps = ps;
}
public Date getPe() {
return pe;
}
public void setPe(Date pe) {
this.pe = pe;
}
public String getPlacard() {
return placard;
}
public void setPlacard(String placard) {
this.placard = placard;
}
public int getPlimit() {
return plimit;
}
public void setPlimit(int plimit) {
this.plimit = plimit;
}
public String getDescribe() {
return describe;
}
public void setDescribe(String describe) {
this.describe = describe;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String[] getTags1() {
return tags1;
}
public void setTags1(String[] tags1) {
this.tags1 = tags1;
}
public String[] getTags2() {
return tags2;
}
public void setTags2(String[] tags2) {
this.tags2 = tags2;
}
}
| true
|
60e39064d5917c8408216e27ad46606ba7f06878
|
Java
|
cristianbd95/DAW2
|
/MySqlJAVA/src/hilos25112020/MainExecutor.java
|
UTF-8
| 1,047
| 2.796875
| 3
|
[] |
no_license
|
package hilos25112020;
import java.sql.Connection;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MainExecutor {
public static void main(String[] args) {
final long startTime = System.currentTimeMillis();
Conexion1 c = new Conexion1(true, "salud");
Connection conexion = c.getConexion();
OperacionesCrud oc = new OperacionesCrud(conexion);
int numeroRun = 3;
Ventana v1 = new Ventana("Ventana 1");
Ventana v2 = new Ventana("Ventana 2");
Ventana v3 = new Ventana("Ventana 3");
v1.setVisible(true);
v2.setVisible(true);
v3.setVisible(true);
ExecutorService executor = Executors.newFixedThreadPool(numeroRun);
Runnable cliente1 = new Cliente(conexion,v1);
Runnable cliente2 = new Cliente(conexion,v2);
Runnable cliente3 = new Cliente(conexion,v3);
executor.execute(cliente1);
executor.execute(cliente2);
executor.execute(cliente3);
}
}
| true
|
bc9f96cb8724d83f03bbdd3bf449d48748b8d736
|
Java
|
yukazhydent/Pemograman-2
|
/Latihan1.java
|
UTF-8
| 1,019
| 3.53125
| 4
|
[] |
no_license
|
import java.util.Scanner;
public class Latihan1{
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Masukan nilai Mahasiswa (A/B/C/D/E):");
String nilai = s.next();
String ket = "";
switch (nilai) {
case "A":
ket = "Excellent!";
break;
case "B":
ket = "Good job!";
break;
case "C":
ket = "Study Harder!";
break;
default:
ket = "Sorry, you failed.";
break;
}
System.out.println("Comment: "+ket);
System.out.println("Masukkan tiga nilai ujian anda untuk dihitung rata-ratanya:");
int nilai1 = s.nextInt();
int nilai2 = s.nextInt();
int nilai3 = s.nextInt();
double eva = (double)(nilai1+nilai2+nilai3)/3;
if (eva >= 60) {
System.out.println("Nilai rata-rata ujian anda adalah "+eva+", Congratulations :D");
}else{
System.out.println("Nilai rata-rata ujian anda adalah "+eva+", Belajar lebih baik lagi :(");
}
}
}
| true
|
c6eca7f1f8f286c1f1113dc692e871b56dbf3e45
|
Java
|
ahpoder/pasoos2007hbc
|
/Module3/HotTargui-ProgProj-F08-Semi/src/hottargui/strategy/SettlementOnlyPutUnitsStrategy.java
|
UTF-8
| 416
| 2.484375
| 2
|
[] |
no_license
|
package hottargui.strategy;
import hottargui.framework.*;
public class SettlementOnlyPutUnitsStrategy implements PutUnitsStrategy {
public boolean isPutValid(Player p, Tile t, int count) {
if ((p.getCoins() >= count) &&
(t.getOwnerColor() == p.getColor()) &&
(t.getType() == TileType.Settlement || count == 0)) {
return false;
}
else{
return true;
}
}
}
| true
|
d11e4d8f628d07f34ae78adf2d7ae1046ae15fc7
|
Java
|
kartben/azure-iot-sdk-java
|
/iot-e2e-tests/common/src/main/java/com/microsoft/azure/sdk/iot/common/helpers/ErrorInjectionHelper.java
|
UTF-8
| 6,376
| 2
| 2
|
[
"MIT"
] |
permissive
|
/*
* Copyright (c) Microsoft. All rights reserved.
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
package com.microsoft.azure.sdk.iot.common.helpers;
import com.microsoft.azure.sdk.iot.device.Message;
import java.util.UUID;
public class ErrorInjectionHelper
{
public static final String FaultType_Tcp = "KillTcp";
public static final String FaultType_AmqpConn = "KillAmqpConnection";
public static final String FaultType_AmqpSess = "KillAmqpSession";
public static final String FaultType_AmqpCBSReq = "KillAmqpCBSLinkReq";
public static final String FaultType_AmqpCBSResp = "KillAmqpCBSLinkResp";
public static final String FaultType_AmqpD2C = "KillAmqpD2CLink";
public static final String FaultType_AmqpC2D = "KillAmqpC2DLink";
public static final String FaultType_AmqpTwinReq = "KillAmqpTwinLinkReq";
public static final String FaultType_AmqpTwinResp = "KillAmqpTwinLinkResp";
public static final String FaultType_AmqpMethodReq = "KillAmqpMethodReqLink";
public static final String FaultType_AmqpMethodResp = "KillAmqpMethodRespLink";
public static final String FaultType_Throttle = "InvokeThrottling";
public static final String FaultType_QuotaExceeded = "InvokeMaxMessageQuota";
public static final String FaultType_Auth = "InvokeAuthError";
public static final String FaultType_GracefulShutdownAmqp = "ShutDownAmqp";
public static final String FaultType_GracefulShutdownMqtt = "ShutDownMqtt";
public static final String FaultCloseReason_Boom = "Boom";
public static final String FaultCloseReason_Bye = "byebye";
public static final int DefaultDelayInSec = 1;
public static final int DefaultDurationInSec = 5;
public static Message tcpConnectionDropErrorInjectionMessage(int delayInSecs, int durationInSecs)
{
return createMessageWithErrorInjectionProperties(FaultType_Tcp, FaultCloseReason_Boom, delayInSecs, durationInSecs);
}
public static Message amqpsConnectionDropErrorInjectionMessage(int delayInSecs, int durationInSecs)
{
return createMessageWithErrorInjectionProperties(FaultType_AmqpConn, FaultCloseReason_Boom, delayInSecs, durationInSecs);
}
public static Message amqpsSessionDropErrorInjectionMessage(int delayInSecs, int durationInSecs)
{
return createMessageWithErrorInjectionProperties(FaultType_AmqpSess, FaultCloseReason_Boom, delayInSecs, durationInSecs);
}
public static Message amqpsCBSReqLinkDropErrorInjectionMessage(int delayInSecs, int durationInSecs)
{
return createMessageWithErrorInjectionProperties(FaultType_AmqpCBSReq, FaultCloseReason_Boom, delayInSecs, durationInSecs);
}
public static Message amqpsCBSRespLinkDropErrorInjectionMessage(int delayInSecs, int durationInSecs)
{
return createMessageWithErrorInjectionProperties(FaultType_AmqpCBSResp, FaultCloseReason_Boom, delayInSecs, durationInSecs);
}
public static Message amqpsD2CTelemetryLinkDropErrorInjectionMessage(int delayInSecs, int durationInSecs)
{
return createMessageWithErrorInjectionProperties(FaultType_AmqpD2C, FaultCloseReason_Boom, delayInSecs, durationInSecs);
}
public static Message amqpsC2DLinkDropErrorInjectionMessage(int delayInSecs, int durationInSecs)
{
return createMessageWithErrorInjectionProperties(FaultType_AmqpC2D, FaultCloseReason_Boom, delayInSecs, durationInSecs);
}
public static Message amqpsMethodReqLinkDropErrorInjectionMessage(int delayInSecs, int durationInSecs)
{
return createMessageWithErrorInjectionProperties(FaultType_AmqpMethodReq, FaultCloseReason_Boom, delayInSecs, durationInSecs);
}
public static Message amqpsMethodRespLinkDropErrorInjectionMessage(int delayInSecs, int durationInSecs)
{
return createMessageWithErrorInjectionProperties(FaultType_AmqpMethodResp, FaultCloseReason_Boom, delayInSecs, durationInSecs);
}
public static Message amqpsTwinReqLinkDropErrorInjectionMessage(int delayInSecs, int durationInSecs)
{
return createMessageWithErrorInjectionProperties(FaultType_AmqpTwinReq, FaultCloseReason_Boom, delayInSecs, durationInSecs);
}
public static Message amqpsTwinRespLinkDropErrorInjectionMessage(int delayInSecs, int durationInSecs)
{
return createMessageWithErrorInjectionProperties(FaultType_AmqpTwinResp, FaultCloseReason_Boom, delayInSecs, durationInSecs);
}
public static Message throttledConnectionErrorInjectionMessage(int delayInSecs, int durationInSecs)
{
return createMessageWithErrorInjectionProperties(FaultType_Throttle, FaultCloseReason_Boom, delayInSecs, durationInSecs);
}
public static Message authErrorInjectionMessage(int delayInSecs, int durationInSecs)
{
return createMessageWithErrorInjectionProperties(FaultType_Auth, FaultCloseReason_Boom, delayInSecs, durationInSecs);
}
public static Message quotaExceededErrorInjectionMessage(int delayInSecs, int durationInSecs)
{
return createMessageWithErrorInjectionProperties(FaultType_QuotaExceeded, FaultCloseReason_Boom, delayInSecs, durationInSecs);
}
public static Message amqpsGracefulShutdownErrorInjectionMessage(int delayInSecs, int durationInSecs)
{
return createMessageWithErrorInjectionProperties(FaultType_GracefulShutdownAmqp, FaultCloseReason_Bye, delayInSecs, durationInSecs);
}
public static Message mqttGracefulShutdownErrorInjectionMessage(int delayInSecs, int durationInSecs)
{
return createMessageWithErrorInjectionProperties(FaultType_GracefulShutdownMqtt, FaultCloseReason_Bye, delayInSecs, durationInSecs);
}
public static Message createMessageWithErrorInjectionProperties(String faultType, String reason, int delayInSecs, int durationInSecs)
{
String dataBuffer = UUID.randomUUID().toString();
Message message = new Message(dataBuffer);
message.setProperty("AzIoTHub_FaultOperationType", faultType);
message.setProperty("AzIoTHub_FaultOperationCloseReason", reason);
message.setProperty("AzIoTHub_FaultOperationDelayInSecs", String.valueOf(delayInSecs));
message.setProperty("AzIoTHub_FaultOperationDurationInSecs", String.valueOf(durationInSecs));
return message;
}
}
| true
|
664a9e40fff1af0b2961ca13be705566121ed159
|
Java
|
nilaybesli/JavaCamp_Day4.3
|
/game/src/Concrete/SaleManager.java
|
UTF-8
| 862
| 2.625
| 3
|
[] |
no_license
|
package Concrete;
import Abstracts.SaleService;
import Entities.Campaign;
import Entities.Game;
import Entities.User;
public class SaleManager implements SaleService{
public void Sell(User user, Game game) {
System.out.println("User : "+user.getName()+ " " +user.getLastName());
System.out.println("Game : " + game.getGameName());
System.out.println("Price : " +game.getPrice());
System.out.println("Satis gerceklesti!");
}
public void sellWithCampaign(Game game, User user, Campaign campaign) {
System.out.println("User : "+user.getName()+ " " +user.getLastName());
System.out.println("Game : " + game.getGameName());
System.out.println("Price With Campaign : " + (game.getPrice()-campaign.getDiscount()));
System.out.println("Used :" +campaign.getCampaignName());
}
}
| true
|
bfa15a461b3ad1d257064a10b3cd04f3a2163fbf
|
Java
|
kenuosec/Decompiled-Whatsapp
|
/android/support/v4/content/FileProvider.java
|
UTF-8
| 32,052
| 1.703125
| 2
|
[] |
no_license
|
package android.support.v4.content;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.ProviderInfo;
import android.content.res.XmlResourceParser;
import android.net.Uri;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import com.whatsapp.arj;
import com.whatsapp.proto.E2E.Message.VideoMessage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import org.v;
import org.whispersystems.Y;
import org.whispersystems.aF;
import org.whispersystems.at;
public class FileProvider extends ContentProvider {
private static final String[] COLUMNS;
private static final File DEVICE_ROOT;
private static HashMap sCache;
private static final String[] z;
private PathStrategy mStrategy;
interface PathStrategy {
File getFileForUri(Uri uri);
Uri getUriForFile(File file);
}
class SimplePathStrategy implements PathStrategy {
private static final String[] z;
private final String mAuthority;
private final HashMap mRoots;
static {
String[] strArr = new String[8];
String str = "'mo\nm\u0004yq\u001bm\u0007cvO/\f,g\u0002=\u001du";
Object obj = -1;
String[] strArr2 = strArr;
String[] strArr3 = strArr;
int i = 0;
while (true) {
char[] toCharArray = str.toCharArray();
int length = toCharArray.length;
char[] cArr = toCharArray;
for (int i2 = 0; length > i2; i2++) {
int i3;
char c = cArr[i2];
switch (i2 % 5) {
case v.m /*0*/:
i3 = arj.Theme_radioButtonStyle;
break;
case at.g /*1*/:
i3 = 12;
break;
case at.i /*2*/:
i3 = 2;
break;
case at.o /*3*/:
i3 = 111;
break;
default:
i3 = 77;
break;
}
cArr[i2] = (char) (i3 ^ c);
}
str = new String(cArr).intern();
switch (obj) {
case v.m /*0*/:
strArr2[i] = str;
str = ";iq\u0000!\u001fifO=\bxjO'\u001car\n)Ing\u0016\"\u0007h\"\f\"\u0007jk\b8\u001bifO?\u0006cv";
i = 2;
strArr2 = strArr3;
obj = 1;
break;
case at.g /*1*/:
strArr2[i] = str;
str = "/mk\u0003(\r,v\u0000m\u001biq\u0000!\u001fi\"\f,\u0007cl\u0006.\b`\"\u001f,\u001dd\"\t\"\u001b,";
i = 3;
strArr2 = strArr3;
obj = 2;
break;
case at.i /*2*/:
strArr2[i] = str;
str = "<bc\r!\f,v\u0000m\u000fel\u000bm\ncl\t$\u000eyp\n)I~m\u00009Ijm\u001dm";
i = 4;
strArr2 = strArr3;
obj = 3;
break;
case at.o /*3*/:
strArr2[i] = str;
i = 5;
strArr2 = strArr3;
str = "\ncl\u001b(\u0007x";
obj = 4;
break;
case at.p /*4*/:
strArr2[i] = str;
i = 6;
str = "/mk\u0003(\r,v\u0000m\u000fel\u000bm\ncl\t$\u000eyp\n)I~m\u00009Ixj\u000e9Iom\u00019\bel\u001cm";
obj = 5;
strArr2 = strArr3;
break;
case at.m /*5*/:
strArr2[i] = str;
i = 7;
str = "/mk\u0003(\r,v\u0000m\u001biq\u0000!\u001fi\"\f,\u0007cl\u0006.\b`\"\u001f,\u001dd\"\t\"\u001b,";
obj = 6;
strArr2 = strArr3;
break;
case Y.f /*6*/:
strArr2[i] = str;
z = strArr3;
return;
default:
strArr2[i] = str;
str = "/mk\u0003(\r,v\u0000m\u001biq\u0000!\u001fi\"\f,\u0007cl\u0006.\b`\"\u001f,\u001dd\"\t\"\u001b,";
i = 1;
strArr2 = strArr3;
obj = null;
break;
}
}
}
public void addRoot(String str, File file) {
try {
if (TextUtils.isEmpty(str)) {
throw new IllegalArgumentException(z[0]);
}
try {
this.mRoots.put(str, file.getCanonicalFile());
} catch (Throwable e) {
throw new IllegalArgumentException(z[1] + file, e);
}
} catch (IOException e2) {
throw e2;
}
}
public File getFileForUri(Uri uri) {
String encodedPath = uri.getEncodedPath();
int indexOf = encodedPath.indexOf(47, 1);
String decode = Uri.decode(encodedPath.substring(1, indexOf));
String decode2 = Uri.decode(encodedPath.substring(indexOf + 1));
File file = (File) this.mRoots.get(decode);
if (file == null) {
try {
throw new IllegalArgumentException(z[4] + uri);
} catch (IOException e) {
throw e;
}
}
File file2 = new File(file, decode2);
try {
File canonicalFile = file2.getCanonicalFile();
try {
if (canonicalFile.getPath().startsWith(file.getPath())) {
return canonicalFile;
}
throw new SecurityException(z[2]);
} catch (IOException e2) {
throw e2;
}
} catch (IOException e3) {
throw new IllegalArgumentException(z[3] + file2);
}
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
public android.net.Uri getUriForFile(java.io.File r8) {
/*
r7 = this;
r4 = android.support.v4.content.ContextCompat.a;
r3 = r8.getCanonicalPath(); Catch:{ IOException -> 0x006d }
r0 = 0;
r1 = r7.mRoots;
r1 = r1.entrySet();
r5 = r1.iterator();
r2 = r0;
L_0x0012:
r0 = r5.hasNext();
if (r0 == 0) goto L_0x004d;
L_0x0018:
r0 = r5.next();
r0 = (java.util.Map.Entry) r0;
r1 = r0.getValue();
r1 = (java.io.File) r1;
r1 = r1.getPath();
r6 = r3.startsWith(r1); Catch:{ IOException -> 0x008a }
if (r6 == 0) goto L_0x00ff;
L_0x002e:
if (r2 == 0) goto L_0x0044;
L_0x0030:
r6 = r1.length(); Catch:{ IOException -> 0x008c }
r1 = r2.getValue(); Catch:{ IOException -> 0x008c }
r1 = (java.io.File) r1; Catch:{ IOException -> 0x008c }
r1 = r1.getPath(); Catch:{ IOException -> 0x008c }
r1 = r1.length(); Catch:{ IOException -> 0x008c }
if (r6 <= r1) goto L_0x00ff;
L_0x0044:
if (r4 == 0) goto L_0x0102;
L_0x0046:
r1 = android.support.v4.app.FragmentActivity.a;
r1 = r1 + 1;
android.support.v4.app.FragmentActivity.a = r1;
r2 = r0;
L_0x004d:
if (r2 != 0) goto L_0x008e;
L_0x004f:
r0 = new java.lang.IllegalArgumentException; Catch:{ IOException -> 0x006b }
r1 = new java.lang.StringBuilder; Catch:{ IOException -> 0x006b }
r1.<init>(); Catch:{ IOException -> 0x006b }
r2 = z; Catch:{ IOException -> 0x006b }
r4 = 6;
r2 = r2[r4]; Catch:{ IOException -> 0x006b }
r1 = r1.append(r2); Catch:{ IOException -> 0x006b }
r1 = r1.append(r3); Catch:{ IOException -> 0x006b }
r1 = r1.toString(); Catch:{ IOException -> 0x006b }
r0.<init>(r1); Catch:{ IOException -> 0x006b }
throw r0; Catch:{ IOException -> 0x006b }
L_0x006b:
r0 = move-exception;
throw r0;
L_0x006d:
r0 = move-exception;
r0 = new java.lang.IllegalArgumentException;
r1 = new java.lang.StringBuilder;
r1.<init>();
r2 = z;
r3 = 7;
r2 = r2[r3];
r1 = r1.append(r2);
r1 = r1.append(r8);
r1 = r1.toString();
r0.<init>(r1);
throw r0;
L_0x008a:
r0 = move-exception;
throw r0; Catch:{ IOException -> 0x008c }
L_0x008c:
r0 = move-exception;
throw r0;
L_0x008e:
r0 = r2.getValue();
r0 = (java.io.File) r0;
r1 = r0.getPath();
r0 = "/";
r0 = r1.endsWith(r0);
if (r0 == 0) goto L_0x00fd;
L_0x00a1:
r0 = r1.length();
r0 = r3.substring(r0);
if (r4 == 0) goto L_0x00fb;
L_0x00ab:
r1 = r1.length();
r1 = r1 + 1;
r0 = r0.substring(r1);
r1 = r0;
L_0x00b6:
r3 = new java.lang.StringBuilder;
r3.<init>();
r0 = r2.getKey();
r0 = (java.lang.String) r0;
r0 = android.net.Uri.encode(r0);
r0 = r3.append(r0);
r2 = 47;
r0 = r0.append(r2);
r2 = "/";
r1 = android.net.Uri.encode(r1, r2);
r0 = r0.append(r1);
r0 = r0.toString();
r1 = new android.net.Uri$Builder;
r1.<init>();
r2 = z;
r3 = 5;
r2 = r2[r3];
r1 = r1.scheme(r2);
r2 = r7.mAuthority;
r1 = r1.authority(r2);
r0 = r1.encodedPath(r0);
r0 = r0.build();
return r0;
L_0x00fb:
r1 = r0;
goto L_0x00b6;
L_0x00fd:
r0 = r3;
goto L_0x00ab;
L_0x00ff:
r0 = r2;
goto L_0x0044;
L_0x0102:
r2 = r0;
goto L_0x0012;
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.v4.content.FileProvider.SimplePathStrategy.getUriForFile(java.io.File):android.net.Uri");
}
public SimplePathStrategy(String str) {
this.mRoots = new HashMap();
this.mAuthority = str;
}
}
public int update(Uri uri, ContentValues contentValues, String str, String[] strArr) {
throw new UnsupportedOperationException(z[18]);
}
public int delete(Uri uri, String str, String[] strArr) {
try {
return this.mStrategy.getFileForUri(uri).delete() ? 1 : 0;
} catch (SecurityException e) {
throw e;
}
}
public boolean onCreate() {
return true;
}
static {
String[] strArr = new String[24];
String str = "z)svBXhnu\u0007L)hiB\u001c)t~US!~4TI8juUHf\\Sky\u0017JHhj\u0001^_uc\u0018[Noohw\u007fS]e~{S]";
int i = -1;
String[] strArr2 = strArr;
String[] strArr3 = strArr;
int i2 = 0;
while (true) {
char[] toCharArray = str.toCharArray();
int length = toCharArray.length;
char[] cArr = toCharArray;
for (int i3 = 0; length > i3; i3++) {
int i4;
char c = cArr[i3];
switch (i3 % 5) {
case v.m /*0*/:
i4 = 60;
break;
case at.g /*1*/:
i4 = 72;
break;
case at.i /*2*/:
i4 = 26;
break;
case at.o /*3*/:
i4 = 26;
break;
default:
i4 = 39;
break;
}
cArr[i3] = (char) (i4 ^ c);
}
str = new String(cArr).intern();
switch (i) {
case v.m /*0*/:
strArr2[i2] = str;
str = "r':\u007f_H-htFPhstTY:ni";
i2 = 2;
strArr2 = strArr3;
i = 1;
break;
case at.g /*1*/:
strArr2[i2] = str;
str = "l:ulNX-h:JI;n:@N)tn\u0007I:s:WY:wsTO!utT";
i2 = 3;
strArr2 = strArr3;
i = 2;
break;
case at.i /*2*/:
strArr2[i2] = str;
str = "l:ulNX-h:JI;n:IS<:xB\u001c-bjHN<\u007f~";
i2 = 4;
strArr2 = strArr3;
i = 3;
break;
case at.o /*3*/:
strArr2[i2] = str;
i2 = 5;
strArr2 = strArr3;
str = "]&~hHU,4iRL8uhS\u0012\u000eSVbc\u0018HUqu\f_Hxl\tNRt";
i = 4;
break;
case at.p /*4*/:
strArr2[i2] = str;
i2 = 6;
str = "L)nr";
i = 5;
strArr2 = strArr3;
break;
case at.m /*5*/:
strArr2[i2] = str;
i2 = 7;
str = "q!iiNR/:{IX:usC\u0012;ojWS:n4au\u0004_Ewn\u0007LScy\u001aEJfh\u0000I:JY<{7C]<{";
i = 6;
strArr2 = strArr3;
break;
case Y.f /*6*/:
strArr2[i2] = str;
i2 = 8;
str = "R)w\u007f";
i = 7;
strArr2 = strArr3;
break;
case aF.v /*7*/:
strArr2[i2] = str;
i2 = 9;
str = "N'un\nL)nr";
i = 8;
strArr2 = strArr3;
break;
case aF.u /*8*/:
strArr2[i2] = str;
i2 = 10;
str = "_)yrB\u00118{nO";
i = 9;
strArr2 = strArr3;
break;
case Y.l /*9*/:
strArr2[i2] = str;
i2 = 11;
str = "Z!v\u007fT\u00118{nO";
i = 10;
strArr2 = strArr3;
break;
case Y.t /*10*/:
strArr2[i2] = str;
i2 = 12;
str = "Y0n\u007fUR)v7W]<r";
i = 11;
strArr2 = strArr3;
break;
case Y.j /*11*/:
strArr2[i2] = str;
i2 = 13;
str = "]8jvN_)nsHRguySY<7iSN-{w";
i = 12;
strArr2 = strArr3;
break;
case Y.p /*12*/:
strArr2[i2] = str;
i2 = 14;
str = "c;s`B";
i = 13;
strArr2 = strArr3;
break;
case Y.q /*13*/:
strArr2[i2] = str;
i2 = 15;
str = "c,siWP)cEI]%\u007f";
i = 14;
strArr2 = strArr3;
break;
case arj.Toolbar_titleMarginEnd /*14*/:
strArr2[i2] = str;
i2 = 16;
str = "c;s`B";
i = 15;
strArr2 = strArr3;
break;
case arj.Toolbar_titleMarginTop /*15*/:
strArr2[i2] = str;
i2 = 17;
str = "c,siWP)cEI]%\u007f";
i = 16;
strArr2 = strArr3;
break;
case VideoMessage.JPEG_THUMBNAIL_FIELD_NUMBER /*16*/:
strArr2[i2] = str;
i2 = 18;
str = "r':\u007f_H-htFPhojC]<\u007fi";
i = 17;
strArr2 = strArr3;
break;
case arj.Toolbar_maxButtonHeight /*17*/:
strArr2[i2] = str;
i2 = 19;
str = "K)";
i = 18;
strArr2 = strArr3;
break;
case arj.Toolbar_collapseIcon /*18*/:
strArr2[i2] = str;
i2 = 20;
str = "N?n";
i = 19;
strArr2 = strArr3;
break;
case arj.Toolbar_collapseContentDescription /*19*/:
strArr2[i2] = str;
i2 = 21;
str = "u&l{KU,:wHX- :";
i = 20;
strArr2 = strArr3;
break;
case arj.Toolbar_navigationIcon /*20*/:
strArr2[i2] = str;
i2 = 22;
str = "K<";
i = 21;
strArr2 = strArr3;
break;
case arj.Toolbar_navigationContentDescription /*21*/:
strArr2[i2] = str;
i2 = 23;
str = "N?";
i = 22;
strArr2 = strArr3;
break;
case arj.Toolbar_logoDescription /*22*/:
strArr2[i2] = str;
z = strArr3;
strArr = new String[2];
str = "c,siWP)cEI]%\u007f";
i = 23;
strArr2 = strArr;
strArr3 = strArr;
i2 = 0;
break;
case arj.Toolbar_titleTextColor /*23*/:
strArr2[i2] = str;
str = "c;s`B";
i = 24;
i2 = 1;
strArr2 = strArr3;
break;
case arj.Toolbar_subtitleTextColor /*24*/:
strArr2[i2] = str;
COLUMNS = strArr3;
DEVICE_ROOT = new File("/");
sCache = new HashMap();
return;
default:
strArr2[i2] = str;
str = "z)svBXhnu\u0007L)hiB\u001c)t~US!~4TI8juUHf\\Sky\u0017JHhj\u0001^_uc\u0018[Noohw\u007fS]e~{S]";
i2 = 1;
strArr2 = strArr3;
i = 0;
break;
}
}
}
private static Object[] copyOf(Object[] objArr, int i) {
Object obj = new Object[i];
System.arraycopy(objArr, 0, obj, 0, i);
return obj;
}
public static Uri getUriForFile(Context context, String str, File file) {
return getPathStrategy(context, str).getUriForFile(file);
}
public void attachInfo(Context context, ProviderInfo providerInfo) {
try {
super.attachInfo(context, providerInfo);
if (providerInfo.exported) {
throw new SecurityException(z[4]);
}
try {
if (providerInfo.grantUriPermissions) {
this.mStrategy = getPathStrategy(context, providerInfo.authority);
return;
}
throw new SecurityException(z[3]);
} catch (SecurityException e) {
throw e;
}
} catch (SecurityException e2) {
throw e2;
}
}
private static String[] copyOf(String[] strArr, int i) {
Object obj = new String[i];
System.arraycopy(strArr, 0, obj, 0, i);
return obj;
}
private static PathStrategy parsePathStrategy(Context context, String str) {
boolean z = ContextCompat.a;
PathStrategy simplePathStrategy = new SimplePathStrategy(str);
XmlResourceParser loadXmlMetaData = context.getPackageManager().resolveContentProvider(str, 128).loadXmlMetaData(context.getPackageManager(), z[5]);
if (loadXmlMetaData == null) {
try {
throw new IllegalArgumentException(z[7]);
} catch (SecurityException e) {
throw e;
}
}
while (true) {
int next = loadXmlMetaData.next();
if (next == 1) {
break;
} else if (next == 2) {
File buildPath;
String name = loadXmlMetaData.getName();
String attributeValue = loadXmlMetaData.getAttributeValue(null, z[8]);
String attributeValue2 = loadXmlMetaData.getAttributeValue(null, z[6]);
if (z[9].equals(name)) {
buildPath = buildPath(DEVICE_ROOT, new String[]{attributeValue2});
} else if (z[11].equals(name)) {
buildPath = buildPath(context.getFilesDir(), new String[]{attributeValue2});
} else if (z[10].equals(name)) {
buildPath = buildPath(context.getCacheDir(), new String[]{attributeValue2});
} else if (z[12].equals(name)) {
buildPath = buildPath(Environment.getExternalStorageDirectory(), new String[]{attributeValue2});
} else {
buildPath = null;
}
if (buildPath != null) {
try {
simplePathStrategy.addRoot(attributeValue, buildPath);
} catch (SecurityException e2) {
throw e2;
}
}
if (z) {
break;
}
}
}
return simplePathStrategy;
}
private static PathStrategy getPathStrategy(Context context, String str) {
PathStrategy pathStrategy;
synchronized (sCache) {
pathStrategy = (PathStrategy) sCache.get(str);
if (pathStrategy == null) {
try {
pathStrategy = parsePathStrategy(context, str);
sCache.put(str, pathStrategy);
} catch (Throwable e) {
throw new IllegalArgumentException(z[1], e);
} catch (Throwable e2) {
throw new IllegalArgumentException(z[0], e2);
}
}
}
return pathStrategy;
}
public String getType(Uri uri) {
File fileForUri = this.mStrategy.getFileForUri(uri);
int lastIndexOf = fileForUri.getName().lastIndexOf(46);
if (lastIndexOf >= 0) {
String mimeTypeFromExtension = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileForUri.getName().substring(lastIndexOf + 1));
if (mimeTypeFromExtension != null) {
return mimeTypeFromExtension;
}
}
return z[13];
}
public ParcelFileDescriptor openFile(Uri uri, String str) {
return ParcelFileDescriptor.open(this.mStrategy.getFileForUri(uri), modeToMode(str));
}
private static File buildPath(File file, String[] strArr) {
boolean z = ContextCompat.a;
int length = strArr.length;
int i = 0;
File file2 = file;
while (i < length) {
String str = strArr[i];
if (str != null) {
file2 = new File(file2, str);
}
int i2 = i + 1;
if (z) {
break;
}
i = i2;
}
return file2;
}
public Uri insert(Uri uri, ContentValues contentValues) {
throw new UnsupportedOperationException(z[2]);
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
private static int modeToMode(java.lang.String r4) {
/*
r1 = android.support.v4.content.ContextCompat.a;
r0 = "r";
r0 = r0.equals(r4);
if (r0 == 0) goto L_0x000f;
L_0x000b:
r0 = 268435456; // 0x10000000 float:2.5243549E-29 double:1.32624737E-315;
if (r1 == 0) goto L_0x007f;
L_0x000f:
r0 = "w";
r0 = r0.equals(r4); Catch:{ SecurityException -> 0x0077 }
if (r0 != 0) goto L_0x0024;
L_0x0018:
r0 = z; Catch:{ SecurityException -> 0x0077 }
r2 = 22;
r0 = r0[r2]; Catch:{ SecurityException -> 0x0077 }
r0 = r0.equals(r4); Catch:{ SecurityException -> 0x0077 }
if (r0 == 0) goto L_0x0028;
L_0x0024:
r0 = 738197504; // 0x2c000000 float:1.8189894E-12 double:3.647180266E-315;
if (r1 == 0) goto L_0x007f;
L_0x0028:
r0 = z; Catch:{ SecurityException -> 0x0079 }
r2 = 19;
r0 = r0[r2]; Catch:{ SecurityException -> 0x0079 }
r0 = r0.equals(r4); Catch:{ SecurityException -> 0x0079 }
if (r0 == 0) goto L_0x0038;
L_0x0034:
r0 = 704643072; // 0x2a000000 float:1.1368684E-13 double:3.481399345E-315;
if (r1 == 0) goto L_0x007f;
L_0x0038:
r0 = z; Catch:{ SecurityException -> 0x007b }
r2 = 23;
r0 = r0[r2]; Catch:{ SecurityException -> 0x007b }
r0 = r0.equals(r4); Catch:{ SecurityException -> 0x007b }
if (r0 == 0) goto L_0x0048;
L_0x0044:
r0 = 939524096; // 0x38000000 float:3.0517578E-5 double:4.641865793E-315;
if (r1 == 0) goto L_0x007f;
L_0x0048:
r0 = z; Catch:{ SecurityException -> 0x007d }
r2 = 20;
r0 = r0[r2]; Catch:{ SecurityException -> 0x007d }
r0 = r0.equals(r4); Catch:{ SecurityException -> 0x007d }
if (r0 == 0) goto L_0x0058;
L_0x0054:
r0 = 1006632960; // 0x3c000000 float:0.0078125 double:4.973427635E-315;
if (r1 == 0) goto L_0x007f;
L_0x0058:
r0 = new java.lang.IllegalArgumentException; Catch:{ SecurityException -> 0x0075 }
r1 = new java.lang.StringBuilder; Catch:{ SecurityException -> 0x0075 }
r1.<init>(); Catch:{ SecurityException -> 0x0075 }
r2 = z; Catch:{ SecurityException -> 0x0075 }
r3 = 21;
r2 = r2[r3]; Catch:{ SecurityException -> 0x0075 }
r1 = r1.append(r2); Catch:{ SecurityException -> 0x0075 }
r1 = r1.append(r4); Catch:{ SecurityException -> 0x0075 }
r1 = r1.toString(); Catch:{ SecurityException -> 0x0075 }
r0.<init>(r1); Catch:{ SecurityException -> 0x0075 }
throw r0; Catch:{ SecurityException -> 0x0075 }
L_0x0075:
r0 = move-exception;
throw r0;
L_0x0077:
r0 = move-exception;
throw r0;
L_0x0079:
r0 = move-exception;
throw r0;
L_0x007b:
r0 = move-exception;
throw r0;
L_0x007d:
r0 = move-exception;
throw r0;
L_0x007f:
return r0;
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.v4.content.FileProvider.modeToMode(java.lang.String):int");
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
public android.database.Cursor query(android.net.Uri r11, java.lang.String[] r12, java.lang.String r13, java.lang.String[] r14, java.lang.String r15) {
/*
r10 = this;
r3 = android.support.v4.content.ContextCompat.a;
r0 = r10.mStrategy;
r4 = r0.getFileForUri(r11);
if (r12 != 0) goto L_0x000c;
L_0x000a:
r12 = COLUMNS;
L_0x000c:
r0 = r12.length;
r5 = new java.lang.String[r0];
r0 = r12.length;
r6 = new java.lang.Object[r0];
r1 = 0;
r7 = r12.length;
r0 = 0;
r2 = r0;
r0 = r1;
L_0x0017:
if (r2 >= r7) goto L_0x005d;
L_0x0019:
r8 = r12[r2];
r1 = z; Catch:{ SecurityException -> 0x0078 }
r9 = 17;
r1 = r1[r9]; Catch:{ SecurityException -> 0x0078 }
r1 = r1.equals(r8); Catch:{ SecurityException -> 0x0078 }
if (r1 == 0) goto L_0x0088;
L_0x0027:
r1 = z; Catch:{ SecurityException -> 0x007a }
r9 = 15;
r1 = r1[r9]; Catch:{ SecurityException -> 0x007a }
r5[r0] = r1; Catch:{ SecurityException -> 0x007a }
r1 = r0 + 1;
r9 = r4.getName(); Catch:{ SecurityException -> 0x007a }
r6[r0] = r9; Catch:{ SecurityException -> 0x007a }
if (r3 == 0) goto L_0x0086;
L_0x0039:
r0 = z; Catch:{ SecurityException -> 0x007c }
r9 = 16;
r0 = r0[r9]; Catch:{ SecurityException -> 0x007c }
r0 = r0.equals(r8); Catch:{ SecurityException -> 0x007c }
if (r0 == 0) goto L_0x0086;
L_0x0045:
r0 = z; Catch:{ SecurityException -> 0x007c }
r8 = 14;
r0 = r0[r8]; Catch:{ SecurityException -> 0x007c }
r5[r1] = r0; Catch:{ SecurityException -> 0x007c }
r0 = r1 + 1;
r8 = r4.length(); Catch:{ SecurityException -> 0x007c }
r8 = java.lang.Long.valueOf(r8); Catch:{ SecurityException -> 0x007c }
r6[r1] = r8; Catch:{ SecurityException -> 0x007c }
L_0x0059:
r1 = r2 + 1;
if (r3 == 0) goto L_0x0084;
L_0x005d:
r1 = copyOf(r5, r0);
r0 = copyOf(r6, r0);
r2 = new android.database.MatrixCursor;
r4 = 1;
r2.<init>(r1, r4);
r2.addRow(r0); Catch:{ SecurityException -> 0x007e }
r0 = android.support.v4.app.FragmentActivity.a; Catch:{ SecurityException -> 0x007e }
if (r0 == 0) goto L_0x0077;
L_0x0072:
if (r3 == 0) goto L_0x0082;
L_0x0074:
r0 = 0;
L_0x0075:
android.support.v4.content.ContextCompat.a = r0;
L_0x0077:
return r2;
L_0x0078:
r0 = move-exception;
throw r0; Catch:{ SecurityException -> 0x007a }
L_0x007a:
r0 = move-exception;
throw r0; Catch:{ SecurityException -> 0x007c }
L_0x007c:
r0 = move-exception;
throw r0;
L_0x007e:
r0 = move-exception;
throw r0; Catch:{ SecurityException -> 0x0080 }
L_0x0080:
r0 = move-exception;
throw r0;
L_0x0082:
r0 = 1;
goto L_0x0075;
L_0x0084:
r2 = r1;
goto L_0x0017;
L_0x0086:
r0 = r1;
goto L_0x0059;
L_0x0088:
r1 = r0;
goto L_0x0039;
*/
throw new UnsupportedOperationException("Method not decompiled: android.support.v4.content.FileProvider.query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String):android.database.Cursor");
}
}
| true
|
ae732a06af6d49d5d2854e5a67fbc9108396643f
|
Java
|
pkdevbox/osee
|
/plugins/org.eclipse.osee.http.jetty.test/src/org/eclipse/osee/http/jetty/util/CookieStoringHttpClientFilter.java
|
UTF-8
| 2,021
| 1.984375
| 2
|
[] |
no_license
|
/*******************************************************************************
* Copyright (c) 2015 Boeing.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Boeing - initial API and implementation
*******************************************************************************/
package org.eclipse.osee.http.jetty.util;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.client.ClientResponseContext;
import javax.ws.rs.client.ClientResponseFilter;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.ext.Provider;
/**
* @author Roberto E. Escobar
*/
@Provider
public class CookieStoringHttpClientFilter implements ClientResponseFilter, ClientRequestFilter {
private final Map<String, Cookie> cookies = new HashMap<String, Cookie>(3);
@Override
public void filter(ClientRequestContext context) {
setCookies(HttpHeaders.COOKIE, cookies, context.getHeaders());
}
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) {
Map<String, NewCookie> newCookies = responseContext.getCookies();
if (newCookies != null && !newCookies.isEmpty()) {
cookies.putAll(newCookies);
}
setCookies(HttpHeaders.SET_COOKIE, cookies, responseContext.getHeaders());
}
@SuppressWarnings({"unchecked", "rawtypes"})
private void setCookies(String header, Map<String, Cookie> cookies, MultivaluedMap headers) {
if (cookies != null && !cookies.isEmpty()) {
for (Cookie cookie : cookies.values()) {
headers.add(header, cookie.toString());
}
}
}
}
| true
|
0f828ccdc2054bd31fc0b9c1f9bb0acf74e6d04f
|
Java
|
bogdanorzea/PopularMovies
|
/app/src/main/java/com/bogdanorzea/popularmovies/ui/details/CastAdapter.java
|
UTF-8
| 2,308
| 2.46875
| 2
|
[
"MIT",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
package com.bogdanorzea.popularmovies.ui.details;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bogdanorzea.popularmovies.R;
import com.bogdanorzea.popularmovies.model.object.Cast;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class CastAdapter extends RecyclerView.Adapter<CastAdapter.ViewHolder> {
private Context context;
private List<Cast> mCast;
public CastAdapter(@NonNull Context context) {
this.context = context;
this.mCast = new ArrayList<>();
}
public List<Cast> getCast() {
return mCast;
}
public void addCast(@NonNull List<Cast> data) {
int size = getItemCount();
mCast.addAll(data);
if (size > 0) {
notifyItemRangeInserted(size, data.size());
} else {
notifyDataSetChanged();
}
}
@NonNull
@Override
public CastAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View layout = LayoutInflater.from(context).inflate(R.layout.item_cast, parent, false);
return new CastAdapter.ViewHolder(layout);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
Cast castMember = mCast.get(position);
holder.name.setText(castMember.name);
holder.description.setText(castMember.character);
Picasso.with(context)
.load(castMember.getProfileUrl())
.error(R.drawable.missing_cover)
.into(holder.profile);
}
@Override
public int getItemCount() {
return mCast.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
final TextView name;
final TextView description;
final ImageView profile;
public ViewHolder(View view) {
super(view);
name = view.findViewById(R.id.name);
description = view.findViewById(R.id.character);
profile = view.findViewById(R.id.profile);
}
}
}
| true
|