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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c21003aaf53120d9c3edf94c13e6f2ae21b8d4ff | Java | CodeOfMine/JavaEEProject | /src/com/servlet/DisplayServlet.java | UTF-8 | 1,526 | 2.375 | 2 | [] | no_license | package com.servlet;
import com.domain.Message;
import com.domain.User;
import com.service.Impl.MessageServiceImpl;
import com.service.Impl.UserServieImpl;
import com.service.MessageService;
import com.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Random;
@WebServlet(name = "DisplayServlet",urlPatterns = "/displayServlet")
public class DisplayServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//创建MessageService对象并调用方法
MessageService messageService = new MessageServiceImpl();
List<Message> messages = messageService.getAllMessage();
//创建session域对象
HttpSession session = request.getSession();
session.setAttribute("allMessage",messages);
//重定向到主界面
response.sendRedirect(request.getContextPath()+"/main.jsp");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
| true |
4e8c093940739c94bb45d23e12349a10034bb50c | Java | peizihui/bx-scheduler | /bx-scheduler-store/src/main/java/org/bx/scheduler/store/IJobInfoStore.java | UTF-8 | 175 | 1.671875 | 2 | [] | no_license | package org.bx.scheduler.store;
import org.bx.scheduler.store.entity.SchedulerJobInfo;
public interface IJobInfoStore {
SchedulerJobInfo getJobInfo(String triggerId);
}
| true |
33ede31a22bb373f9d63fff6bcee4c90089fd21a | Java | VellaMessiah/MentoringSessionsPhase3 | /session1/src/main/java/com/mentoringsessions/session1/Entities/Customer.java | UTF-8 | 504 | 2.234375 | 2 | [] | no_license | package com.mentoringsessions.session1.Entities;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Generated;
import org.hibernate.annotations.Table;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Customer {
@Id
private String id;
@Column
private String name;
@Column
private int salary;
}
| true |
392acf3ca6649921e50502c1159da73991aeb05b | Java | synju/enginex2 | /src/spaceshooter/MenuState.java | UTF-8 | 2,374 | 2.5 | 2 | [] | no_license | package spaceshooter;
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import enginex.Button;
import enginex.State;
import net.java.games.input.Controller;
import net.java.games.input.ControllerEnvironment;
public class MenuState extends State {
Spaceshooter game;
boolean initialized = false;
public Controller joystick;
ArrayList<Button> buttons = new ArrayList<>();
Button btnPlay;
Button btnQuit;
ScrollingBG spaceBG = new ScrollingBG("res/spaceshooter/spacebg.png", 0.0f, 0, 0, 800, 600);
public MenuState(Spaceshooter game) {
super(game);
this.game = game;
}
public void initialize() {
if(initialized)
return;
create();
initialized = true;
}
void initControllers() {
for(Controller c:ControllerEnvironment.getDefaultEnvironment().getControllers())
if(c.getType() == Controller.Type.STICK)
joystick = c;
}
public void create() {
initControllers();
createButtons();
}
public void createButtons() {
btnPlay = new Button(game, "Play Game", game.width / 2 - 100, 200, 200, 75, "res/spaceshooter/btnPlay.png", "res/spaceshooter/btnPlay.png", "res/replicants/sfx/buttonHover.ogg");
buttons.add(btnPlay);
btnQuit = new Button(game, "Quit Game", game.width / 2 - 100, 300, 200, 75, "res/spaceshooter/btnQuit.png", "res/spaceshooter/btnQuit.png", "res/replicants/sfx/buttonHover.ogg");
buttons.add(btnQuit);
}
public void update() {
initialize();
joyStickPoll();
for(Button b:buttons)
b.update();
}
public void render(Graphics2D g) {
// Smooth Images
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
spaceBG.render(g);
// Buttons
for(Button b:buttons)
b.render(g);
}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void mousePressed(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1) {
// Play Button Clicked...
if(btnPlay.hover) {
game.stateMachine.setState(game.PLAY);
}
// Quit Button Clicked...
if(btnQuit.hover)
game.exit();
}
}
public void joyStickPoll() {
// Update Joystick Input Data
if(joystick != null) {
// Poll Joystick for updates
joystick.poll();
// Get Components
// Component[] components = joystick.getComponents();
}
}
}
| true |
7678f171070a751aba10853f6be4bad334881e4f | Java | George-Kovalenko/ContactList | /contact-list-web/src/main/java/edu/itechart/contactlist/handler/fieldhandlers/MaritalStatusFieldHandler.java | UTF-8 | 699 | 2.65625 | 3 | [] | no_license | package edu.itechart.contactlist.handler.fieldhandlers;
import edu.itechart.contactlist.entity.Contact;
import edu.itechart.contactlist.handler.FieldHandlerException;
public class MaritalStatusFieldHandler implements FieldHandler {
@Override
public void handleInputField(Contact contact, String field) throws FieldHandlerException {
try {
Integer id = Integer.parseInt(field);
if (id != 0) {
contact.setMaritalStatus(id);
} else {
contact.setMaritalStatus(null);
}
} catch (NumberFormatException e) {
throw new FieldHandlerException("Invalid marital status", e);
}
}
}
| true |
2f1b5522577ac571e8087e44e2809e9c06687f55 | Java | marcelam70/Java_2020 | /src/RecapClass/OverloadingConcept2.java | UTF-8 | 309 | 2.625 | 3 | [] | no_license | package RecapClass;
public class OverloadingConcept2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
main(3);
main("Marcela");
}
public static void main(int i){
System.out.println(i);
}
public static void main(String name){
System.out.println(name);
}
}
| true |
883e20ee796642e34ecbaaa9dc6705bee5ed6161 | Java | zedyjy/CS102_Lab05 | /ConsoleHangmanView.java | UTF-8 | 695 | 3.4375 | 3 | [] | no_license | package CS102.Lab05;
public class ConsoleHangmanView implements IHangmanView{
@Override
public void updateView(Hangman hangman) {
if (!hangman.isGameOver()) {
System.out.println("Known so far: " + hangman.getKnownSoFar());
System.out.println("You have " + (hangman.getMaxAllowedIncorrectTries() - hangman.getNumOfIncorrectTries()) + " tries left.");
}
else if (hangman.isGameOver() && !hangman.hasLost()) {
System.out.println("You won!");
}
else if (hangman.hasLost() && hangman.isGameOver()) {
System.out.println("You lost! Secret word was : " + hangman.secretWord.toString());
}
}
}
| true |
3b5bdc6e5229e980d383214ed68699e47d785436 | Java | avary/MyQuran | /app/search/Indexed.java | UTF-8 | 330 | 2.046875 | 2 | [] | no_license | package search;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Mark the class to be indexed
* @author jfp
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Indexed {
}
| true |
9760573cb5ed2c9d625d8cfd7aef30bd6d255d55 | Java | dgkim11/spring-app-enterprise-sample | /hotel-domain-infra/src/main/java/example/spring/hotel/infrastructure/domain/mybatis/MyBatisRepositories.java | UTF-8 | 210 | 1.59375 | 2 | [] | no_license | package example.spring.hotel.infrastructure.domain.mybatis;
/**
* MyBatis 리파지토리 bean들이 있는 root 위치를 가리키는 용도로만 사용한다.
*/
public interface MyBatisRepositories {
}
| true |
dfb29ec4515545542ad8008d968acb005457cdcc | Java | mr-rohangupta/java-design-patterns | /src/main/java/com/java/designpatterns/creationalpatterns/abstractfactorypattern/factories/BakeryFactory.java | UTF-8 | 1,377 | 2.921875 | 3 | [] | no_license | package com.java.designpatterns.creationalpatterns.abstractfactorypattern.factories;
import com.java.designpatterns.creationalpatterns.abstractfactorypattern.interfacesandabstracts.Bakery;
import com.java.designpatterns.creationalpatterns.abstractfactorypattern.interfacesandabstracts.Pizza;
import com.java.designpatterns.creationalpatterns.abstractfactorypattern.interfacesandabstracts.impl.AmazingBlazingBakers;
import com.java.designpatterns.creationalpatterns.abstractfactorypattern.interfacesandabstracts.impl.FantasticBakers;
import com.java.designpatterns.creationalpatterns.abstractfactorypattern.interfacesandabstracts.impl.SuperBakers;
/**
* Created by IntelliJ IDEA.
* User: Rohan Gupta
* Date: 15-05-2021
* Time: 13:21
*/
public class BakeryFactory extends BakersPizzaAbstractFactory {
@Override
public Bakery getBakery(String bakeryName) {
if(bakeryName == null)
return null;
if(bakeryName.equalsIgnoreCase("AmazingBlazingBakers")){
return new AmazingBlazingBakers();
}
else if(bakeryName.equalsIgnoreCase("FantasticBakers")){
return new FantasticBakers();
}
else if(bakeryName.equalsIgnoreCase("SuperBakers")){
return new SuperBakers();
}
return null;
}
@Override
public Pizza getPizza(String name) {
return null;
}
}
| true |
64d536acdff07d9d963348944d8ce972e85f24ac | Java | otheruniversum/agar-1 | /core/src/com/game/agar/rendering/Camera.java | UTF-8 | 1,338 | 3.125 | 3 | [] | no_license | package com.game.agar.rendering;
import com.badlogic.gdx.math.Matrix4;
import com.game.agar.shared.Position;
public class Camera {
private Position position;
private float zoom = 0.1f;
private int width, height;
public Camera(int width, int height){
this.width = width;
this.height = height;
position = new Position(width / 2.f, width / 2.f);
}
public void changeZoom(double change){
zoom += change;
}
public void setPosition(Position position){
this.position = position;
}
public float getZoom(){
return zoom;
}
public Matrix4 getMatrix(){
Matrix4 matrix = new Matrix4();
Matrix4 translation = new Matrix4();
matrix.setToScaling(zoom, zoom, 0);
float x = width / 2.f;
float y = height / 2.f;
// scaling around (width / 2, height / 2) point
float centeringX = x - zoom * x;
float centeringY = y - zoom * y;
// translation accordingly to camera position and zoom
float translationX = -((float)position.x - x) * zoom;
float translationY = -((float)position.y - y) * zoom;
translation.setToTranslation(centeringX + translationX, centeringY + translationY, 0);
matrix = translation.mul(matrix);
return matrix;
}
}
| true |
5e25da6cbae6269c870a9d1fa2ec68f493d24ee9 | Java | apache/derby | /java/org.apache.derby.engine/org/apache/derby/impl/sql/compile/DMLStatementNode.java | UTF-8 | 14,267 | 1.921875 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unicode",
"LGPL-2.0-or-later",
"CPL-1.0",
"CDDL-1.0",
"MIT",
"LicenseRef-scancode-other-copyleft",
"NAIST-2003",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"CC-BY-SA-3.0",
"LicenseRef-scancode-generic-export-compliance"
] | permissive | /*
Derby - Class org.apache.derby.impl.sql.compile.DMLStatementNode
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to you under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.derby.impl.sql.compile;
import java.util.List;
import org.apache.derby.shared.common.error.StandardException;
import org.apache.derby.iapi.services.context.ContextManager;
import org.apache.derby.shared.common.sanity.SanityManager;
import org.apache.derby.iapi.sql.ResultColumnDescriptor;
import org.apache.derby.iapi.sql.ResultDescription;
import org.apache.derby.iapi.sql.compile.Visitor;
import org.apache.derby.iapi.sql.conn.Authorizer;
import org.apache.derby.iapi.sql.dictionary.DataDictionary;
import org.apache.derby.iapi.util.JBitSet;
/**
* A DMLStatementNode represents any type of DML statement: a cursor declaration,
* an INSERT statement, and UPDATE statement, or a DELETE statement. All DML
* statements have result sets, but they do different things with them. A
* SELECT statement sends its result set to the client, an INSERT statement
* inserts its result set into a table, a DELETE statement deletes from a
* table the rows corresponding to the rows in its result set, and an UPDATE
* statement updates the rows in a base table corresponding to the rows in its
* result set.
*
*/
abstract class DMLStatementNode extends StatementNode
{
/**
* The result set is the rows that result from running the
* statement. What this means for SELECT statements is fairly obvious.
* For a DELETE, there is one result column representing the
* key of the row to be deleted (most likely, the location of the
* row in the underlying heap). For an UPDATE, the row consists of
* the key of the row to be updated plus the updated columns. For
* an INSERT, the row consists of the new column values to be
* inserted, with no key (the system generates a key).
*
* The parser doesn't know anything about keys, so the columns
* representing the keys will be added after parsing (perhaps in
* the binding phase?).
*
*/
ResultSetNode resultSet;
DMLStatementNode(ResultSetNode resultSet, ContextManager cm) {
super(cm);
this.resultSet = resultSet;
}
/**
* Prints the sub-nodes of this object. See QueryTreeNode.java for
* how tree printing is supposed to work.
*
* @param depth The depth of this node in the tree
*/
@Override
void printSubNodes(int depth)
{
if (SanityManager.DEBUG)
{
super.printSubNodes(depth);
if (resultSet != null)
{
printLabel(depth, "resultSet: ");
resultSet.treePrint(depth + 1);
}
}
}
/**
* Get the ResultSetNode from this DML Statement.
* (Useful for view resolution after parsing the view definition.)
*
* @return ResultSetNode The ResultSetNode from this DMLStatementNode.
*/
ResultSetNode getResultSetNode()
{
return resultSet;
}
/**
* Bind this DMLStatementNode. This means looking up tables and columns and
* getting their types, and figuring out the result types of all
* expressions, as well as doing view resolution, permissions checking,
* etc.
*
* @param dataDictionary The DataDictionary to use to look up
* columns, tables, etc.
*
* @return The bound query tree
*
* @exception StandardException Thrown on error
*/
QueryTreeNode bind(DataDictionary dataDictionary)
throws StandardException
{
// We just need select privilege on most columns and tables
getCompilerContext().pushCurrentPrivType(getPrivType());
try {
/*
** Bind the tables before binding the expressions, so we can
** use the results of table binding to look up columns.
*/
bindTables(dataDictionary);
/* Bind the expressions */
bindExpressions();
}
finally
{
getCompilerContext().popCurrentPrivType();
}
return this;
}
/**
* Bind only the underlying ResultSets with tables. This is necessary for
* INSERT, where the binding order depends on the underlying ResultSets.
* This means looking up tables and columns and
* getting their types, and figuring out the result types of all
* expressions, as well as doing view resolution, permissions checking,
* etc.
*
* @param dataDictionary The DataDictionary to use to look up
* columns, tables, etc.
*
* @return The bound query tree
*
* @exception StandardException Thrown on error
*/
QueryTreeNode bindResultSetsWithTables(DataDictionary dataDictionary)
throws StandardException
{
/* Okay to bindly bind the tables, since ResultSets without tables
* know to handle the call.
*/
bindTables(dataDictionary);
/* Bind the expressions in the underlying ResultSets with tables */
bindExpressionsWithTables();
return this;
}
/**
* Bind the tables in this DML statement.
*
* @param dataDictionary The data dictionary to use to look up the tables
*
* @exception StandardException Thrown on error
*/
protected void bindTables(DataDictionary dataDictionary)
throws StandardException
{
/* Bind the tables in the resultSet
* (DMLStatementNode is above all ResultSetNodes, so table numbering
* will begin at 0.)
* In case of referential action on delete , the table numbers can be
* > 0 because the nodes are create for dependent tables also in the
* the same context.
*/
boolean doJOO = getOptimizerFactory().doJoinOrderOptimization();
ContextManager cm = getContextManager();
resultSet = resultSet.bindNonVTITables(dataDictionary,
new FromList(doJOO, cm));
resultSet = resultSet.bindVTITables(new FromList(doJOO, cm));
}
/**
* Bind the expressions in this DML statement.
*
* @exception StandardException Thrown on error
*/
protected void bindExpressions()
throws StandardException
{
FromList fromList =
new FromList(getOptimizerFactory().doJoinOrderOptimization(),
getContextManager());
/* Bind the expressions under the resultSet */
resultSet.bindExpressions(fromList);
/* Verify that all underlying ResultSets reclaimed their FromList */
if (SanityManager.DEBUG)
SanityManager.ASSERT(fromList.size() == 0,
"fromList.size() is expected to be 0, not " + fromList.size() +
" on return from RS.bindExpressions()");
}
/**
* Bind the expressions in the underlying ResultSets with tables.
*
* @exception StandardException Thrown on error
*/
protected void bindExpressionsWithTables()
throws StandardException
{
FromList fromList =
new FromList(getOptimizerFactory().doJoinOrderOptimization(),
getContextManager());
/* Bind the expressions under the resultSet */
resultSet.bindExpressionsWithTables(fromList);
/* Verify that all underlying ResultSets reclaimed their FromList */
if (SanityManager.DEBUG)
SanityManager.ASSERT(fromList.size() == 0,
"fromList.size() is expected to be 0, not " + fromList.size() +
" on return from RS.bindExpressions()");
}
/**
* Returns the type of activation this class
* generates.
*
* @return either (NEED_ROW_ACTIVATION | NEED_PARAM_ACTIVATION) or
* (NEED_ROW_ACTIVATION) depending on params
*
*/
int activationKind()
{
List<ParameterNode> parameterList =
getCompilerContext().getParameterList();
/*
** We need rows for all types of DML activations. We need parameters
** only for those that have parameters.
*/
if (parameterList != null && !parameterList.isEmpty())
{
return StatementNode.NEED_PARAM_ACTIVATION;
}
else
{
return StatementNode.NEED_ROW_ACTIVATION;
}
}
/**
* Optimize a DML statement (which is the only type of statement that
* should need optimizing, I think). This method over-rides the one
* in QueryTreeNode.
*
* This method takes a bound tree, and returns an optimized tree.
* It annotates the bound tree rather than creating an entirely
* new tree.
*
* Throws an exception if the tree is not bound, or if the binding
* is out of date.
*
*
* @exception StandardException Thrown on error
*/
@Override
public void optimizeStatement() throws StandardException
{
resultSet = resultSet.preprocess(getCompilerContext().getNumTables(),
null,
(FromList) null);
// Evaluate expressions with constant operands here to simplify the
// query tree and to reduce the runtime cost. Do it before optimize()
// since the simpler tree may have more accurate information for
// the optimizer. (Example: The selectivity for 1=1 is estimated to
// 0.1, whereas the actual selectivity is 1.0. In this step, 1=1 will
// be rewritten to TRUE, which is known by the optimizer to have
// selectivity 1.0.)
accept(new ConstantExpressionVisitor());
resultSet = resultSet.optimize(getDataDictionary(), null, 1.0d);
resultSet = resultSet.modifyAccessPaths();
/* If this is a cursor, then we
* need to generate a new ResultSetNode to enable the scrolling
* on top of the tree before modifying the access paths.
*/
if (this instanceof CursorNode)
{
ResultColumnList siRCList;
ResultColumnList childRCList;
ResultSetNode siChild = resultSet;
/* We get a shallow copy of the ResultColumnList and its
* ResultColumns. (Copy maintains ResultColumn.expression for now.)
*/
siRCList = resultSet.getResultColumns();
childRCList = siRCList.copyListAndObjects();
resultSet.setResultColumns(childRCList);
/* Replace ResultColumn.expression with new VirtualColumnNodes
* in the ScrollInsensitiveResultSetNode's ResultColumnList. (VirtualColumnNodes include
* pointers to source ResultSetNode, this, and source ResultColumn.)
*/
siRCList.genVirtualColumnNodes(resultSet, childRCList);
/* Finally, we create the new ScrollInsensitiveResultSetNode */
resultSet = new ScrollInsensitiveResultSetNode(
resultSet, siRCList, null, getContextManager());
// Propagate the referenced table map if it's already been created
if (siChild.getReferencedTableMap() != null)
{
resultSet.setReferencedTableMap((JBitSet) siChild.getReferencedTableMap().clone());
}
}
}
/**
* Make a ResultDescription for use in a PreparedStatement.
*
* ResultDescriptions are visible to JDBC only for cursor statements.
* For other types of statements, they are only used internally to
* get descriptions of the base tables being affected. For example,
* for an INSERT statement, the ResultDescription describes the
* rows in the table being inserted into, which is useful when
* the values being inserted are of a different type or length
* than the columns in the base table.
*
* @return A ResultDescription for this DML statement
*/
@Override
public ResultDescription makeResultDescription()
{
ResultColumnDescriptor[] colDescs = resultSet.makeResultDescriptors();
String statementType = statementToString();
return getExecutionFactory().getResultDescription(
colDescs, statementType );
}
/**
* Generate the code to create the ParameterValueSet, if necessary,
* when constructing the activation. Also generate the code to call
* a method that will throw an exception if we try to execute without
* all the parameters being set.
*
* @param acb The ActivationClassBuilder for the class we're building
*/
void generateParameterValueSet(ActivationClassBuilder acb)
throws StandardException
{
List<ParameterNode> parameterList =
getCompilerContext().getParameterList();
int numberOfParameters = (parameterList == null) ? 0 : parameterList.size();
if (numberOfParameters <= 0)
return;
ParameterNode.generateParameterValueSet
( acb, numberOfParameters, parameterList);
}
/**
* A read statement is atomic (DMLMod overrides us) if there
* are no work units, and no SELECT nodes, or if its SELECT nodes
* are all arguments to a function. This is admittedly
* a bit simplistic, what if someone has: <pre>
* VALUES myfunc(SELECT max(c.commitFunc()) FROM T)
* </pre>
* but we aren't going too far out of our way to
* catch every possible wierd case. We basically
* want to be permissive w/o allowing someone to partially
* commit a write.
*
* @return true if the statement is atomic
*
* @exception StandardException on error
*/
@Override
public boolean isAtomic() throws StandardException
{
/*
** If we have a FromBaseTable then we have
** a SELECT, so we want to consider ourselves
** atomic. Don't drill below StaticMethodCallNodes
** to allow a SELECT in an argument to a method
** call that can be atomic.
*/
HasNodeVisitor visitor = new HasNodeVisitor(FromBaseTable.class, StaticMethodCallNode.class);
this.accept(visitor);
if (visitor.hasNode())
{
return true;
}
return false;
}
/**
* Accept the visitor for all visitable children of this node.
*
* @param v the visitor
*
* @exception StandardException on error
*/
@Override
void acceptChildren(Visitor v)
throws StandardException
{
super.acceptChildren(v);
if (resultSet != null)
{
resultSet = (ResultSetNode)resultSet.accept(v);
}
}
/**
* Return default privilege needed for this node. Other DML nodes can override
* this method to set their own default privilege.
*
* @return true if the statement is atomic
*/
int getPrivType()
{
return Authorizer.SELECT_PRIV;
}
}
| true |
9b3985cd1ba8d51b07dd5538961192f02bd51c08 | Java | winstone/repository | /src/repository/service/CommentsService.java | UTF-8 | 1,083 | 2.1875 | 2 | [] | no_license | package repository.service;
import java.util.List;
import cn.org.act.sdp.repository.cleavage.entity.CommentsTBean;
/**
* 用户评价接口
* @author Mandula
*
*/
public interface CommentsService {
/**
* 保存一个用户评价
* @param jobId
* @param serviceId 被评价的serviceId
* @param comment 评价的内容
* @param fromUser 评价的用户,null的时候数据库相应的值为-1
* @return 评价保存是否成功
*/
public boolean save(Long jobId,Long serviceId,String comment,String fromUser);
/**
* 通过ServiveId获取用户评价集合
* @param jobId
* @param serviceId
* @return 本serviceId相应Service的用户评价集合
*/
public List get(Long jobId,Long serviceId);
/**
* 通过commentsId获取一个commentTBean
* @param id
* @return
*/
public CommentsTBean get(long id);
/**
* 返回所有的用户评价
* @param jobId
* @return 用户评价集合
*/
public List getAll(Long jobId);
/**
* 更新一个用户评价
* @param o
* @return
*/
public boolean update(Object o);
}
| true |
9a027c83bd4bd019d512969a1f79ea1b5d2834cb | Java | tobiramalebg/BungeeMOTD | /src/fr/gonzyui/commands/CleanMOTD.java | UTF-8 | 1,413 | 2.359375 | 2 | [
"Apache-2.0"
] | permissive | package fr.gonzyui.commands;
import fr.gonzyui.variables.Messages;
import fr.gonzyui.variables.Variables;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.plugin.Command;
public class CleanMOTD extends Command {
private final Variables variables;
private final Messages messages;
public CleanMOTD(String string, Variables variables, Messages messages) {
super(string);
this.messages = messages;
this.variables = variables;
}
public void execute(CommandSender sender, String[] args) {
if (sender.hasPermission("motd.admin")) {
if (args.length < 1 || args[0].equalsIgnoreCase("help")) {
sender.sendMessage((BaseComponent)new TextComponent(this.messages.getUsage()));
} else if (args[0].equalsIgnoreCase("reload")) {
this.variables.reloadConfig();
this.messages.reload();
sender.sendMessage((BaseComponent)new TextComponent(this.messages.getReload()));
} else {
sender.sendMessage((BaseComponent)new TextComponent(this.messages.getUnknownCommand()));
}
} else {
sender.sendMessage((BaseComponent)new TextComponent(this.messages.getNoPerm()));
}
}
}
| true |
44d23909e66bb87ba0502f7c1c625b83837b30c2 | Java | thejitesh/OnlineCompetionAlgoPractice | /app/src/main/java/com/example/jiteshvartak/onlinetestalgorithmspractice/BoundsComparision.java | UTF-8 | 699 | 3.171875 | 3 | [] | no_license | package com.example.jiteshvartak.onlinetestalgorithmspractice;
import java.util.*;
class BoundsComparision {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
Arrays.sort(arr);
int start = 0;
int end = 0;
int count = 0;
if (arr[0] == 0) {
start = arr[0];
end = start + 4;
count++;
}
for (int i = 0; i < n; i++) {
if (arr[i] > end) {
start = arr[i];
end = start + 4;
count++;
}
}
print(count + "");
scanner.close();
}
static void print(String str) {
System.out.println(str);
}
} | true |
cb43f3e10c94e215ddd44fab1acdb11a14e8e03b | Java | hun20415/IOF | /IOF/src/main/java/kr/ac/iof/main/dao/FarmEquipListDao.java | UTF-8 | 1,398 | 1.867188 | 2 | [] | no_license | /** **/
/** File Name : FarmEquipListDao.java **/
/** Description : FarmEquipList Dao interface **/
/** Update : 2015.05.14(옥정윤) **/
/** ETC : **/
/** **/
package kr.ac.iof.main.dao;
import java.util.List;
import kr.ac.iof.model.Main.FarmEquipList;
import kr.ac.iof.model.Main.FarmInfo;
public interface FarmEquipListDao {
public void add(int m_farmId, int m_eqTypeId, FarmEquipList farmEquipList);
public void delete(int m_farmId, int eqId);
public void update(int m_farmId, int m_eqTypeId, FarmEquipList farmEquipList);
public List<FarmEquipList> getAll();
public FarmEquipList getById(int m_farmId, int m_eqTypeId);
public FarmEquipList getById(int m_farmId, int farmSectionId, int eqId);
//songlock 2015-06-03
public List<FarmEquipList> getByFarmIdAndSectionId(int m_farmId, int farmSectionId);
public List<FarmEquipList> getAll2(int farmId);
}
| true |
e75627130cdfab511e3624ec35a4c39a4096db00 | Java | rocmeister/Trivia-Game | /src/egc3_lw31/server/chatroom/model/IChatRoomModel2ViewAdapter.java | UTF-8 | 743 | 2.5625 | 3 | [] | no_license | package egc3_lw31.server.chatroom.model;
import java.awt.Component;
import java.util.List;
import common.IGroup;
import common.IRemoteConnection;
/**
* The adapter from the mini model to view
*/
public interface IChatRoomModel2ViewAdapter {
/**
* Add text to the view
* @param t Text to display
*/
public void appendString(String t);
/**
* Add the GUI component
* @param comp The GUI component to add
*/
public void addComponent(Component comp);
/**
* Create a tab for team room
* @param name Name of tab for team room
* @param teamMbrsConnections Members in new chatroom
* @return Chatroom that has been created
*/
public IGroup createTeamRoom(String name, List<IRemoteConnection> teamMbrsConnections);
}
| true |
2501c3f1f376a6be811cca85f8b6d9418d644cb4 | Java | zumrutsarp/robotkod4 | /src/main/java/frc/robot/commands/Runhopper.java | UTF-8 | 1,550 | 2.671875 | 3 | [] | no_license | package frc.robot.commands;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.subsystems.hoppersubsystem;
public class Runhopper extends CommandBase {
/**
* Creates a new Runhopper.
*/
private String mode;
private final hoppersubsystem m_hopper;
private double m_speed=0.6;
private double h_speed =0.8;
private double l_speed=0.4;
public Runhopper(final String _mode,final hoppersubsystem _hopper )
{
// Use addRequirements() here to declare subsystem dependencies.
this.mode = _mode;
this.m_hopper = _hopper;// burası hata verecektir çünki burada
addRequirements(_hopper );// subsystem ile commandimizi eşleştirdiğimiz kısımfakat buraa
}
// Called when the command is initially scheduled.
@Override
public void initialize() {
}
// Called every time the scheduler runs while the command is scheduled.
@Override
public void execute() {
if (mode =="normal"){
m_hopper.runhopper("normal",m_speed,m_speed);
}
else if ( mode=="negative" ){
m_hopper.runhopper("negative",l_speed,l_speed);
}
else if (mode=="fastnormal"){
m_hopper.runhopper("fastnormal",h_speed,h_speed);
}
else{
m_hopper.runhopper("nothing ", -m_speed, m_speed);
}
}
// Called once the command ends or is interrupted.
@Override
public void end(boolean interrupted) {
m_hopper.runhopper( "nothing",0,0 );
}
// Returns true when the command should end.
@Override
public boolean isFinished() {
return false;
}} | true |
4d01af48bccd55a5c2d8e67a8a8193dc7d672156 | Java | muten84/spring-security-oauth2 | /others/sdoagent-poc/sdoemsrepo-mobileagent/target/generated-sources/annotations/it/eng/areas/ems/mobileagent/module/AgentModule_ProvideDocumentStoreFactory.java | UTF-8 | 1,141 | 2.0625 | 2 | [] | no_license | package it.eng.areas.ems.mobileagent.module;
import dagger.internal.Factory;
import dagger.internal.Preconditions;
import it.eng.areas.ems.mobileagent.message.db.DocumentStore;
import javax.annotation.Generated;
@Generated(
value = "dagger.internal.codegen.ComponentProcessor",
comments = "https://google.github.io/dagger"
)
public final class AgentModule_ProvideDocumentStoreFactory implements Factory<DocumentStore> {
private final AgentModule module;
public AgentModule_ProvideDocumentStoreFactory(AgentModule module) {
this.module = module;
}
@Override
public DocumentStore get() {
return Preconditions.checkNotNull(
module.provideDocumentStore(), "Cannot return null from a non-@Nullable @Provides method");
}
public static AgentModule_ProvideDocumentStoreFactory create(AgentModule module) {
return new AgentModule_ProvideDocumentStoreFactory(module);
}
public static DocumentStore proxyProvideDocumentStore(AgentModule instance) {
return Preconditions.checkNotNull(
instance.provideDocumentStore(),
"Cannot return null from a non-@Nullable @Provides method");
}
}
| true |
cc8a85b0829c5ec7062d768be9cf63ecf740c62d | Java | IMTAltiStudiLucca/Klava2 | /CaseStudies/src/app/skeleton/sorting/v1/DistributedSortMaster.java | UTF-8 | 4,905 | 2.484375 | 2 | [] | no_license | package app.skeleton.sorting.v1;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Vector;
import app.operations.TupleOperations;
import apps.sorting.QSort;
import common.TupleLogger;
import interfaces.ITupleSpace;
import profiler.DProfiler;
public class DistributedSortMaster<T extends ITupleSpace> {
private Object masterGSName;
Class tupleSpaceClass;
TupleLogger logger = null;
// specific data
private int[] values;
private int threshold;
int numberOfWorkers;
ArrayList<Object> workerTSName;
public static Object[] sortingTupleTemplate = new Object[] { String.class, QSort.class, String.class };
public DistributedSortMaster(Object masterGSName, int numberOfWorkers, int[] values, Class tupleSpaceClass) {
this.masterGSName = masterGSName;
this.numberOfWorkers = numberOfWorkers;
this.values = values;
// this.workerTSName = workerTSName;
this.tupleSpaceClass = tupleSpaceClass;
}
public void start() throws FileNotFoundException, IOException, InterruptedException {
System.out.println("Connecting to data grid " + masterGSName);
// start local tuple space
T masterSpace = (T) getInstanceOfT(tupleSpaceClass);
masterSpace.startTupleSpace(masterGSName, numberOfWorkers, true);
threshold = (int) (values.length * 0.01d);
QSort qs = new QSort(values, threshold);
System.out.println("Done.");
System.out.println("Master started");
int workerCounter = 0;
while (true) {
Thread.sleep(50);
TupleOperations.takeTuple(masterSpace,
masterSpace, masterSpace.formTuple("SortingTuple",
new Object[] { "sorting", null, "worker_ready" }, sortingTupleTemplate), true, false);
workerCounter++;
if (workerCounter == numberOfWorkers)
break;
}
System.out.println("Master: all worker are connected");
TupleLogger.begin("Master::TotalRuntime");
// spread the test key
TupleOperations.writeTuple(masterSpace, masterSpace, masterSpace.formTuple("SortingTuple",
new Object[] { "master_key", null, DProfiler.testKey }, DistributedSortMaster.sortingTupleTemplate),
true, false);
// choose on of the workers and send to it all data
System.out.print("Adding data to tuplespace...");
/*
* ArrayList<ITupleSpace> allWorkerTS = new ArrayList<>(); for(int i =
* 0; i < workerTSName.size(); i++) { T workerTS =
* getInstanceOfT(tupleSpaceClass);
* workerTS.startTupleSpace(workerTSName.get(i), numberOfWorkers,
* false); allWorkerTS.add(workerTS); }
*/
TupleOperations.writeTuple(
masterSpace, masterSpace, masterSpace.formTuple("SortingTuple",
new Object[] { "sort_array", qs, "unsorted" }, DistributedSortMaster.sortingTupleTemplate),
true, false);
qs = null;
// collect sorted sections of array
int n = 0;
Vector<int[]> sortedPartitions = new Vector<int[]>();
System.out.print("Waiting for sorted parts...");
while (n < values.length) {
// SortingTuple foundTuple = gigaSpace.take(new SortingTuple(null,
// "sorted"), takeTimeout);
Object foundTupleTupleTemplate = masterSpace.formTuple("SortingTuple",
new Object[] { "sorting", null, "sorted" }, DistributedSortMaster.sortingTupleTemplate);
Object foundTupleTupleObject = TupleOperations.takeTuple(masterSpace, masterSpace, foundTupleTupleTemplate,
true, false);
Object[] foundTuple = masterSpace.tupleToObjectArray("SortingTuple", foundTupleTupleObject);
QSort q = (QSort) foundTuple[1];
sortedPartitions.addElement(q.getData());
n += q.getData().length;
System.out.println("collected " + n + " elements.");
}
System.out.println("Done. " + sortedPartitions.size() + " partitions collected.");
// reconstruct array
values = MegreSort.reconstructArray(sortedPartitions, values.length);
// stop all workers
for (int i = 0; i < numberOfWorkers; i++)
TupleOperations.writeTuple(masterSpace, masterSpace, masterSpace.formTuple("SortingTuple",
new Object[] { "sort_array", null, "complete" }, DistributedSortMaster.sortingTupleTemplate), true,
false);
TupleLogger.end("Master::TotalRuntime");
DProfiler.writeTestKeyToFile(DProfiler.testKey);
String executionFolder = System.getProperty("user.dir");
System.out.println(executionFolder);
TupleLogger.writeAllToFile(DProfiler.testKey);
// TupleLogger.printStatistics(executionFolder, DProfiler.testKey,
// new String[] { "take::remote", "take::local", "write::remote", "write::local", "takeE::local",
// "takeE::remote", "read::l-r", "nodeVisited", "Master::TotalRuntime" });
System.out.println("Master process finished...Shutting down...");
Thread.sleep(10000);
System.exit(0);
}
public T getInstanceOfT(Class<T> aClass) {
try {
return aClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
| true |
dfaa5d19e9d7f4082d506c4a32eee4cda982c83f | Java | k0l0ssus/codesicles | /code-with-quarkus/src/main/java/com/apress/demo/guesstimator/dao/GameRequestHandler.java | UTF-8 | 298 | 1.703125 | 2 | [
"Apache-2.0"
] | permissive | package com.apress.demo.guesstimator.dao;
import com.apress.demo.guesstimator.dto.GuesstimatorRequestDTO;
import com.apress.demo.guesstimator.dto.GuesstimatorResponseDTO;
public interface GameRequestHandler {
public GuesstimatorResponseDTO handle(GuesstimatorRequestDTO request);
}
| true |
c0b448daac472661620a94efc60dc49069d118d7 | Java | lexicalintelligence/lexical | /lexicalj/src/main/java/com/lexicalintelligence/search/SearchRequest.java | UTF-8 | 2,193 | 2.078125 | 2 | [] | no_license | /*
* Copyright 2015 Lexical Intelligence, LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lexicalintelligence.search;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.codehaus.jackson.type.TypeReference;
import com.lexicalintelligence.admin.LexicalAdminClient;
public class SearchRequest {
protected final Log log = LogFactory.getLog(SearchRequest.class);
protected static final String PATH = "/search";
protected LexicalAdminClient client;
protected String query;
public SearchRequest(LexicalAdminClient client) {
this.client = client;
}
public SearchRequest setQuery(String query) {
this.query = query;
return this;
}
public SearchResponse execute() {
Reader reader = null;
SearchResponse searchResponse = new SearchResponse(true);
try {
HttpResponse response = client.getHttpClient().execute(new HttpGet(client.getUrl() + PATH + "?prefix=" + URLEncoder.encode(query, "UTF-8")));
reader = new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8);
List<String> items = client.getObjectMapper().readValue(reader, new TypeReference<List<String>>() {
});
searchResponse.setItems(items);
}
catch (Exception e) {
searchResponse = new SearchResponse(false);
log.error(e);
}
finally {
try {
reader.close();
}
catch (Exception e) {
log.error(e);
}
}
return searchResponse;
}
}
| true |
7a9946cbb4a4f782ea26c186be75dd9d5b9b124d | Java | raminarmanfar/sb-jpa-hibernate-course | /src/test/java/com/armanfar/sbjdbcdemo/CriteriaQueryTest.java | UTF-8 | 3,871 | 2.546875 | 3 | [] | no_license | package com.armanfar.sbjdbcdemo;
import com.armanfar.sbjdbcdemo.section5.model.Course;
import com.armanfar.sbjdbcdemo.section5.model.Student;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.*;
import java.util.List;
@SpringBootTest(classes = Section9DemoApplication.class)
public class CriteriaQueryTest {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private EntityManager em;
@Test
@Transactional
public void test_criteria_query_get_all_courses() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Course> cq = cb.createQuery(Course.class);
Root<Course> courseRoot = cq.from(Course.class);
TypedQuery<Course> query = em.createQuery(cq.select(courseRoot));
List<Course> courses = query.getResultList();
logger.info("\n>>>>>>>>>>>>>> Courses -> {}", courses);
}
@Test
@Transactional
public void test_criteria_query_with_condition() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Course> cq = cb.createQuery(Course.class);
Root<Course> courseRoot = cq.from(Course.class);
Predicate likeCondition = cb.like(courseRoot.get("name"), "%100 Steps%");
cq.where(likeCondition);
TypedQuery<Course> query = em.createQuery(cq.select(courseRoot));
List<Course> courses = query.getResultList();
logger.info("\n>>>>>>>>>>>>>> Courses -> {}", courses);
}
@Test
@Transactional
public void test_criteria_query_courses_without_students() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Course> cq = cb.createQuery(Course.class);
Root<Course> courseRoot = cq.from(Course.class);
Predicate studentsIsEmpty = cb.isEmpty(courseRoot.get("students"));
cq.where(studentsIsEmpty);
TypedQuery<Course> query = em.createQuery(cq.select(courseRoot));
List<Course> courses = query.getResultList();
logger.info("\n>>>>>>>>>>>>>> Courses -> {}", courses);
}
@Test
@Transactional
public void test_criteria_query_join_courses_with_students() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Course> cq = cb.createQuery(Course.class);
Root<Course> courseRoot = cq.from(Course.class);
courseRoot.join("students");
TypedQuery<Course> query = em.createQuery(cq.select(courseRoot));
List<Course> courses = query.getResultList();
logger.info("\n\n>>>>>>>>>>>>>>>>>>>>>>>>> Total Courses found -> {}", courses.size());
for(Course course: courses) {
logger.info("\n>>>>>>>>>>>>>> Courses -> {} -> students taken the course -> {}", course, course.getStudents());
}
}
@Test
@Transactional
public void test_criteria_query_left_join_courses_with_students() {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Course> cq = cb.createQuery(Course.class);
Root<Course> courseRoot = cq.from(Course.class);
courseRoot.join("students", JoinType.LEFT);
TypedQuery<Course> query = em.createQuery(cq.select(courseRoot));
List<Course> courses = query.getResultList();
logger.info("\n\n>>>>>>>>>>>>>>>>>>>>>>>>> Total Courses found -> {}", courses.size());
for(Course course: courses) {
logger.info("\n>>>>>>>>>>>>>> Courses -> {} -> students taken the course -> {}", course, course.getStudents());
}
}
}
| true |
f4ff29b58ed5d14f4eedf2a495bc098808ad4edf | Java | rbramwell/rundeck-cli | /src/main/java/org/rundeck/client/util/ExtConfigSource.java | UTF-8 | 1,133 | 2.25 | 2 | [
"Apache-2.0"
] | permissive | package org.rundeck.client.util;
import com.simplifyops.toolbelt.InputError;
/**
* @author greg
* @since 1/11/17
*/
public class ExtConfigSource implements ConfigSource {
ConfigSource configSource;
public ExtConfigSource(final ConfigSource configSource) {
this.configSource = configSource;
}
@Override
public int getInt(final String key, final int defval) {
return configSource.getInt(key, defval);
}
@Override
public Long getLong(final String key, final Long defval) {
return configSource.getLong(key, defval);
}
@Override
public boolean getBool(final String key, final boolean defval) {
return configSource.getBool(key, defval);
}
@Override
public String getString(final String key, final String defval) {
return configSource.getString(key, defval);
}
@Override
public String get(final String key) {
return configSource.get(key);
}
@Override
public String require(final String key, final String description) throws InputError {
return configSource.require(key, description);
}
}
| true |
7e0cc8ae3fa011da527af0c68a67bb47c909289b | Java | jaghaimo/starsector-api | /src/com/fs/starfarer/api/impl/campaign/OverheadTooltipCreator.java | UTF-8 | 2,113 | 2.359375 | 2 | [] | no_license | package com.fs.starfarer.api.impl.campaign;
import com.fs.starfarer.api.ui.TooltipMakerAPI;
import com.fs.starfarer.api.ui.TooltipMakerAPI.TooltipCreator;
public class OverheadTooltipCreator implements TooltipCreator {
public void createTooltip(TooltipMakerAPI tooltip, boolean expanded, Object tooltipParam) {
// FDNode node = (FDNode) tooltipParam;
//
// float pad = 3f;
// float opad = 10f;
// Color h = Misc.getHighlightColor();
// Color g = Misc.getGrayColor();
//
// MarketAPI market = (MarketAPI) node.custom;
//
// OverheadData overhead = CoreScript.computeOverhead(market);
//
// tooltip.addPara("Overhead due to scaling up operations to meet demand from multiple sources.", opad);
//
// if (overhead.max != null) { // shouldn't be possible, but just in case
// SupplierData sd = overhead.max;
// CommodityOnMarketAPI com = sd.getCommodity();
// String units = "units";
// if (sd.getQuantity() == 1) units = "unit";
// tooltip.addPara("The highest-value export from " + market.getName() + " is %s " + units +
// " of " + com.getCommodity().getName() + " sold to " + sd.getMarket().getName() +
// " for %s per month.",
// opad,
// h,
// "" + sd.getQuantity(), Misc.getDGSCredits(sd.getExportValue(market)));
//
// tooltip.addPara("The total value of exports from " + market.getName() + " is %s, " +
// "resulting in approximately %s overhead.",
// opad, h,
// Misc.getDGSCredits(market.getExportIncome(false)),
// "" + (int)Math.round(overhead.fraction * 100f) + "%");
// }
//
// tooltip.addPara("More exports always result in more income, but the gains decrease " +
// "exponentially with more export destinations being shipped to.", g, opad);
// tooltip.addPara("The overhead amount is based on the highest single export; the higher it is, the lower " +
// "the overall amount of overhead.", g, opad);
}
public float getTooltipWidth(Object tooltipParam) {
return 450;
}
public boolean isTooltipExpandable(Object tooltipParam) {
return false;
}
}
| true |
35a74f13c1efaeb4fa61606603bca9ba0b6ba276 | Java | romanperesypkin/Java | /3.Java_PRO/PRO_2_HW_JSON_XML/src/Main/TaskTwo/TaskTwo.java | UTF-8 | 1,510 | 2.78125 | 3 | [] | no_license | package Main.TaskTwo;
import com.sun.jmx.remote.internal.Unmarshal;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.File;
public class TaskTwo {
public static void run()
{
Trains trains = new Trains();
/*
trains.add(new Train("1", "AA", "BB", "1234", "6789"));
trains.add(new Train("2", "AA", "BB", "1234", "6789"));
*/
try
{
//File file = new File("D:\\MyPrj\\Java_main\\PRO_HW_JSON_XML\\out.xml");
File file = new File("D:\\MyPrj\\Java_main\\PRO_HW_JSON_XML\\trains.xml");
/*
if ( ! file.exists())
return;
*/
JAXBContext jaxb_context = JAXBContext.newInstance(Trains.class);
/*
Marshaller marshaller = jaxb_context.createMarshaller();
//Make output xml files readable for human
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(trains, file);
marshaller.marshal(trains, System.out);
*/
Unmarshaller unmarshaller = jaxb_context.createUnmarshaller();
trains = (Trains) unmarshaller.unmarshal(file);
System.out.println(trains);
}
catch (JAXBException ex)
{
ex .getStackTrace();
}
}
}
| true |
1b3a2507933a1448d516d0509c129d97f6f000ad | Java | webprograming2018/finalproject-n1_3_studentwebnew | /Ver x.0/Ver3/StudentWeb/src/java/DAO/AdminDAO.java | UTF-8 | 2,430 | 2.734375 | 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 DAO;
import connectDB.connectDB;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import model.Admin;
import model.LichThi;
/**
*
* @author Administrator
*/
public class AdminDAO {
connectDB con;
Statement stm;
PreparedStatement ps;
ResultSet rs;
public AdminDAO() {
if(con == null)
con= new connectDB();
}
public Admin checkLogin(String username, String password){
Admin admin = null;
String strSQL = "select * from tbladmin where username = '" + username + "' and password = '" + password + "'";
try {
rs = con.getStatement().executeQuery(strSQL);
while (rs.next()) {
String ho = rs.getString("ho");
String ten = rs.getString("ten");
String image = rs.getString("image");
String maNV = rs.getString("maNV");
admin = new Admin(username, password, maNV, ho, ten, image);
}
con.closeConnet();
} catch (Exception e) {
e.printStackTrace();
}
return admin; // null is false;
}
public boolean update(Admin admin, String maNV) {
try {
String sql = "update tbladmin a set a.username = ? , a.password = ? , a.maNV = ? , a.ho = ? , a.ten = ? where a.maNV = ? " ;
ps = con.openConnect().prepareStatement(sql);
ps.setString(1, admin.getUsername());
ps.setString(2, admin.getPassword());
ps.setString(3, admin.getMaNV());
ps.setString(4, admin.getHo());
ps.setString(5, admin.getTen());
ps.setString(6, maNV);
return ps.executeUpdate() == 1;
} catch (Exception ex) {
return false;
}
}
public static void main(String[] args) {
// Admin admin = new AdminDAO().checkLogin("hiep97", "123");
// System.out.println(admin.ho + admin.ten + admin.image + admin.maNV);
AdminDAO a = new AdminDAO();
Admin admin = new Admin("hiep97", "123", "NV102", "Lê", "Tuấn Hiệp");
System.out.println(a.update(admin, "NV101"));
}
}
| true |
7d556feadb4a6007889822c99d241c89ded4684f | Java | gvrc1881/scr | /src/main/java/com/scr/repository/AssistanceRepository.java | UTF-8 | 281 | 1.578125 | 2 | [] | no_license | package com.scr.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.scr.model.Assistance;
@Repository
public interface AssistanceRepository extends JpaRepository<Assistance, Long>{
}
| true |
1b9ef1aeb2b86814aa84ffaf88af8b38821c0c20 | Java | petekofod/tstoolv2 | /src/main/java/net/railwaynet/logdelivery/strolr/FederationsController.java | UTF-8 | 6,100 | 2.03125 | 2 | [] | no_license | package net.railwaynet.logdelivery.strolr;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jcraft.jsch.JSchException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
@RestController
public class FederationsController {
private static final Logger logger = LoggerFactory.getLogger(FederationsController.class);
private static final ObjectMapper objectMapper = new ObjectMapper();
@Value("${scac.federations.mapping.file:scac.json}")
private String SCAC_FILE;
private static Map<String, List<String>> SCAC_FEDERATION;
@Autowired
private Environment env;
private static String IOB_ADDRESS;
private static String REMOTE_HOST;
private static String REMOTE_USERNAME;
private static String REMOTE_KEY;
public Map<String, List<String>> getScacFederation() {
if (SCAC_FEDERATION == null) {
try {
SCAC_FEDERATION = objectMapper.readValue(new FileReader(SCAC_FILE),
new TypeReference<Map<String, List<String>>>() {});
if (logger.isInfoEnabled()) {
logger.info("List of SCAC:");
for (Map.Entry<String, List<String>> entry: SCAC_FEDERATION.entrySet()) {
logger.info(entry.getKey() + " : " + Arrays.toString(entry.getValue().toArray()));
}
}
} catch (IOException e) {
logger.error("Can't read " + SCAC_FILE, e);
throw new ResponseStatusException(
HttpStatus.INTERNAL_SERVER_ERROR, "Can't read the list of SCAC/railroads!", e);
}
}
return SCAC_FEDERATION;
}
public String getRemoteHost() {
if (REMOTE_HOST == null) {
REMOTE_HOST = env.getProperty("remote_host");
logger.info("SSH remote host: " + REMOTE_HOST);
}
return REMOTE_HOST;
}
public String getRemoteUsername() {
if (REMOTE_USERNAME == null) {
REMOTE_USERNAME = env.getProperty("remote_username");
logger.info("SSH username: " + REMOTE_USERNAME);
}
return REMOTE_USERNAME;
}
public String getRemoteKey() {
if (REMOTE_KEY == null) {
REMOTE_KEY = env.getProperty("remote_key");
logger.info("SSH key: " + REMOTE_KEY);
}
return REMOTE_KEY;
}
private String getIP() {
if (IOB_ADDRESS == null) {
IOB_ADDRESS = env.getProperty("iobaddress");
logger.info("IOB Address: " + IOB_ADDRESS);
}
return IOB_ADDRESS;
}
private Map<String, Object> handleFederation(String name, String[] outputLines) {
logger.debug("Parsing...");
Map<String, Object> json = new HashMap<>();
json.put("name", name);
boolean headerPassed = false;
int totalHosts = 0;
int operationalHosts = 0;
for (String line: outputLines) {
logger.debug("next line: " + line);
if (headerPassed) {
String[] tokens = line.split("\\s+");
String host = tokens[0];
String status = tokens[4];
logger.debug("Host: " + host + ", status: " + status);
if (host.startsWith(name)) {
totalHosts++;
if (status.equals("Operational"))
operationalHosts++;
}
} else {
headerPassed = line.contains("================");
}
}
json.put("total_servers", totalHosts);
json.put("operational_servers", operationalHosts);
return json;
}
@CrossOrigin
@RequestMapping("/federations.json/{scac}")
public String railroads(@PathVariable(value="scac") String scac) {
scac = scac.toUpperCase();
logger.debug("Requesting federation statuses for " + scac);
List<String> federations = getScacFederation().get(scac);
if (federations == null) {
throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "Unknown SCAC!");
}
String qpidRoute;
try {
qpidRoute = RemoteExecBySSH.execScript(getRemoteHost(), getRemoteKey(), getRemoteUsername(), "qpid-route link list " + getIP() + ":16000");
} catch (JSchException | IOException e) {
logger.debug("Can't get results of qpid-route!", e);
throw new ResponseStatusException(
HttpStatus.INTERNAL_SERVER_ERROR, "Can't get results of qpid-route command!", e);
}
String[] outputLines = qpidRoute.split(System.getProperty("line.separator"));
Map<String,Object> json = new HashMap<>();
json.put("SCAC", scac);
List<Map<String, Object>> federationsJson = new ArrayList<>();
json.put("federations", federationsJson);
for (String f: federations) {
logger.debug("Adding federation " + f);
federationsJson.add(handleFederation(f, outputLines));
}
try {
return objectMapper.writeValueAsString(json);
} catch (JsonProcessingException e) {
throw new ResponseStatusException(
HttpStatus.INTERNAL_SERVER_ERROR, "Can't serialize the result to JSON!", e);
}
}
}
| true |
38bc530cf8fa8622abf9d42e3ff0617d8a19e6f9 | Java | perfectsense/training | /core/src/main/java/brightspot/importtransformers/BlogPageImportTransformer.java | UTF-8 | 4,795 | 1.890625 | 2 | [] | no_license | package brightspot.importtransformers;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import brightspot.blog.BlogPage;
import brightspot.importapi.ImportTransformer;
import brightspot.importtransformers.element.ImportElementUtil;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import com.psddev.cms.db.Seo;
import com.psddev.dari.db.Predicate;
import com.psddev.dari.db.PredicateParser;
import com.psddev.dari.util.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
public class BlogPageImportTransformer extends ImportTransformer<BlogPage> {
private static final String DISPLAY_NAME_FIELD = "displayName";
private static final String INTERNAL_NAME_FIELD = "internalName";
private static final String DESCRIPTION_FIELD = "description";
private static final String PARENT_FIELD = "parent";
private static final String LEAD_IMAGE_FIELD = "leadImage";
private static final String PROMO_IMAGE_FIELD = "promoImage";
private static final String PROMO_DESCRIPTION_FIELD = "promoDescription";
private static final String SEO_TITLE_FIELD = "seoTitle";
private static final String SEO_DESCRIPTION_FIELD = "seoDescription";
private static final String SEO_KEYWORDS_FIELD = "seoKeywords";
@JsonProperty(DISPLAY_NAME_FIELD)
private String displayName;
@JsonProperty(INTERNAL_NAME_FIELD)
private String internalName;
@JsonProperty(DESCRIPTION_FIELD)
private String description;
@JsonProperty(PARENT_FIELD)
private BlogPageImportTransformer parent;
@JsonProperty(LEAD_IMAGE_FIELD)
private WebImageImportTransformer imageReference;
@JsonProperty(PROMO_IMAGE_FIELD)
private WebImageImportTransformer promoImageReference;
@JsonProperty(PROMO_DESCRIPTION_FIELD)
private String promoDescription;
@JsonProperty(SEO_TITLE_FIELD)
private String seoTitle;
@JsonProperty(SEO_DESCRIPTION_FIELD)
private String seoDescription;
@JsonProperty(SEO_KEYWORDS_FIELD)
private Set<String> seoKeywords;
@Override
public String getExternalId() {
return ObjectUtils.firstNonBlank(this.externalId, this.getIdAsString(), this.displayName);
}
@Override
public BlogPage transform() throws Exception {
Preconditions.checkArgument(
StringUtils.isNotBlank(this.getDisplayName()),
"displayName not provided for BlogPage with externalId [" + this.getExternalId() + "]");
BlogPage blog = (BlogPage) this.createNewObject();
blog.setDisplayName(ImportElementUtil.processInlineRichText(this.getDisplayName(), this));
blog.setInternalName(this.getInternalName());
blog.setDescription(ImportElementUtil.processInlineRichText(this.getDescription(), this));
if (parent != null) {
Optional.ofNullable(parent.findOrCreate(this))
.ifPresent(p -> p.asHasSectionWithFieldData().setSection(p));
}
blog.setLead(ImportTransformerUtil.retrieveModuleLead(this.getImageReference(), this));
ImportTransformerUtil.setPromoImage(blog, this.getPromoImageReference(), this);
blog.asPagePromotableWithOverridesData()
.setPromoDescription(ImportElementUtil.processInlineRichText(this.getPromoDescription(), this));
blog.asSeoWithFieldsData().setTitle(this.getSeoTitle());
blog.asSeoWithFieldsData().setDescription(this.getSeoDescription());
blog.as(Seo.ObjectModification.class).setKeywords(this.getSeoKeywords());
return blog;
}
@Override
public Predicate getUniqueFieldPredicate() {
if (StringUtils.isBlank(this.getDisplayName())) {
return null;
}
return PredicateParser.Static.parse(
BlogPage.class.getName() + "/displayName = \"" + this.getDisplayName() + "\"");
}
public String getDisplayName() {
return displayName;
}
public String getInternalName() {
return internalName;
}
public String getDescription() {
return description;
}
public BlogPageImportTransformer getParent() {
return parent;
}
public WebImageImportTransformer getImageReference() {
return imageReference;
}
public WebImageImportTransformer getPromoImageReference() {
return promoImageReference;
}
public String getPromoDescription() {
return promoDescription;
}
public String getSeoTitle() {
return seoTitle;
}
public String getSeoDescription() {
return seoDescription;
}
public Set<String> getSeoKeywords() {
if (seoKeywords == null) {
seoKeywords = new HashSet<>();
}
return seoKeywords;
}
}
| true |
bdb0e89ffc984b7d214b0a4fac2063ce2e47a12e | Java | devmngr/SDJ1-Java | /Exam1/src/ex2/MyDate.java | UTF-8 | 1,369 | 3.625 | 4 | [] | no_license | package ex2;
import java.util.GregorianCalendar;
public class MyDate
{
private int day;
private int month;
private int year;
public MyDate(int day, int month, int year)
{
this.day = day;
this.month = month;
this.year = year;
}
public int getDay()
{
return day;
}
public int getMonth()
{
return month;
}
public int getYear()
{
return year;
}
public void set(int day, int month, int year)
{
this.day = day;
this.month = month;
this.year = year;
}
public MyDate copy()
{
return new MyDate(day, month, year);
}
public boolean equals(Object obj)
{
if (!(obj instanceof MyDate))
{
return false;
}
MyDate other = (MyDate) obj;
return day == other.day && month == other.month && year == other.year;
}
public String toString()
{
return "Rented from: " + day + "/" + month + "/" + year;
}
public MyDate now()
{
GregorianCalendar currentDate = new GregorianCalendar();
int currentDay = currentDate.get(GregorianCalendar.DATE);
int currentMonth = currentDate.get(GregorianCalendar.MONTH);
int currentYear = currentDate.get(GregorianCalendar.YEAR);
MyDate Current = new MyDate(currentDay, currentMonth, currentYear);
return Current;
}
}
| true |
f744549449bce822a35fbc3ff42caba1c2620b06 | Java | jritter/InstaCircleLib | /InstaCircleLib/src/ch/bfh/evoting/instacirclelib/service/ProcessBroadcastMessageIntentService.java | UTF-8 | 6,070 | 2.375 | 2 | [] | no_license | package ch.bfh.evoting.instacirclelib.service;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.util.Arrays;
import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import ch.bfh.evoting.instacirclelib.Message;
import ch.bfh.evoting.instacirclelib.db.NetworkDbHelper;
public class ProcessBroadcastMessageIntentService extends IntentService {
private static final String TAG = NetworkService.class.getSimpleName();
private static final String PREFS_NAME = "network_preferences";
private static final Integer[] messagesToSave = { Message.MSG_CONTENT,
Message.MSG_MSGJOIN, Message.MSG_MSGLEAVE };
private NetworkDbHelper dbHelper;
private String cipherKey;
private CipherHandler cipherHandler;
public ProcessBroadcastMessageIntentService() {
super(TAG);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Initializing the dbHelper in order to get access to the database
dbHelper = NetworkDbHelper.getInstance(this);
cipherKey = getSharedPreferences(PREFS_NAME, 0).getString("password",
"N/A");
cipherHandler = new CipherHandler(cipherKey.getBytes());
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(Intent intent) {
String identification = getSharedPreferences(PREFS_NAME, 0).getString(
"identification", "N/A");
Message msg = null;
boolean dataAvailable = false;
if (intent.getBooleanExtra("decrypted", false)){
msg = (Message) intent.getSerializableExtra("message");
dataAvailable = true;
}
else {
byte[] encryptedData = intent.getByteArrayExtra("encryptedData");
byte[] data = cipherHandler.decrypt(encryptedData);
if (data != null){
// deserializing the payload into a Message object
ByteArrayInputStream bis = new ByteArrayInputStream(
data);
ObjectInput oin = null;
try {
oin = new ObjectInputStream(bis);
msg = (Message) oin.readObject();
}
catch (Exception e){
e.printStackTrace();
} finally {
try {
bis.close();
oin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
msg.setSenderIPAddress(intent.getStringExtra("senderAddress"));
dataAvailable = true;
}
}
// let's try to deserialize the payload only if the
// decryption process has been successful
if (dataAvailable) {
// Use the messagetype to determine what to do with the message
switch (msg.getMessageType()) {
case Message.MSG_CONTENT:
// no special action required, just saving later on...
break;
case Message.MSG_MSGJOIN:
// add the new participant to the participants list
dbHelper.insertParticipant(msg.getMessage(),
msg.getSenderIPAddress());
// notify the UI
intent = new Intent("participantJoined");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
break;
case Message.MSG_MSGLEAVE:
// decativate the participant
dbHelper.updateParticipantState(msg.getSender(), 0);
// Notify the UI, but only if it's not myself who left
if (!msg.getSender().equals(identification)) {
intent = new Intent("participantChangedState");
intent.putExtra("participant", msg.getSenderIPAddress());
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
break;
case Message.MSG_RESENDREQ:
// should be handled as unicast
break;
case Message.MSG_RESENDRES:
// should be handled as unicast
break;
case Message.MSG_WHOISTHERE:
// immediately send a unicast response with my own identification
// back
Message response = new Message(
(dbHelper.getNextSequenceNumber() - 1) + "",
Message.MSG_IAMHERE, identification, -1);
Intent messageIntent = new Intent(this, SendUnicastIntentService.class);
messageIntent.putExtra("message", response);
messageIntent.putExtra("ipAddress", msg.getSenderIPAddress());
startService(messageIntent);
break;
case Message.MSG_IAMHERE:
// should be handled as unicast
break;
default:
// shouldn't happen
break;
}
// handling the conversation relevant messages
if (Arrays.asList(messagesToSave).contains(msg.getMessageType())) {
// checking whether the sequence number is the one which we expect
// from the participant, otherwise request the missing messages
if (msg.getSequenceNumber() != -1
&& msg.getSequenceNumber() > dbHelper
.getCurrentParticipantSequenceNumber(msg
.getSender()) + 1) {
// Request missing messages
Message resendRequestMessage = new Message("",
Message.MSG_RESENDREQ, getSharedPreferences(PREFS_NAME,
0).getString("identification", "N/A"), -1);
Intent messageIntent = new Intent(this, SendUnicastIntentService.class);
messageIntent.putExtra("message", resendRequestMessage);
messageIntent.putExtra("ipAddress", msg.getSenderIPAddress());
startService(messageIntent);
} else {
if (dbHelper != null && (!dbHelper.isMessageInDatabase(msg))) {
// insert the message into the database
dbHelper.insertMessage(msg);
}
}
}
if (msg.getMessageType() == Message.MSG_MSGLEAVE
&& msg.getSender().equals(identification)) {
if (msg.getMessage().equals(Message.DELETE_DB)
&& msg.getSender().equals(identification)) {
dbHelper.cleanDatabase();
}
Intent stopServiceIntent = new Intent(this, NetworkService.class);
stopService(stopServiceIntent);
} else {
// otherwise notify the UI that a new message has been arrived
Intent messageArrivedIntent = new Intent("messageArrived");
messageArrivedIntent.putExtra("message", msg);
LocalBroadcastManager.getInstance(this).sendBroadcast(messageArrivedIntent);
Log.d(TAG, "sent broadcast...");
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
| true |
b0f85712bc8939faa4dda7b65ce95c4f951b3a19 | Java | xuefeiCheng/common | /canyon/src/main/java/com/ebupt/portal/canyon/system/service/impl/LogServiceImpl.java | UTF-8 | 2,470 | 2.125 | 2 | [] | no_license | package com.ebupt.portal.canyon.system.service.impl;
import com.ebupt.portal.canyon.common.enums.UpdateEnum;
import com.ebupt.portal.canyon.common.util.PageableUtil;
import com.ebupt.portal.canyon.common.util.TimeUtil;
import com.ebupt.portal.canyon.common.vo.PageVo;
import com.ebupt.portal.canyon.system.dao.LogDao;
import com.ebupt.portal.canyon.system.entity.Log;
import com.ebupt.portal.canyon.system.service.LogService;
import com.ebupt.portal.canyon.system.vo.LogSearchVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
/**
* 日志处理业务层实现
*
* @author chy
* @date 2019-03-08 16:31
*/
@Service("logService")
public class LogServiceImpl implements LogService {
private final LogDao logDao;
@Autowired
public LogServiceImpl(LogDao logDao) {
this.logDao = logDao;
}
@Override
public void save(Log log) {
this.logDao.save(log);
}
@Override
public Page<Log> findByPage(PageVo<LogSearchVo> pageVo) {
LogSearchVo logSearch = pageVo.getSearch();
Specification<Log> specification = ((root, query, criteriaBuilder) -> {
List<Predicate> list = new ArrayList<>();
if (logSearch != null) {
if (StringUtils.isNotEmpty(logSearch.getUserName())) {
list.add(criteriaBuilder.like(root.get("operator"), logSearch.getUserName() + "%"));
}
if (StringUtils.isNotEmpty(logSearch.getStartTime())) {
list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"), logSearch.getStartTime()));
}
if (StringUtils.isNotEmpty(logSearch.getEndTime())) {
list.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime"), logSearch.getEndTime()));
}
if (StringUtils.isNotEmpty(logSearch.getType())) {
list.add(criteriaBuilder.equal(root.get("result"), logSearch.getType()));
}
}
Predicate[] predicates = new Predicate[list.size()];
return query.where(list.toArray(predicates)).getRestriction();
});
return this.logDao.findAll(specification, PageableUtil.getPageable(pageVo));
}
@Override
public UpdateEnum deleteByTime(int daysAgo) {
String time = TimeUtil.getBeforeDays(daysAgo) + "000000";
this.logDao.deleteByTime(time);
return UpdateEnum.SUCCESS;
}
}
| true |
a12b8ff46d358912d8e1ce8740185a593377be33 | Java | mgonzalez434/Desafio_Uno | /periodos/src/util/UtilFecha.java | UTF-8 | 2,195 | 2.90625 | 3 | [] | no_license | package util;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import java.text.ParseException;
public class UtilFecha {
public ArrayList <Date> calculoFecha(String fechaCreacion, String fechaFin, JsonArray fechas){
ArrayList <Date> fechasArray=this.arregloFechas(fechaCreacion, fechaFin);
for (int i = 0; i < fechas.size(); i++) {
JsonElement object = fechas.get(i);
String fechaAux=object.toString();
Date fecha = this.parseFecha(fechaAux);
fechasArray.remove(fecha);
}
return fechasArray;
}
public Date parseFecha(String fecha)
{
fecha=fecha.replaceAll("\"", "");
SimpleDateFormat formato = new SimpleDateFormat("yyyy-MM-dd");
Date fechaDate = null;
try {
fechaDate = formato.parse(fecha);
}
catch (ParseException ex)
{
System.out.println(ex);
}
return fechaDate;
}
public int parseFechaAnno(Date fecha)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
return Integer.parseInt(dateFormat.format(fecha));
}
public int parseFechaMes(Date fecha)
{
SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
return Integer.parseInt(dateFormat.format(fecha));
}
public ArrayList <Date> arregloFechas(String fechaCreacion, String fechaFin){
ArrayList <Date> fechasArray= new ArrayList<Date>();
Date fechaC = this.parseFecha(fechaCreacion);
Date fechaF = this.parseFecha(fechaFin);
int annoC = this.parseFechaAnno(fechaC);
int annoF = this.parseFechaAnno(fechaF);
int mesC = this.parseFechaMes(fechaC);
int mesF = this.parseFechaMes(fechaF);
for(int i=annoC;i<=annoF;i++){
if(i==annoF){
for(int z=0;z<=mesF;z++){
String mes= Integer.toString(z);
String fechaAux=i+"-"+mes+"-"+"01";
fechasArray.add(this.parseFecha(fechaAux));
}
}else{
for(int z=mesC;z<13;z++){
String mes= Integer.toString(z);
String fechaAux=i+"-"+mes+"-"+"01";
fechasArray.add(this.parseFecha(fechaAux));
}
mesC=01;
}
}
return fechasArray;
}
}
| true |
26910d424ee12217c9225a40af7cc5b6b2a6381f | Java | 1151761454/Hello-World | /CMS/src/cn/xihua/web/filter/PowerFilter.java | GB18030 | 1,544 | 2.3125 | 2 | [] | no_license | package cn.xihua.web.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class PowerFilter implements Filter {
@Override
public void destroy() {
// TODO Զɵķ
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
// TODO Զɵķ
//ÿĬִеķ
//жǷ¼ûе¼ת¼ҳ
//жsessionǷе¼ûд¼
HttpServletRequest request=(HttpServletRequest) req;
HttpServletResponse response=(HttpServletResponse) resp;
HttpSession session=request.getSession();
//ȡݣһnull
Object obj=session.getAttribute("user");
if(obj==null) {
//ʾϢ
session.setAttribute("msg", "ȵ¼");
//ת¼ҳ
response.sendRedirect("/CMS/login.jsp");
return ;//ִ
}
//
chain.doFilter(req, resp);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Զɵķ
}
}
| true |
e3636cf35d751149cbe6bcfadbde14fef4f00874 | Java | adrianocarvalho1990/Testes_Adriano_Carvalho | /src/PreCondicoesAcessarSite.java | ISO-8859-1 | 3,270 | 2.5 | 2 | [] | no_license |
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.*;
public class PreCondicoesAcessarSite {
@Test
public void GerarBoleto() {
String mensagemErro1 = "Preencha este campo.";
// Configurao do Driver
System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to("https://www.alterdata.com.br");
System.out.println("Pgina Inicial Alterdata foi acessada");
// Configurao do timer
WebDriverWait wait = new WebDriverWait(driver, (30));
// Clicar na Central do Cliente
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("(//a[text()='Central do Cliente'])[1]")))
.click();
System.out.println("Pgina da Central do Cliente foi acessada");
// Clicar em Gerar Boleto
List<String> abas = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(abas.get(1));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[text()=' Gerar Boleto']"))).click();
System.out.println("Boto de Gerar Boleto foi aceito");
// Gerar Boleto com Campo em Branco
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@value='Obter boletos']"))));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@value='Obter boletos']"))).click();
System.out.println("Boto obter boleto foi clicado");
try {
Robot robot = new Robot();
BufferedImage bi = robot.createScreenCapture(new Rectangle(100, 100));
ImageIO.write(bi, "jpg", new File("C:/imageTest.jpg"));
} catch (AWTException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Tentativa de acesso com Campos em Branco foi validado");
// Gerar Boleto com Cdigo Cliente Errado
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("CodCliente"))).sendKeys("123456");
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@value='Obter boletos']"))).click();
Assert.assertFalse(driver.getPageSource().contains("OPS! No foi possvel recuperar dados deste cdigo ou no est identificado como cliente Alterdata."));
try {
Robot robot = new Robot();
BufferedImage bi = robot.createScreenCapture(new Rectangle(100, 100));
ImageIO.write(bi, "jpg", new File("C:/imageTest2.jpg"));
} catch (AWTException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Tentativa de acesso com Cdigo do Cliente errado foi validado");
}
} | true |
65a1fe83575355f044cefd3bec610e8e08af0942 | Java | rxfu/lj-javaweb-platform | /platform/src/com/pl/service/impl/UserDetailsServiceImpl.java | UTF-8 | 1,726 | 2.234375 | 2 | [] | no_license | package com.pl.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.pl.dao.SecurityUserDao;
import com.pl.service.BaseUserDetails;
import com.pl.tdo.SecurityUserBean;
public class UserDetailsServiceImpl implements UserDetailsService {
private SecurityUserDao securityUserDao;
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
SecurityUserBean securityUserBean = securityUserDao.selectByUsername(username);
if(securityUserBean == null){
throw new UsernameNotFoundException("用户 : "+username+"不存在!");
}
String userId = securityUserBean.getUserId();
String password = securityUserBean.getPassword();
List<String> authoritiesTemp = securityUserDao.selectAuthoritiesByUserId(userId);
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String auth : authoritiesTemp) {
authorities.add(new GrantedAuthorityImpl(auth));
}
BaseUserDetails baseUserDetails = new BaseUserDetails(userId, username, password, authorities);
return baseUserDetails;
}
public SecurityUserDao getSecurityUserDao() {
return securityUserDao;
}
public void setSecurityUserDao(SecurityUserDao securityUserDao) {
this.securityUserDao = securityUserDao;
}
}
| true |
615f26958632de08337482f3fed1dd7b9d576ce6 | Java | DipasDam107/ProcesosYThreads | /src/main/java/ejercicioFilosofos/CenaFilosofos.java | UTF-8 | 2,663 | 3.46875 | 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 ejercicioFilosofos;
/**
*
* @author daniel.ignacio.dipas
*/
public class CenaFilosofos {
final static int FILOSOFOS_NUMERO = 10;
public static void main(String[] args){
//Supongamos que tenemos 10 filosofos
final Filosofo[] filosofos = new Filosofo[FILOSOFOS_NUMERO];
//Cada filósofo tendrá un tenedor a cada lado (Que se puede comer perfectamente con uno, pero supongamos que necesitan 2 para proceder xD). Se declara el array y se inicializa.
Object[] tenedores = new Object[FILOSOFOS_NUMERO];
for (int i = 0; i < FILOSOFOS_NUMERO; i++) {
tenedores[i] = new Object();
}
//Recorremos los filósofos para ponerles los tenedores a cada lado
for (int i = 0; i < FILOSOFOS_NUMERO; i++) {
Object tenedorIzquierda = tenedores[i];
Object tenedorDerecha;
/*Cuando el tenedor de la izquierda sea el ultimo, el tenedor de la derecha tiene que ser el de la izquierda del primer filósofo*/
if(i==(FILOSOFOS_NUMERO-1))
tenedorDerecha = tenedores[0];
else
tenedorDerecha = tenedores[i + 1];
//Este es el punto crítico de la aplicación. Supongamos que cada Thread (Filósofo) coge el tenedor de la izquierda
//Como todos los filósofos cogen el tenedor a su izquierda, y necesitan dos para comer, al buscar el de la derecha se encuentra que ya está "reservado" por otro filósofo
//RESULTADO: Todos mueren de hambre, a filosofar al cementerio
filosofos[i] = new Filosofo(tenedorIzquierda, tenedorDerecha, i);
/*La solución en este caso pasa por hacer que el primer filósofo en vez de buscar el primer tenedor a la izquierda, lo busque a la derecha*/
/*De esta manera la aplicación se desbloquea, siempre habrá alguien con dos tenedores disponibles para comer, no se produce el deadlock*/
/*RESULTADO: Hay chapa para rato*/
/*
if(i==0)
filosofos[i] = new Filosofo(tenedorDerecha, tenedorIzquierda, i);
else
filosofos[i] = new Filosofo(tenedorIzquierda, tenedorDerecha, i);
*/
Thread t = new Thread(filosofos[i]);
t.start();
}
}
}
| true |
9dccb35c098183d8e77595d099d8db89439d769d | Java | OtusTeam/Spring | /2021-11/spring-13/spring-data-keyvalue-class-work/spring-data-keyvalue-solution/src/main/java/ru/otus/spring/repostory/EmailRepositoryImpl.java | UTF-8 | 708 | 2.28125 | 2 | [] | no_license | package ru.otus.spring.repostory;
import org.springframework.data.keyvalue.core.KeyValueOperations;
import org.springframework.stereotype.Repository;
import ru.otus.spring.domain.Email;
import java.util.List;
@Repository
public class EmailRepositoryImpl implements EmailRepository {
final private KeyValueOperations keyValueTemplate;
public EmailRepositoryImpl( KeyValueOperations keyValueTemplate ) {
this.keyValueTemplate = keyValueTemplate;
}
@Override
public List<Email> findAll() {
return (List<Email>) keyValueTemplate.findAll( Email.class );
}
@Override
public Email save( Email email ) {
return keyValueTemplate.insert( email );
}
}
| true |
342f8f26c84628cdbf373b505878507e794a895b | Java | juyeong-repo/study-Java | /JavaTest/src/custom/AnnotationUse2.java | UTF-8 | 667 | 2.3125 | 2 | [] | no_license | package custom;
public class AnnotationUse2 {
@InsertIntData(data = 40)
private int x;
@InsertIntData(data = 25)
private int y;
private int noUseAnno;
public AnnotationUse2() {
this.x=-1;
this.y=-1;
this.noUseAnno= -1;
}
@Override
public String toString() {
return "AnnotationUse2 [x=" + x + ", y=" + y + ", noUseAnno=" + noUseAnno + "]";
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getNoUseAnno() {
return noUseAnno;
}
public void setNoUseAnno(int noUseAnno) {
this.noUseAnno = noUseAnno;
}
}
| true |
a5ec4d1fe0ccd37fbb16e1e7755666b5e951ac7f | Java | heqinghqocsh/Android_Animation | /app/src/main/java/com/example/heqing/animation/zooming/ZoomingActivity.java | UTF-8 | 6,303 | 2.359375 | 2 | [] | no_license | package com.example.heqing.animation.zooming;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import com.example.heqing.animation.R;
/**
* Created by HeQing on 2017/8/5 0005.
*/
public class ZoomingActivity extends AppCompatActivity {
private Animator mCurrentAnimator;
private int mShortAnimationDuration;
private View thumbView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zooming_layout);
thumbView = findViewById(R.id.thumb_button_1);
mShortAnimationDuration = getResources().getInteger(android.R.integer.config_shortAnimTime);
thumbView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
zoomImgFromThumb(thumbView, R.drawable.demo);
}
});
}
private void zoomImgFromThumb(final View thumbView, int imgResId) {
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}
final ImageView expandedImageView = (ImageView) findViewById(R.id.expanded_image);
expandedImageView.setImageResource(imgResId);
final Rect startBounds = new Rect();
final Rect finalBounds = new Rect();
final Point globalOffset = new Point();
thumbView.getGlobalVisibleRect(startBounds);
findViewById(R.id.container).getGlobalVisibleRect(finalBounds, globalOffset);
startBounds.offset(-globalOffset.x, -globalOffset.y);
finalBounds.offset(-globalOffset.x, -globalOffset.y);
float startScale;
if (finalBounds.width() / finalBounds.height() >
startBounds.width() / startBounds.height()) {
// Extend start bounds horizontally
startScale = startBounds.height() / finalBounds.height();
float startWidth = startScale * finalBounds.width();
float deltaWidth = (startWidth - startBounds.width()) / 2;
startBounds.left -= deltaWidth;
startBounds.right += deltaWidth;
} else {
// Extend start bounds vertically
startScale = (float) startBounds.width() / finalBounds.width();
float startHeight = startScale * finalBounds.height();
float deltaHeight = (startHeight - startBounds.height()) / 2;
startBounds.top -= deltaHeight;
startBounds.bottom += deltaHeight;
}
thumbView.setAlpha(0f);
expandedImageView.setVisibility(View.VISIBLE);
// Set the pivot point for SCALE_X and SCALE_Y transformations
// to the top-left corner of the zoomed-in view (the default
// is the center of the view).
expandedImageView.setPivotX(0f);
expandedImageView.setPivotY(0f);
// Construct and run the parallel animation of the four translation and
// scale properties (X, Y, SCALE_X, and SCALE_Y).
AnimatorSet set = new AnimatorSet();
set.play(ObjectAnimator.ofFloat(expandedImageView, View.X, startBounds.left, finalBounds.left))
.with(ObjectAnimator.ofFloat(expandedImageView, View.Y, startBounds.top, finalBounds.top))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X, startScale, 1f))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y, startScale, 1f));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mCurrentAnimator = null;
}
@Override
public void onAnimationCancel(Animator animation) {
mCurrentAnimator = null;
}
});
set.start();
mCurrentAnimator = set;
// Upon clicking the zoomed-in image, it should zoom back down
// to the original bounds and show the thumbnail instead of
// the expanded image.
final float startScaleFinal = startScale;
expandedImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}
// Animate the four positioning/sizing properties in parallel,
// back to their original values.
AnimatorSet set = new AnimatorSet();
set.play(ObjectAnimator.ofFloat(expandedImageView, View.X, startBounds.left))
.with(ObjectAnimator.ofFloat(expandedImageView, View.Y, startBounds.top))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X, startScaleFinal))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y, startScaleFinal));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
thumbView.setAlpha(1f);
expandedImageView.setVisibility(View.GONE);
mCurrentAnimator = null;
}
@Override
public void onAnimationCancel(Animator animation) {
thumbView.setAlpha(1f);
expandedImageView.setVisibility(View.GONE);
mCurrentAnimator = null;
}
});
set.start();
mCurrentAnimator = set;
}
});
}
}
| true |
9335c491b17678cf24aa473908a03dbd305d5e95 | Java | kje6445/algorithm2 | /src/WinterBase4/Solution_3142.java | UTF-8 | 866 | 3.078125 | 3 | [] | no_license | package WinterBase4;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Solution_3142 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testCases = Integer.parseInt(br.readLine());
for (int i = 1; i <= testCases; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int unicon; //뿔이 1개
int twincon; //뿔이 2개
twincon = n / 2;
unicon = m - twincon;
int sum = twincon * 2 + unicon;
while (sum != n) {
--twincon;
++unicon;
sum = twincon * 2 + unicon;
}
System.out.println("#" + i + " " + unicon + " " + twincon);
}
}
}
| true |
4b3089c117f03a6d7af92c2e5a33885ee1bcd622 | Java | iva-i/JP23 | /java_learningOOP/src/tasks10/Queue.java | UTF-8 | 1,330 | 3.875 | 4 | [] | no_license | package tasks10;
class Queue {
private int size;
private int[] elements;
private int index = 0;
// constructors
public Queue() {
this(8);
}
public Queue(int size) {
this.size=size;
elements = new int[size];
}
// methods
public int getElement(int i) {
return elements[i];
}
public int getSizeVar() {
return size;
}
/**
* adds v into the queue doubles the size if needed
*
* @param v
*/
public void enqueue(int v) {
if (index == elements.length) {
doubleSize();
size++;
elements[index++] = v;
} else {
elements[index++] = v;
}
}
/**
* removes and returns the element from the queue
*
* @return int
*/
public int dequeue() {
int help = elements[0];
for (int i = 0; i < elements.length - 1; i++) {
elements[i] = elements[i + 1];
}
size--;
return help;
}
/**
* method returns true if the queue is empty
*
* @return bool
*/
public boolean empty() {
return size == 0;
}
/**
* returns the size of the queue
*
* @return int
*/
public int getSize() {
return elements.length;
}
/**
* doubles the size of an array if the last index is full
*/
public void doubleSize() {
int[] help = new int[elements.length * 2];
for (int i = 0; i < elements.length; i++) {
help[i] = elements[i];
}
elements = help;
}
}
| true |
bb2618a2d6a42e7b8f0848913359fbde27d22b9c | Java | remix7/ctyping | /src/main/java/top/cynara/ctyping/service/impl/ExamRecodeServiceImpl.java | UTF-8 | 1,340 | 1.929688 | 2 | [] | no_license | package top.cynara.ctyping.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.cynara.ctyping.entitiy.Exam;
import top.cynara.ctyping.entitiy.ExamRecode;
import top.cynara.ctyping.entitiy.mapper.ExamRecodeMapper;
import top.cynara.ctyping.service.ExamRecodeService;
/**
* @ClassName ExamRecodeServiceImpl
* @Description 测试记录接口实现
* @author Cynara-remix http://cynara.top E-mail remix7@live.cn
* @date 2016年10月21日 下午8:26:44
* @version V1.0
*/
@Service("ExamRecodeService")
public class ExamRecodeServiceImpl implements ExamRecodeService {
@Autowired
private ExamRecodeMapper mapper;
public int insert(ExamRecode examRecode) {
return mapper.insert(examRecode);
}
public void delete(Integer id) {
mapper.delete(id);
}
public void update(ExamRecode examRecode) {
mapper.update(examRecode);
}
public ExamRecode findById(Integer id) {
return mapper.findById(id);
}
public List<ExamRecode> findAll() {
return mapper.findAll();
}
public List<ExamRecode> findByUserId(Integer id) {
return mapper.findByUserId(id);
}
public ExamRecode findByUidAndUdt(Integer uid, String udt) {
return mapper.findByUidAndUdt(uid, udt);
}
}
| true |
e19f879b27897dbf0bc5994b83c3be847ed38c75 | Java | cmason12/CoversionTestApplication | /ConversionTestApplication/src/ConversionTable/ConversionTable.java | UTF-8 | 15,980 | 2.875 | 3 | [] | no_license |
package ConversionTable;
import Models.ModLabel;
import Models.ModTextField;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ConversionTable {
//================== Conversion Methods ========================//
private static String _BinaryToHex(TextField input) {
String returnString = "";
try {
int decimal = Integer.parseInt(input.getText(), 2);
returnString = Integer.toString(decimal, 16);
} catch (Exception e) {
returnString = "#N/A";
}
return returnString;
}
private static String _BinaryToDec(TextField input) {
String returnString = "";
try {
returnString = Integer.parseInt(input.getText(), 2) + "";
} catch (Exception e) {
returnString = "#N/A";
}
return returnString;
}
private static String _BinaryToASCII(TextField input) {
String returnString = "";
try {
int charCode = Integer.parseInt(input.getText(), 2);
returnString = (char) charCode + " ";
} catch (Exception e) {
returnString = "#N/A";
}
return returnString;
}
private static String _HexToBinary(TextField input) {
String returnString = "";
try {
int hex = Integer.parseInt(input.getText(), 16);
returnString = Integer.toString(hex, 2);
} catch (Exception e) {
returnString = "#N/A";
}
return returnString;
}
private static String _HexToDecimal(TextField input) {
String returnString = "";
try {
int hex = Integer.parseInt(input.getText(), 16);
returnString = Integer.toString(hex, 10);
} catch (Exception e) {
returnString = "#N/A";
}
return returnString;
}
private static String _HexToASCII(TextField input) {
String returnString = "";
try {
String bin = Integer.toString(Integer.parseInt(input.getText(), 16), 2);
System.out.println(bin);
int charCode = Integer.parseInt(bin, 2);
returnString = (char) charCode + " ";
} catch (Exception e) {
returnString = "#N/A";
}
return returnString;
}
private static String _DecimalToBinary(TextField input) {
String returnString = "";
try {
int dec = Integer.parseInt(input.getText(), 16);
returnString = Integer.toString(dec, 2);
} catch (Exception e) {
returnString = "#N/A";
}
return returnString;
}
private static String _DecimalToHex(TextField input) {
String returnString = "";
try {
int dec = Integer.parseInt(input.getText(), 10);
returnString = Integer.toString(dec, 16);
} catch (Exception e) {
returnString = "#N/A";
}
return returnString;
}
private static String _DecimalToASCII(TextField input) {
String returnString = "";
try {
String bin = Integer.toString(Integer.parseInt(input.getText(),
10), 2);
System.out.println(bin);
int charCode = Integer.parseInt(bin, 2);
returnString = (char) charCode + " ";
} catch (Exception e) {
returnString = "#N/A";
}
return returnString;
}
//==================<END> Conversion Methods ========================//
//================== Type Check ========================//
private static String _BinaryCheck(ModTextField input, ModTextField cell) {
String returnString = "";
try {
int bin = Integer.parseInt(input.getTextField().getText(), 2);
returnString = input.getTextField().getText() + "";
cell.setBackColor(Color.GREEN);
} catch (Exception e) {
returnString = "#N/A";
cell.setBackColor(Color.RED);
}
return returnString;
}
private static String _HexCheck(ModTextField input, ModTextField cell) {
String returnString = "";
try {
int bin = Integer.parseInt(input.getTextField().getText(), 16);
returnString = input.getTextField().getText() + "";
cell.setBackColor(Color.GREEN);
} catch (Exception e) {
returnString = "#N/A";
cell.setBackColor(Color.RED);
}
return returnString;
}
private static String _DecimalCheck(ModTextField input, ModTextField cell) {
String returnString = "";
try {
int bin = Integer.parseInt(input.getTextField().getText(), 10);
returnString = bin + "";
cell.setBackColor(Color.GREEN);
} catch (Exception e) {
returnString = "#N/A";
cell.setBackColor(Color.RED);
}
return returnString;
}
//==================<END> Type Check ========================//
//================== StageBuilder ========================//
public static Scene getTable(Stage parent) {
Scene scene;
/*
Bieng built row by row
0. Enter
1. Column Headers: Binary, Hex, Dec, ASCII
2. BinaryTo
3. HexTo
4. Dec To
*/
//------------Row0 -------------------------//
HBox enterBox = new HBox();
enterBox.setStyle("-fx-background-color: #"
+ Color.LIGHTGREEN.toString().substring(2,
Color.LIGHTGREEN.toString().length() - 2) + ";");
ModLabel lblEnter = new ModLabel(parent, "Enter Value:");
lblEnter.setFont("Arial", 24);
lblEnter.setFontColor(Color.DARKGREEN);
lblEnter.setMaxWidth(50);
ModTextField txtEnter = new ModTextField(parent);
txtEnter.setWidth(300);
txtEnter.setFont("Arial", 16);
txtEnter.setBorderColor(Color.BLACK);
enterBox.getChildren().addAll(lblEnter.getLabel(),
txtEnter.getTextField());
//------------<END> Row0 -------------------------//
//------------Row1 -------------------------//
HBox row1Box = new HBox();
ModLabel lblSpacer = new ModLabel(parent, " ");
lblSpacer.setFont("Arial", 25);
lblSpacer.setBackColor(Color.DARKGREY);
lblSpacer.setFontColor(Color.DARKGREY);
lblSpacer.setBorderColor(Color.BLACK);
lblSpacer.setMaxWidth(150);
ModLabel lblBin = new ModLabel(parent, " BINARY ");
lblBin.setFont("Arial", 25);
lblBin.setBackColor(Color.CORAL);
lblBin.setFontColor(Color.BLACK);
lblBin.setBorderColor(Color.BLACK);
lblBin.setMaxWidth(150);
ModLabel lblHex = new ModLabel(parent, " HEX ");
lblHex.setFont("Arial", 25);
lblHex.setBackColor(Color.LIGHTGRAY);
lblHex.setFontColor(Color.BLACK);
lblHex.setBorderColor(Color.BLACK);
lblHex.setMaxWidth(150);
ModLabel lblDec = new ModLabel(parent, " DECIMAL");
lblDec.setFont("Arial", 25);
lblDec.setBackColor(Color.CORAL);
lblDec.setFontColor(Color.BLACK);
lblDec.setBorderColor(Color.BLACK);
lblDec.setMaxWidth(150);
ModLabel lblASCII = new ModLabel(parent, " ASCII ");
lblASCII.setFont("Arial", 25);
lblASCII.setBackColor(Color.LIGHTGRAY);
lblASCII.setFontColor(Color.BLACK);
lblASCII.setBorderColor(Color.BLACK);
lblASCII.setMaxWidth(150);
row1Box.getChildren().addAll(lblSpacer.getLabel(), lblBin.getLabel(),
lblHex.getLabel(), lblDec.getLabel(), lblASCII.getLabel());
//------------<END> Row1 -------------------------//
//------------Row2 -------------------------//
HBox row2Box = new HBox();
ModTextField cell_1_1 = new ModTextField(parent);
cell_1_1.setWidth(lblSpacer.getWidth());
cell_1_1.setText("Binary To:");
cell_1_1.setBackColor(Color.CORAL);
cell_1_1.setBorderColor(Color.BLACK);
cell_1_1.setBorderColor(Color.BLACK);
ModTextField cell_1_2 = new ModTextField(parent);
cell_1_2.setWidth(lblBin.getWidth());
cell_1_2.setBorderColor(Color.BLACK);
ModTextField cell_1_3 = new ModTextField(parent);
cell_1_3.setWidth(lblHex.getWidth());
cell_1_3.setBorderColor(Color.BLACK);
ModTextField cell_1_4 = new ModTextField(parent);
cell_1_4.setWidth(lblDec.getWidth());
cell_1_4.setBorderColor(Color.BLACK);
ModTextField cell_1_5 = new ModTextField(parent);
cell_1_5.setWidth(lblASCII.getWidth());
cell_1_5.setBorderColor(Color.BLACK);
row2Box.getChildren().addAll(cell_1_1.getTextField(),
cell_1_2.getTextField(), cell_1_3.getTextField(),
cell_1_4.getTextField(), cell_1_5.getTextField());
//------------<END> Row2 -------------------------//
//------------Row3 -------------------------//
HBox row3Box = new HBox();
ModTextField cell_2_1 = new ModTextField(parent);
cell_2_1.setWidth(lblSpacer.getWidth());
cell_2_1.setBorderColor(Color.BLACK);
cell_2_1.setText("Hex To:");
cell_2_1.setBackColor(Color.LIGHTGRAY);
cell_2_1.setBorderColor(Color.BLACK);
ModTextField cell_2_2 = new ModTextField(parent);
cell_2_2.setWidth(lblBin.getWidth());
cell_2_2.setBorderColor(Color.BLACK);
ModTextField cell_2_3 = new ModTextField(parent);
cell_2_3.setWidth(lblHex.getWidth());
cell_2_3.setBorderColor(Color.BLACK);
ModTextField cell_2_4 = new ModTextField(parent);
cell_2_4.setWidth(lblDec.getWidth());
ModTextField cell_2_5 = new ModTextField(parent);
cell_2_4.setBorderColor(Color.BLACK);
cell_2_5.setWidth(lblASCII.getWidth());
cell_2_5.setBorderColor(Color.BLACK);
row3Box.getChildren().addAll(cell_2_1.getTextField(),
cell_2_2.getTextField(), cell_2_3.getTextField(),
cell_2_4.getTextField(), cell_2_5.getTextField());
//------------<END> Row3 -------------------------//
//------------Row4 -------------------------//
HBox row4Box = new HBox();
ModTextField cell_3_1 = new ModTextField(parent);
cell_3_1.setWidth(lblSpacer.getWidth());
cell_3_1.setText("Decimal To:");
cell_3_1.setBackColor(Color.CORAL);
cell_3_1.setBorderColor(Color.BLACK);
ModTextField cell_3_2 = new ModTextField(parent);
cell_3_2.setWidth(lblBin.getWidth());
cell_3_2.setBorderColor(Color.BLACK);
ModTextField cell_3_3 = new ModTextField(parent);
cell_3_3.setWidth(lblHex.getWidth());
cell_3_3.setBorderColor(Color.BLACK);
ModTextField cell_3_4 = new ModTextField(parent);
cell_3_4.setWidth(lblDec.getWidth());
cell_3_4.setBorderColor(Color.BLACK);
ModTextField cell_3_5 = new ModTextField(parent);
cell_3_5.setWidth(lblASCII.getWidth());
cell_3_5.setBorderColor(Color.BLACK);
row4Box.getChildren().addAll(cell_3_1.getTextField(),
cell_3_2.getTextField(), cell_3_3.getTextField(),
cell_3_4.getTextField(), cell_3_5.getTextField());
//------------<END> Row4 -------------------------//
//------------Row5 -------------------------//
HBox row5Box = new HBox();
ModTextField cell_4_1 = new ModTextField(parent);
cell_4_1.setWidth(lblSpacer.getWidth());
cell_4_1.setText("ASCII To:");
cell_4_1.setBackColor(Color.LIGHTGRAY);
cell_4_1.setBorderColor(Color.BLACK);
ModTextField cell_4_2 = new ModTextField(parent);
cell_4_2.setWidth(lblBin.getWidth());
ModTextField cell_4_3 = new ModTextField(parent);
cell_4_3.setWidth(lblHex.getWidth());
ModTextField cell_4_4 = new ModTextField(parent);
cell_4_4.setWidth(lblDec.getWidth());
ModTextField cell_4_5 = new ModTextField(parent);
cell_4_5.setWidth(lblASCII.getWidth());
cell_4_5.getTextField().setDisable(true);
row5Box.getChildren().addAll(cell_4_1.getTextField(),
cell_4_2.getTextField(), cell_4_3.getTextField(),
cell_4_4.getTextField(), cell_4_5.getTextField());
//------------<END> Row5 -------------------------//
//Scene Assembly
VBox tableBox = new VBox();
tableBox.getChildren().addAll(enterBox, row1Box, row2Box,
row3Box, row4Box);
Pane root = new Pane();
root.getChildren().addAll(tableBox);
root.setStyle("-fx-background-color: #"
+ Color.LIGHTBLUE.toString().substring(2,
Color.LIGHTBLUE.toString().length() - 2) + ";");
scene = new Scene(root, 650, 250);
tableBox.setTranslateY(+45);
//Listeners and Event Handlers
parent.heightProperty().addListener(e -> {
});
parent.widthProperty().addListener(e -> {
cell_1_1.setWidth(lblSpacer.getWidth());
cell_1_2.setWidth(lblBin.getWidth());
cell_1_3.setWidth(lblHex.getWidth());
cell_1_4.setWidth(lblDec.getWidth());
cell_1_5.setWidth(lblASCII.getWidth());
});
txtEnter.getTextField().setOnKeyReleased((KeyEvent event) -> {
System.out.println("Here");
//BinaryToHex
cell_1_3.getTextField().setText(
_BinaryToHex(txtEnter.getTextField()));
//BinaryToDec
cell_1_4.getTextField().setText(
_BinaryToDec(txtEnter.getTextField()));
//BinaryToASCII
cell_1_5.getTextField().setText(
_BinaryToASCII(txtEnter.getTextField()));
//HexToBinary
cell_2_2.getTextField().setText(
_HexToBinary(txtEnter.getTextField()));
//HexToDecimal
cell_2_4.getTextField().setText(
_HexToDecimal(txtEnter.getTextField()));
//HexToASCII
cell_2_5.getTextField().setText(
_HexToASCII(txtEnter.getTextField()));
//DecimalToBinary
cell_3_2.getTextField().setText(
_DecimalToBinary(txtEnter.getTextField()));
//DecimalToHex
cell_3_3.getTextField().setText(
_DecimalToHex(txtEnter.getTextField()));
//DecimalToASCII
cell_3_5.getTextField().setText(
_DecimalToASCII(txtEnter.getTextField()));
//BinaryCheck
cell_1_2.getTextField().setText(
_BinaryCheck(txtEnter, cell_1_2));
//HexCheck
cell_2_3.getTextField().setText(
_HexCheck(txtEnter, cell_2_3));
//DecimalCheck
cell_3_4.getTextField().setText(
_DecimalCheck(txtEnter, cell_3_4));
});
return scene;
}
//==================<End> StageBuilder ========================//
}
| true |
da7b1c97764eddbdff550f3bd6a534f0a2833297 | Java | Azedine-bou/Jenkins-today | /Java_Grundlagen_Kap_01/src/BeginnProgramming/Ubung_kap1.java | UTF-8 | 1,613 | 3.546875 | 4 | [] | no_license | package BeginnProgramming;
public class Ubung_kap1 {
public static void main(String[] args) {
int [] tag = new int [14];
int [] temp = {12,14,9,25,15,16,15,15,11,8,13,13,15,12};
//Ausgabe von Arrays tagen
System.out.print("Tagen \t \t:");
for(int i = 1;i <tag.length;i++) {
tag[i]=i;
System.out.print(" \t"+tag[i]);
}
System.out.println();
int sum =0;
//Ausgabe von Arrays temperatur
System.out.print("Wettervorhesage :");
for(int i = 0;i <temp.length;i++) {
System.out.print("\t"+temp[i]);
sum += temp[i];
}
System.out.println();
double mittel = sum/temp.length;
System.out.println("mittel von array gleich =" +mittel);
int min = temp[0];
int max = temp[0];
for(int i = 0;i <temp.length;i++) {
if (min>temp[i]) {
min =temp[i];
}
}
System.out.println("min temp \t :" + min);
for(int i = 0;i <temp.length;i++) {
if (max<temp[i]) {
max =temp[i];
}
}
int maxTempDiff = 0;
int foundDay = 0;
int newMaxDiff = 0;
for (int i = 0; i < temp.length; i++) {
if ((i + 1) < temp.length) {
if (temp[i] < temp[i + 1]) {
newMaxDiff = temp[i + 1] - temp[i];
}
if (temp[i] >= temp[i + 1]) {
newMaxDiff = temp[i] - temp[i + 1];
}
if (maxTempDiff < newMaxDiff) {
maxTempDiff = newMaxDiff;
foundDay = i;
}
}
}
if (maxTempDiff != 0) {
System.out.println("Maximale Temperatur unterschied: " + maxTempDiff + " von Tag " + (foundDay + 1) + " zu Tag " + (foundDay + 2));
} else {
System.out.println("Alle Temperaturen sind gleich");
}
}
}
| true |
b8ac79e321d04d3d2c404183a30396fdbc23d6c0 | Java | lu7025199/JDatabase | /app/src/main/java/com/jowney/database/bean/Student.java | UTF-8 | 2,186 | 2.3125 | 2 | [] | no_license | package com.jowney.database.bean;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Index;
/**
* Creator: Jowney (~._.~)
* Date: 2018/5/13/21:23
* Description:
*/
@Entity
public class Student {
@Id(autoincrement = true)
private Long Id;
private Long teacherId;
private String name;
private Integer age;
private String department;
private String gender;
@Generated(hash = 1395859517)
public Student(Long Id, Long teacherId, String name, Integer age, String department, String gender) {
this.Id = Id;
this.teacherId = teacherId;
this.name = name;
this.age = age;
this.department = department;
this.gender = gender;
}
@Generated(hash = 1556870573)
public Student() {
}
@Override
public String toString() {
return "ID:" + Id + " TeacherId:"+teacherId+" name:" + name +" age:"+age + " department:" + department + " gender:" + gender;
}
/*
@Override
public String toString() {
return "ID:" + Id + " name:" + name + " department:" + department + " gender:" + gender;
}*/
public Long getId() {
return this.Id;
}
public void setId(Long Id) {
this.Id = Id;
}
public Long getTeacherId() {
return this.teacherId;
}
public void setTeacherId(Long teacherId) {
this.teacherId = teacherId;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return this.age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getDepartment() {
return this.department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
| true |
e157366c23854bd36b7b21d3a09480f913f2982b | Java | RikuHei/Hungry-Travellers | /client/app/src/main/java/hungry/travelersapp/hungry_travellers_app/ui/reserve/DatePickerFragment.java | UTF-8 | 2,094 | 2.671875 | 3 | [] | no_license | package hungry.travelersapp.hungry_travellers_app.ui.reserve;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import androidx.fragment.app.DialogFragment;
import java.util.Calendar;
import hungry.travelersapp.hungry_travellers_app.R;
public class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
private int year, month, day;
private Button btn;
private DatePickerFragment.OnDateReceiveCallBack mListener;
private Context context;
public interface OnDateReceiveCallBack {
void onDateReceive(int year, int month, int day);
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
try {
mListener = (DatePickerFragment.OnDateReceiveCallBack) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement OnDateSetListener");
}
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
TextView pickedDate = (TextView) getActivity().findViewById(R.id.datePickerTextView);
String pickedDateData = String.format("Picked date:\n" + "%02d", dayOfMonth) + "." + String.format("%02d", month + 1) + "." + String.format("%02d", year);
pickedDate.setText(pickedDateData);
mListener.onDateReceive(year, month, dayOfMonth);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
}
| true |
75704cdf7f987f62909be74bb1d0cb3a0dcb64c1 | Java | illay1994/movie-info-backend | /movie-info-persistence/src/test/java/org/lnu/is/dao/dao/DefaultDaoTest.java | UTF-8 | 3,644 | 2.421875 | 2 | [] | no_license | package org.lnu.is.dao.dao;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.lnu.is.dao.builder.QueryBuilder;
import org.lnu.is.dao.persistence.PersistenceManager;
import org.lnu.is.domain.film.Film;
import org.lnu.is.pagination.MultiplePagedQuerySearch;
import org.lnu.is.pagination.MultiplePagedSearch;
import org.lnu.is.pagination.PagedResult;
import org.lnu.is.queries.Query;
import org.mockito.InjectMocks;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class DefaultDaoTest {
@Mock
private PersistenceManager<Film, Long> persistenceManager;
@Mock
private QueryBuilder<Film> queryBuilder;
@InjectMocks
private DefaultDao<Film, Long> unit;
@Before
public void setup() {
unit.setEntityClass(Film.class);
}
@Test
public void testFindById() throws Exception {
// Given
Long id = 1L;
String name = "name";
Film expected = new Film();
expected.setId(id);
expected.setTitle(name);
// When
when(persistenceManager.findById(Matchers.<Class<Film>>any(), anyLong())).thenReturn(expected);
Film actual = unit.getEntityById(id);
// Then
verify(persistenceManager).findById(Film.class, id);
assertEquals(expected, actual);
}
@Test
public void testSave() throws Exception {
// Given
Long id = 1L;
String name = "name";
Film entity = new Film();
entity.setId(id);
entity.setTitle(name);
// When
unit.save(entity);
// Then
verify(persistenceManager).create(entity);
}
@Test
public void testUpdate() throws Exception {
// Given
Long id = 1L;
String name = "name";
Film entity = new Film();
entity.setId(id);
entity.setTitle(name);
// When
unit.update(entity);
// Then
verify(persistenceManager).update(entity);
}
@Test
public void testDelete() throws Exception {
// Given
Long id = 1L;
String name = "name";
Film entity = new Film();
entity.setId(id);
entity.setTitle(name);
// When
unit.delete(entity);
// Then
verify(persistenceManager).remove(entity);
}
@Test
public void testGetEntities() throws Exception {
// Given
Integer offset = 0;
Integer limit = 20;
Map<String, Object> parameters = Collections.emptyMap();
Class<Film> clazz = Film.class;
Film entity1 = new Film();
MultiplePagedSearch<Film> pagedSearch = new MultiplePagedSearch<Film>(offset, limit, parameters, clazz);
pagedSearch.setEntity(entity1);
long count = 100;
List<Film> entities = Arrays.asList(entity1);
PagedResult<Film> expected = new PagedResult<Film>(offset, limit, count, entities);
String querySql = "query Sql";
Query<Film> queries = new Query<Film>(Film.class, querySql);
MultiplePagedQuerySearch<Film> pagedQuerySearch = new MultiplePagedQuerySearch<Film>(queries, pagedSearch.getOffset(),
pagedSearch.getLimit(), pagedSearch.getParameters(), Film.class);
// When
when(queryBuilder.build(Matchers.<MultiplePagedSearch<Film>>any())).thenReturn(querySql);
when(persistenceManager.search(Matchers.<MultiplePagedQuerySearch<Film>>any())).thenReturn(expected);
PagedResult<Film> actual = unit.getEntities(pagedSearch);
// Then
verify(queryBuilder).build(pagedSearch);
verify(persistenceManager).search(pagedQuerySearch);
assertEquals(expected, actual);
}
}
| true |
5a3da8dc5275613fa89e48761c61bef8bd0b5a27 | Java | GrandmasterShadowMorgue/Feud | /core/src/com/feud/CharacterCreation.java | UTF-8 | 5,272 | 2.375 | 2 | [] | no_license | package com.feud;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
public class CharacterCreation implements Screen {
Feud game;
private SpriteBatch batch;
private Stage stage;
private Table table;
private Texture texture;
public CharacterCreation(Feud reference) {
game = reference;
batch = new SpriteBatch();
/*******************************************************************/
FreeTypeFontGenerator generator = new FreeTypeFontGenerator( //Genereates a Freetype font from a .TFF file
Gdx.files.internal("PARCHM.TTF"));
/*******************************************************************/
/*******************************************************************/
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter(); //Parameters for the freetype font
parameter.size = 60;
parameter.color = Color.valueOf("C0C0C0");
parameter.borderWidth = 3;
/*******************************************************************/
/*******************************************************************/
Pixmap pm = new Pixmap(Gdx.files.internal("cursor.png")); //Custom cursor
Gdx.input.setCursorImage(pm, 0, 0);
pm.dispose();
/*******************************************************************/
/*******************************************************************/
texture = new Texture(Gdx.files.internal("menu_background.jpg"));
/*******************************************************************/
/*******************************************************************/
BitmapFont text = new BitmapFont();
text = generator.generateFont(parameter);
/*******************************************************************/
/*******************************************************************/
stage = new Stage();
table = new Table();
/*******************************************************************/
/*******************************************************************/
Skin skin = new Skin();
TextureAtlas buttonAtlas = new TextureAtlas(Gdx.files.internal("button.pack"));
skin.addRegions(buttonAtlas);
/*******************************************************************/
/*******************************************************************/
TextButton.TextButtonStyle textButtonStyle = new TextButtonStyle();
textButtonStyle.font = text;
textButtonStyle.up = skin.getDrawable("stone_button");
textButtonStyle.down = skin.getDrawable("stone_button_pressed");
textButtonStyle.checked = skin.getDrawable("stone_button");
/*******************************************************************/
TextField.TextFieldStyle textFieldStyle = new TextFieldStyle();
textFieldStyle.font = text;
textFieldStyle.fontColor = Color.valueOf("C0C0C0");
/*******************************************************************/
TextField textfield = new TextField("", textFieldStyle);
/*******************************************************************/
/*******************************************************************/
Label.LabelStyle style = new LabelStyle(text,Color.valueOf("C0C0C0"));
Label label = new Label("Enter your name",style);
label.setAlignment(Align.center);
/*******************************************************************/
/*******************************************************************/
table.add(label);
table.add(textfield).row();
table.center();
stage.addActor(table);
/*******************************************************************/
}
@Override
public void show() {
Gdx.input.setInputProcessor(stage);
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(1,1,1,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(texture, 0,0);
batch.end();
stage.act();
stage.draw();
}
@Override
public void resize(int width, int height) {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
stage.dispose();
batch.dispose();
texture.dispose();
game.musicmanager.dispose();
}
@Override
public void dispose() {
}
}
| true |
3e40a3b63b8780bc1516d8313b4cc7d0872c405f | Java | josuegue/ArrayList_Newcomission | /Collection/src/ClassCollection.java | UTF-8 | 502 | 1.703125 | 2 | [] | no_license |
import com.Comisiones.ClassNewcomisiones;
/*
* 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.
*/
/**
*
* @author USUARIOTC
*/
public class ClassCollection {
public static void main(String[] args) {
ClassNewcomisiones comision = new ClassNewcomisiones();
comision.menu();
// TODO code application logic here
}
}
| true |
0cbd828fc2849f00823bf80ac0d97ac6823de1f2 | Java | vithushan19/Yahoo-Fantasy-Football-API-Library | /src/test/java/MatchupDemo.java | UTF-8 | 3,484 | 2.25 | 2 | [] | no_license | import com.yahoo.engine.YahooFantasyEngine;
import com.yahoo.objects.api.YahooApiInfo;
import com.yahoo.objects.league.League;
import com.yahoo.objects.league.LeagueSettings;
import com.yahoo.objects.league.transactions.LeagueTransaction;
import com.yahoo.objects.league.transactions.TransactionPlayersList;
import com.yahoo.objects.players.Player;
import com.yahoo.objects.team.*;
import com.yahoo.services.LeagueService;
import com.yahoo.services.PlayerService;
import com.yahoo.services.TeamService;
import com.yahoo.services.YahooServiceFactory;
import com.yahoo.services.enums.ServiceType;
import com.yahoo.utils.Oceans;
import com.yahoo.utils.OceansMatchup;
import com.yahoo.utils.oauth.OAuthConnection;
import java.awt.*;
import java.io.*;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by cedric on 10/3/14.
*/
public class MatchupDemo
{
public static void main( String[] args )
{
YahooApiInfo info =
new YahooApiInfo("dj0yJmk9SG1OeGxuQUhCdWxKJmQ9WVdrOVdGWkJOSEJDTldFbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD1lNw--",
"8e6b6c1e5f2d1f4e3b4fd74d428ae38c7a02a8e9");
YahooFantasyEngine engine = new YahooFantasyEngine(info);
OAuthConnection oAuthConn = YahooFantasyEngine.getoAuthConn();
YahooServiceFactory factory = YahooFantasyEngine.getServiceFactory();
String requestUrl = oAuthConn.retrieveAuthorizationUrl();
try {
if (!oAuthConn.connect()) {
URI uri = new URI(requestUrl);
Desktop desktop = Desktop.getDesktop();
desktop.browse(uri);
System.out.println("Please type in verifier code:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String verifier = br.readLine();
oAuthConn.retrieveAccessToken(verifier);
}
if (oAuthConn.isAuthorized()) {
// Create services that talk to Yahoo
LeagueService gameService = (LeagueService) factory.getService(ServiceType.LEAGUE);
TeamService teamService = (TeamService) factory.getService(ServiceType.TEAM);
Oceans oceans = new Oceans(gameService, teamService);
List<Team> teams = oceans.getTeams();
Map<Team, OceansMatchup> result = new HashMap<Team, OceansMatchup>(); //Result object of matchup data
for (Team team : teams) {
OceansMatchup oceansMatchup = oceans.createHistoricalMatchup(team);
result.put(team, oceansMatchup);
}
// write result to text
FileOutputStream fout = new FileOutputStream("/Users/vithushan/Documents/code/foo.txt");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(result);
// read text to result object
FileInputStream fit = new FileInputStream("/Users/vithushan/Documents/code/foo.txt");
ObjectInputStream ois = new ObjectInputStream(fit);
Map<Team, OceansMatchup> object = (Map<Team, OceansMatchup>) ois.readObject();
System.out.println("DONE");
}
}
catch (Exception e)
{
System.out.println("Problem with getting accessing url.");
System.err.println(e);
}
}
}
| true |
93be0a8040787061c63a881c3db3eac15b8a1b60 | Java | misterGuo308/spring-boot-intergration | /speing-boot-file-manage/src/main/java/com/example/speingbootfilemanage/common/enums/ResultEnum.java | UTF-8 | 494 | 2.09375 | 2 | [] | no_license | package com.example.speingbootfilemanage.common.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @author guoyou
* @date 2020/1/15 22:17
*/
@Getter
@AllArgsConstructor
public enum ResultEnum {
/**
* 返回结果枚举
*/
SUCCESS_UPLOAD("200", "文件上传成功"),
SYSTEM_FAIL("500", "系统错误"),
PARAMENT_FAIL("400", "参数错误"),
FAIL_UPLOAD("601", "文件操作失败");
private String code;
private String message;
}
| true |
cdfe2f8079912ea6551e1dd737c0f8f2db4f6612 | Java | Khal-Shah/Java_And_Data_Structure_Exercises | /Ch17_Binary_IO/ch17_exercises/ex14_encrypt_file/Encode_File.java | UTF-8 | 1,332 | 3.921875 | 4 | [] | no_license | package ch17_exercises.ex14_encrypt_file;
import java.io.*;
/**
* Chapter 17 (Binary I/O) - Exercise 14:
*
* (Encrypt files) Encode the file by adding 10 to every byte in the file.
* Write a gram that prompts the user to enter an input file name and an output file name
* and saves the encrypted version of the input file to the output file.
*
* @author Khaled
*/
public class Encode_File
{
public static void main(String[] args) throws IOException
{
//encrypt the last-names file
try(FileInputStream fileIn = new FileInputStream("Ch17_Binary_IO/ch17_exercises/ex14_encrypt_file/last-names.txt");
FileOutputStream fileOut = new FileOutputStream("Ch17_Binary_IO/ch17_exercises/ex14_encrypt_file/last-names-encrypted.txt");
BufferedInputStream bufferedIn = new BufferedInputStream(fileIn);
BufferedOutputStream bufferedOut = new BufferedOutputStream(fileOut))
{
System.out.println("Original file size: " + fileIn.available());
int fileOutSize = 0;
int value;
while((value = bufferedIn.read()) != -1)
{
bufferedOut.write((byte) (value + 10));
fileOutSize++;
}
System.out.println("Encrypted file size: " + fileOutSize);
}
}
}
| true |
bc5fb096f89da3a70f7ed44888d71553722dca60 | Java | okanwar/Word-Counter | /ChangeStyle.java | UTF-8 | 1,970 | 4.125 | 4 | [] | no_license | /**
* Title: ChangeStyle
*
* Authors: Chris Eardensohn (ceardensohn@sandiego.edu),
* Om Kanwar (okanwar@sandiego.edu)
*
* Date: 9/29/17
*
* Description: To read from a text file and change the position of the curly braces
* in the file.
*/
import java.util.*;
import java.io.*;
public class ChangeStyle
{
public static void main(String[] args)
throws Exception
{
System.out.println("Enter Filename: ");
// Prompt user for a file name and get file name from console
Scanner sc = new Scanner(System.in);
String filename = new String(sc.nextLine());
File file = new File(filename);
while (file.exists() == false)
//loop to ensure a valid file name is entered
{
System.out.println("Bad file name");
filename = sc.next();
file = new File(filename);
}
sc.close();
ArrayList<String> obj = new ArrayList<String>();
//create array list to store read in lines from file
String line1 = "";
String line2 = "";
Scanner scfile = new Scanner(file);
line1 = scfile.nextLine();
//reading from the file one line at a time
while (scfile.hasNextLine() == true)
//loop to read in lines until no lines left to read from file
{
line2 = scfile.nextLine();
if (line2.length() > 0 && line2.charAt(line2.length() -1) == '{')
//check to see if there is a '{' by itself on a line and
//moving the curly brace to the previous line if true
{
obj.add(line1.concat(" {"));
line1 = scfile.nextLine();
}
else
//adds lines to array list if they don't have a lone curly brace
{
obj.add(line1);
line1 = line2;
}
}
obj.add(line1);
//writes array list back into same file with curly braces in the
//correct locationx
PrintWriter output = new PrintWriter(filename);
for(int i = 0; i < obj.size(); i++)
{
output.println(obj.get(i));
}
output.close();
}
} | true |
809b851b3b58985da2b9f4c70bcbc9909eaa835f | Java | Mubir/car-supply-chain-inventory-service | /src/main/java/com/mubir/inventory/web/mapper/CarInventoryMapper.java | UTF-8 | 393 | 1.757813 | 2 | [] | no_license | package com.mubir.inventory.web.mapper;
import com.mubir.inventory.domain.CarInventory;
import com.mubir.inventory.web.model.CarInventoryDto;
import org.mapstruct.Mapper;
@Mapper(uses = {DateMapper.class})
public interface CarInventoryMapper {
CarInventoryDto carInventoryToCarInventoryDot(CarInventory carInventory);
CarInventory carInventoryDtoToCarDto(CarInventoryDto carInventoryDto);
}
| true |
4390d8c419f35ead22c9415a97e5a2f833c61903 | Java | die-fernandez/campsite-reservations | /src/test/java/com/pacific/volcano/campsitereservations/CampsiteReservationsValidationTests.java | UTF-8 | 10,631 | 2.015625 | 2 | [] | no_license | package com.pacific.volcano.campsitereservations;
import com.pacific.volcano.campsitereservations.api.ErrorResponse;
import com.pacific.volcano.campsitereservations.api.ReservationRequest;
import com.pacific.volcano.campsitereservations.api.ReservationResponse;
import io.restassured.http.ContentType;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import io.restassured.module.mockmvc.config.RestAssuredMockMvcConfig;
import io.restassured.module.mockmvc.response.ValidatableMockMvcResponse;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.test.web.servlet.MockMvc;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import static io.restassured.config.EncoderConfig.encoderConfig;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.is;
@SpringBootTest
@AutoConfigureMockMvc
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class CampsiteReservationsValidationTests {
@Autowired
private MockMvc mockMvc;
@BeforeAll
public void setup() {
RestAssuredMockMvc.config = RestAssuredMockMvcConfig.newConfig()
.encoderConfig(encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false));
}
@Test
public void testFindAvailability_statusOk() {
ArrayList<String> availableDates = given().mockMvc(mockMvc).log().all()
.queryParam("from", LocalDate.now().plusDays(1).format(DateTimeFormatter.ISO_DATE))
.queryParam("to", LocalDate.now().plusDays(4).format(DateTimeFormatter.ISO_DATE))
.when()
.get("/availability")
.then()
.statusCode(HttpStatus.OK.value())
.extract().path("availableDates");
assertThat(availableDates.size()).isEqualTo(4);
}
@Test
public void testFindAvailability_default_statusOk() {
ArrayList<String> availableDates = given().mockMvc(mockMvc).log().all()
.when()
.get("/availability")
.then()
.statusCode(HttpStatus.OK.value())
.extract().path("availableDates");
assertThat(availableDates).isNotEmpty();
}
//testing reservation constraints
@Test
public void testReservation_datesOutOfBounds() {
ReservationRequest testReservationRequest = ReservationRequest.builder()
.arrivalDate(LocalDate.now().plusDays(32))
.departureDate(LocalDate.now().plusDays(34))
.email("testEmail")
.fullname("testName").build();
ValidatableMockMvcResponse validatableResponse = given().mockMvc(mockMvc)
.accept(ContentType.JSON).log().all()
.contentType(ContentType.JSON)
.body(testReservationRequest)
.when()
.post("/reservations")
.then()
.statusCode(HttpStatus.BAD_REQUEST.value());
validatableResponse.log().all();
ErrorResponse errorResponse = validatableResponse.extract().body().as(ErrorResponse.class);
assertThat(errorResponse.getErrors()).isNotEmpty();
assertThat(errorResponse.getErrors())
.contains(
"reservationRequest: Maximum anticipation for a reservation cannot be more than 30 days ahead of arrival");
}
@Test
public void testReservation_minAnticipation() {
ReservationRequest testReservationRequest = ReservationRequest.builder()
.arrivalDate(LocalDate.now())
.departureDate(LocalDate.now().plusDays(2))
.email("testEmail")
.fullname("testName").build();
ValidatableMockMvcResponse validatableResponse = given().mockMvc(mockMvc)
.accept(ContentType.JSON).log().all()
.contentType(ContentType.JSON)
.body(testReservationRequest)
.when()
.post("/reservations")
.then()
.statusCode(HttpStatus.BAD_REQUEST.value());
validatableResponse.log().all();
ErrorResponse errorResponse = validatableResponse.extract().body().as(ErrorResponse.class);
assertThat(errorResponse.getErrors()).isNotEmpty();
assertThat(errorResponse.getErrors())
.contains("reservationRequest: Minimum anticipation for a reservation is 1 day before arrival");
}
@Test
public void testReservation_maxAnticipation() {
ReservationRequest testReservationRequest = ReservationRequest.builder()
.arrivalDate(LocalDate.now().plusMonths(1))
.departureDate(LocalDate.now().plusMonths(1).plusDays(2))
.email("testEmail")
.fullname("testName").build();
ValidatableMockMvcResponse validatableResponse = given().mockMvc(mockMvc)
.accept(ContentType.JSON).log().all()
.contentType(ContentType.JSON)
.body(testReservationRequest)
.when()
.post("/reservations")
.then()
.statusCode(HttpStatus.BAD_REQUEST.value());
validatableResponse.log().all();
ErrorResponse errorResponse = validatableResponse.extract().body().as(ErrorResponse.class);
assertThat(errorResponse.getErrors()).isNotEmpty();
assertThat(errorResponse.getErrors())
.contains(
"reservationRequest: Maximum anticipation for a reservation cannot be more than 30 days ahead of arrival");
}
@Test
public void testReservation_minStay() {
ReservationRequest testReservationRequest = ReservationRequest.builder()
.arrivalDate(LocalDate.now().plusDays(2))
.departureDate(LocalDate.now().plusDays(2))
.email("testEmail")
.fullname("testName").build();
ValidatableMockMvcResponse validatableResponse = given().mockMvc(mockMvc)
.accept(ContentType.JSON).log().all()
.contentType(ContentType.JSON)
.body(testReservationRequest)
.when()
.post("/reservations")
.then()
.statusCode(HttpStatus.BAD_REQUEST.value());
validatableResponse.log().all();
ErrorResponse errorResponse = validatableResponse.extract().body().as(ErrorResponse.class);
assertThat(errorResponse.getErrors()).isNotEmpty();
assertThat(errorResponse.getErrors()).contains("reservationRequest: minimum stay is 1 day");
}
@Test
public void testReservation_maxStay() {
ReservationRequest testReservationRequest = ReservationRequest.builder()
.arrivalDate(LocalDate.now().plusDays(2))
.departureDate(LocalDate.now().plusDays(7))
.email("testEmail")
.fullname("testName").build();
ValidatableMockMvcResponse validatableResponse = given().mockMvc(mockMvc)
.accept(ContentType.JSON).log().all()
.contentType(ContentType.JSON)
.body(testReservationRequest)
.when()
.post("/reservations")
.then()
.statusCode(HttpStatus.BAD_REQUEST.value());
validatableResponse.log().all();
ErrorResponse errorResponse = validatableResponse.extract().body().as(ErrorResponse.class);
assertThat(errorResponse.getErrors()).isNotEmpty();
assertThat(errorResponse.getErrors()).contains("reservationRequest: maximum stay is 3 days");
}
//testing a creation and a cancellation
@Test
public void testReservation_AndAlreadyReserved() {
ReservationRequest testReservationRequest = ReservationRequest.builder()
.arrivalDate(LocalDate.now().plusDays(15)).departureDate(LocalDate.now().plusDays(18))
.email("testEmail").fullname("testName").build();
ValidatableMockMvcResponse response = given().mockMvc(mockMvc)
.accept(ContentType.JSON).log().all()
.contentType(ContentType.JSON)
.body(testReservationRequest)
.when()
.post("/reservations")
.then()
.statusCode(HttpStatus.OK.value());
response.log().all();
ValidatableMockMvcResponse response2 = given().mockMvc(mockMvc)
.accept(ContentType.JSON).log().all()
.contentType(ContentType.JSON)
.body(testReservationRequest)
.when()
.post("/reservations")
.then()
.statusCode(HttpStatus.CONFLICT.value());
ErrorResponse errorResponse = response2.extract().body().as(ErrorResponse.class);
assertThat(errorResponse.getMessage()).contains("No availability for selected dates");
}
//testing a creation and a cancellation
@Test
public void testReservation_AndCancel() {
ReservationRequest testReservationRequest = ReservationRequest.builder()
.arrivalDate(LocalDate.now().plusDays(10)).departureDate(LocalDate.now().plusDays(13))
.email("testEmail").fullname("testName").build();
ValidatableMockMvcResponse response = given().mockMvc(mockMvc)
.accept(ContentType.JSON).log().all()
.contentType(ContentType.JSON)
.body(testReservationRequest)
.when()
.post("/reservations")
.then()
.statusCode(HttpStatus.OK.value());
response.log().all();
ReservationResponse reservationResponse = response.extract().body().as(ReservationResponse.class);
assertThat(reservationResponse.getId()).isNotNull();
given().mockMvc(mockMvc)
.accept(ContentType.JSON).log().all()
.when()
.delete("/reservations/{id}", reservationResponse.getId())
.then()
.statusCode(HttpStatus.OK.value())
.body("active", is(false));
}
}
| true |
cf5a336096b6d657cbea96aa293ad275cc096e89 | Java | programus/j-bots | /eclipse/base/robocode-src/robocode.ui/src/main/java/net/sf/robocode/ui/dialog/ResultsDialog.java | UTF-8 | 4,151 | 2.375 | 2 | [
"Apache-2.0"
] | permissive | /*******************************************************************************
* Copyright (c) 2001-2013 Mathew A. Nelson and Robocode contributors
* 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://robocode.sourceforge.net/license/epl-v10.html
*******************************************************************************/
package net.sf.robocode.ui.dialog;
import net.sf.robocode.battle.BattleResultsTableModel;
import net.sf.robocode.ui.IWindowManager;
import robocode.BattleResults;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
/**
* Dialog to display results (scores) of a battle.
* <p/>
* This class is just a wrapper class used for storing the window position and
* dimension.
*
* @author Mathew A. Nelson (original)
* @author Flemming N. Larsen (contributor)
*/
@SuppressWarnings("serial")
public class ResultsDialog extends BaseScoreDialog {
private JPanel buttonPanel;
private JButton okButton;
private JButton saveButton;
private BattleResultsTableModel tableModel;
private final ButtonEventHandler buttonEventHandler;
public ResultsDialog(IWindowManager manager) {
super(manager, true);
buttonEventHandler = new ButtonEventHandler();
initialize();
addCancelByEscapeKey();
}
public void setup(BattleResults[] results, int numRounds) {
tableModel = new BattleResultsTableModel(results, numRounds);
setTitle(((BattleResultsTableModel) getTableModel()).getTitle());
setResultsData();
table.setPreferredSize(
new Dimension(table.getColumnModel().getTotalColumnWidth(),
table.getModel().getRowCount() * table.getRowHeight()));
table.setPreferredScrollableViewportSize(table.getPreferredSize());
}
private void saveButtonActionPerformed() {
windowManager.showSaveResultsDialog(tableModel);
}
private void okButtonActionPerformed() {
setVisible(false);
}
@Override
protected AbstractTableModel getTableModel() {
return tableModel;
}
@Override
protected JPanel getDialogContentPane() {
if (contentPane == null) {
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.add(getScrollPane(), "Center");
contentPane.add(getButtonPanel(), "South");
}
return contentPane;
}
private JPanel getButtonPanel() {
if (buttonPanel == null) {
buttonPanel = new JPanel();
buttonPanel.setLayout(new BorderLayout());
buttonPanel.add(getOkButton(), "East");
buttonPanel.add(getSaveButton(), "West");
}
return buttonPanel;
}
private JButton getOkButton() {
if (okButton == null) {
okButton = new JButton();
okButton.setText("OK");
okButton.addActionListener(buttonEventHandler);
WindowUtil.setFixedSize(okButton, new Dimension(80, 25));
}
return okButton;
}
private JButton getSaveButton() {
if (saveButton == null) {
saveButton = new JButton();
saveButton.setText("Save");
saveButton.addActionListener(buttonEventHandler);
WindowUtil.setFixedSize(saveButton, new Dimension(80, 25));
}
return saveButton;
}
private void addCancelByEscapeKey() {
String CANCEL_ACTION_KEY = "CANCEL_ACTION_KEY";
int noModifiers = 0;
KeyStroke escapeKey = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, noModifiers, false);
InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
inputMap.put(escapeKey, CANCEL_ACTION_KEY);
AbstractAction cancelAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
okButtonActionPerformed();
}
};
getRootPane().getActionMap().put(CANCEL_ACTION_KEY, cancelAction);
}
private class ButtonEventHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == ResultsDialog.this.getOkButton()) {
okButtonActionPerformed();
} else if (source == ResultsDialog.this.getSaveButton()) {
saveButtonActionPerformed();
}
}
}
}
| true |
2b60b2fff86fc59005a2343b7e94f753d8d16a6d | Java | MarkoMesel/XIWS-TimProj | /AgentMonolithApp/AgentMonolith/src/main/java/com/xiws/agentm/soap/contract/userservice/ObjectFactory.java | UTF-8 | 4,195 | 1.773438 | 2 | [] | no_license | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2020.07.07 at 11:44:13 AM CEST
//
package com.xiws.agentm.soap.contract.userservice;
import javax.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the com.student.soap.contract.userservice package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.student.soap.contract.userservice
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link SoapResponse }
*
*/
public SoapResponse createSoapResponse() {
return new SoapResponse();
}
/**
* Create an instance of {@link StatusType }
*
*/
public StatusType createStatusType() {
return new StatusType();
}
/**
* Create an instance of {@link SoapRegisterRequest }
*
*/
public SoapRegisterRequest createSoapRegisterRequest() {
return new SoapRegisterRequest();
}
/**
* Create an instance of {@link SoapVerifyRequest }
*
*/
public SoapVerifyRequest createSoapVerifyRequest() {
return new SoapVerifyRequest();
}
/**
* Create an instance of {@link SoapLoginRequest }
*
*/
public SoapLoginRequest createSoapLoginRequest() {
return new SoapLoginRequest();
}
/**
* Create an instance of {@link SoapLoginResponse }
*
*/
public SoapLoginResponse createSoapLoginResponse() {
return new SoapLoginResponse();
}
/**
* Create an instance of {@link SoapEditRequest }
*
*/
public SoapEditRequest createSoapEditRequest() {
return new SoapEditRequest();
}
/**
* Create an instance of {@link SoapGetRequest }
*
*/
public SoapGetRequest createSoapGetRequest() {
return new SoapGetRequest();
}
/**
* Create an instance of {@link SoapGetResponse }
*
*/
public SoapGetResponse createSoapGetResponse() {
return new SoapGetResponse();
}
/**
* Create an instance of {@link SoapUsersRequest }
*
*/
public SoapUsersRequest createSoapUsersRequest() {
return new SoapUsersRequest();
}
/**
* Create an instance of {@link SoapUsersResponse }
*
*/
public SoapUsersResponse createSoapUsersResponse() {
return new SoapUsersResponse();
}
/**
* Create an instance of {@link SoapUser }
*
*/
public SoapUser createSoapUser() {
return new SoapUser();
}
/**
* Create an instance of {@link SoapInternalGetUserRequest }
*
*/
public SoapInternalGetUserRequest createSoapInternalGetUserRequest() {
return new SoapInternalGetUserRequest();
}
/**
* Create an instance of {@link SoapBlockUserRequest }
*
*/
public SoapBlockUserRequest createSoapBlockUserRequest() {
return new SoapBlockUserRequest();
}
/**
* Create an instance of {@link SoapActivateUserRequest }
*
*/
public SoapActivateUserRequest createSoapActivateUserRequest() {
return new SoapActivateUserRequest();
}
/**
* Create an instance of {@link SoapDeleteUserRequest }
*
*/
public SoapDeleteUserRequest createSoapDeleteUserRequest() {
return new SoapDeleteUserRequest();
}
}
| true |
e4de17947569c94371821f4e18f4611085a99d7d | Java | brianmarete/Cinephile | /app/src/androidTest/java/com/brianmarete/cinephile/repository/MovieRepositoryTest.java | UTF-8 | 2,218 | 2.109375 | 2 | [] | no_license | package com.brianmarete.cinephile.repository;
import android.arch.core.executor.testing.InstantTaskExecutorRule;
import com.brianmarete.cinephile.data.Resource;
import com.brianmarete.cinephile.data.local.dao.MovieDao;
import com.brianmarete.cinephile.data.local.entity.MovieEntity;
import com.brianmarete.cinephile.data.remote.api.MovieApiService;
import com.brianmarete.cinephile.data.remote.model.MovieApiResponse;
import com.brianmarete.cinephile.data.repository.MovieRepository;
import com.brianmarete.cinephile.util.MockTestUtil;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.List;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.observers.TestObserver;
import static com.brianmarete.cinephile.AppConstants.MOVIES_POPULAR;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MovieRepositoryTest {
@Mock
MovieDao movieDao;
@Mock
MovieApiService movieApiService;
private MovieRepository repository;
@Rule
public InstantTaskExecutorRule instantExecutorRule = new InstantTaskExecutorRule();
@Before
public void init() {
repository = new MovieRepository(movieDao, movieApiService);
}
@Test
public void loadMoviesList() {
Flowable<List<MovieEntity>> loadFromDB = Flowable.empty();
when(movieDao.getMoviesByType(MOVIES_POPULAR))
.thenReturn(loadFromDB);
MovieApiResponse mockResponse = MockTestUtil.mockMovieApiResponse(MOVIES_POPULAR);
when(movieApiService.fetchMoviesByType(MOVIES_POPULAR, 1l))
.thenReturn(Observable.just(mockResponse));
Observable<Resource<List<MovieEntity>>>
data = repository.loadMoviesByType(MOVIES_POPULAR);
verify(movieDao).getMoviesByType(MOVIES_POPULAR);
verify(movieApiService).fetchMoviesByType(MOVIES_POPULAR, 1l);
TestObserver testObserver = new TestObserver();
data.subscribe(testObserver);
testObserver.assertNoErrors();
}
}
| true |
49a6078bc35a7646cd9fcacde2556dad30e5e9a3 | Java | angeldevg/IS_P2_QUICK_SORT | /src/main/java/gt/edu/miumg/sistemas/ingesoftware/p2/QuickSort/QuickSortApplication.java | UTF-8 | 1,066 | 2.4375 | 2 | [] | no_license | package gt.edu.miumg.sistemas.ingesoftware.p2.QuickSort;
import gt.edu.miumg.sistemas.ingesoftware.p2.QuickSort.Services.DataPrinter;
import gt.edu.miumg.sistemas.ingesoftware.p2.QuickSort.Services.IDataPrinter;
import gt.edu.miumg.sistemas.ingesoftware.p2.QuickSort.Services.IQuickSort;
import gt.edu.miumg.sistemas.ingesoftware.p2.QuickSort.Services.QuickSort;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class QuickSortApplication implements CommandLineRunner{
public static void main(String[] args) {
SpringApplication.run(QuickSortApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
IQuickSort quickSort = new QuickSort();
IDataPrinter print = new DataPrinter();
String[] array= {"garcia", "perez", "angel"};
quickSort.quicksort(array, 0, array.length - 1);
print.PrintWords(array);
}
}
| true |
8a6b6b2a7bac73edb4df0fc77488f6e1f8a0ddba | Java | dmitkond/envisor | /src/main/java/dev/dmitkond/envisor/inventory/repository/PartTypeConverter.java | UTF-8 | 772 | 2.6875 | 3 | [] | no_license | package dev.dmitkond.envisor.inventory.repository;
import dev.dmitkond.envisor.inventory.PartType;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter
public class PartTypeConverter implements AttributeConverter<PartType, String> {
@Override
public String convertToDatabaseColumn(PartType partType) {
return switch (partType) {
case PURCHASED -> "P";
case MANUFACTURED -> "M";
};
}
@Override
public PartType convertToEntityAttribute(String s) {
return switch (s) {
case "P" -> PartType.PURCHASED;
case "M" -> PartType.MANUFACTURED;
default -> throw new IllegalArgumentException("Unexpected value: " + s);
};
}
}
| true |
26970a5b5bae06935e1f893c2d6892ca11554379 | Java | pgvalentini/Laboratorio-de-Computacion-I-UTN | /TP_04 - Array Multidimensión/Ej_01.java | UTF-8 | 736 | 3.359375 | 3 | [] | no_license | package TP_4;
import java.util.Scanner;
public class Ej_01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[][] ciudades = new String[4][4];
for(int i=0;i<4;i++){
System.out.println("Ingrese un País y luego tres ciudades");
for(int j=0;j<4;j++){
ciudades[i][j] = sc.nextLine();
}
}
System.out.println("Paises"+"\t"+"Ciudades");
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(ciudades[i][j]+"\t");
}
System.out.println("");
}
System.out.println("");
}
}
| true |
6105ce4bb2d2f7d3022e8643410053472bb87f82 | Java | spoto/ProgrammazioneJava | /compiti/2022-02-02/v2/consegna/it/univr/identifiers/SnakeStyleIdentifier.java | UTF-8 | 773 | 2.765625 | 3 | [] | no_license | package it.univr.identifiers;
//TODO: fate compilare questa classe
public class SnakeStyleIdentifier extends MultiWordIdentifier {
// costruisce un identicatore snake-style le cui parole sono quelle indicate;
// fallisce nelle stesse condizioni del costruttore della superclasse
public SnakeStyleIdentifier(String... words) {
// TODO
}
// come sopra
public SnakeStyleIdentifier(Iterable<String> words) {
// TODO
}
// costruisce un identificatore snake-style le cui parole componenti
// sono la concatenazione delle parole degli ids
public SnakeStyleIdentifier(MultiWordIdentifier... ids) {
// TODO
}
// restituisce un identificatore vowel-style con le stesse parole di this
public VowelStyleIdentifier toVowelStyle() {
// TODO
return null;
}
} | true |
3f408311ad6eb78d1abd653892e9e29fc3301db4 | Java | jcunhasilva/OMS-Play | /customer/app/controllers/Application.java | UTF-8 | 750 | 2.125 | 2 | [
"Apache-2.0"
] | permissive | package controllers;
import java.util.List;
import models.OmsOrder;
import play.*;
import play.data.Form;
import play.db.ebean.Model;
import play.mvc.*;
import views.html.*;
import java.util.List;
import com.avaje.ebean.PagedList;
import static play.libs.Json.toJson;
public class Application extends Controller {
public Result index() {
return ok(index.render("Your new application is ready."));
}
public Result getOrders(int page) {
List<OmsOrder> orders = new Model.Finder(String.class, OmsOrder.class).findPagedList(page, 10).getList();
return ok(toJson(orders));
}
public Result show(long id){
OmsOrder order = OmsOrder.find.byId(id);
return ok(toJson(order));
}
}
| true |
34c1cab40509442dc5c32d9d6e7a8070d31703e1 | Java | MaximeBonnet27/Evaluateur-BOPL | /src/com/aps/parser/Parser.java | UTF-8 | 36,990 | 2.484375 | 2 | [] | no_license | //### This file created by BYACC 1.8(/Java extension 1.15)
//### Java capabilities added 7 Jan 97, Bob Jamison
//### Updated : 27 Nov 97 -- Bob Jamison, Joe Nieten
//### 01 Jan 98 -- Bob Jamison -- fixed generic semantic constructor
//### 01 Jun 99 -- Bob Jamison -- added Runnable support
//### 06 Aug 00 -- Bob Jamison -- made state variables class-global
//### 03 Jan 01 -- Bob Jamison -- improved flags, tracing
//### 16 May 01 -- Bob Jamison -- added custom stack sizing
//### 04 Mar 02 -- Yuval Oren -- improved java performance, added options
//### 14 Mar 02 -- Tomas Hurka -- -d support, static initializer workaround
//### Please send bug reports to tom@hukatronic.cz
//### static char yysccsid[] = "@(#)yaccpar 1.8 (Berkeley) 01/20/90";
package com.aps.parser;
//#line 5 "lexer/bopl.y"
import java.io.*;
import java.util.*;
import com.aps.ast.*;
import com.aps.ast.call.*;
import com.aps.ast.declarations.*;
import com.aps.ast.expressions.*;
import com.aps.ast.instructions.*;
import com.aps.ast.operators.*;
//#line 28 "Parser.java"
public class Parser
{
boolean yydebug; //do I want debug output?
int yynerrs; //number of errors so far
int yyerrflag; //was there an error?
int yychar; //the current working character
//########## MESSAGES ##########
//###############################################################
// method: debug
//###############################################################
void debug(String msg)
{
if (yydebug)
System.out.println(msg);
}
//########## STATE STACK ##########
final static int YYSTACKSIZE = 500; //maximum stack size
int statestk[] = new int[YYSTACKSIZE]; //state stack
int stateptr;
int stateptrmax; //highest index of stackptr
int statemax; //state when highest index reached
//###############################################################
// methods: state stack push,pop,drop,peek
//###############################################################
final void state_push(int state)
{
try {
stateptr++;
statestk[stateptr]=state;
}
catch (ArrayIndexOutOfBoundsException e) {
int oldsize = statestk.length;
int newsize = oldsize * 2;
int[] newstack = new int[newsize];
System.arraycopy(statestk,0,newstack,0,oldsize);
statestk = newstack;
statestk[stateptr]=state;
}
}
final int state_pop()
{
return statestk[stateptr--];
}
final void state_drop(int cnt)
{
stateptr -= cnt;
}
final int state_peek(int relative)
{
return statestk[stateptr-relative];
}
//###############################################################
// method: init_stacks : allocate and prepare stacks
//###############################################################
final boolean init_stacks()
{
stateptr = -1;
val_init();
return true;
}
//###############################################################
// method: dump_stacks : show n levels of the stacks
//###############################################################
void dump_stacks(int count)
{
int i;
System.out.println("=index==state====value= s:"+stateptr+" v:"+valptr);
for (i=0;i<count;i++)
System.out.println(" "+i+" "+statestk[i]+" "+valstk[i]);
System.out.println("======================");
}
//########## SEMANTIC VALUES ##########
//public class ParserVal is defined in ParserVal.java
String yytext;//user variable to return contextual strings
ParserVal yyval; //used to return semantic vals from action routines
ParserVal yylval;//the 'lval' (result) I got from yylex()
ParserVal valstk[];
int valptr;
//###############################################################
// methods: value stack push,pop,drop,peek.
//###############################################################
void val_init()
{
valstk=new ParserVal[YYSTACKSIZE];
yyval=new ParserVal();
yylval=new ParserVal();
valptr=-1;
}
void val_push(ParserVal val)
{
if (valptr>=YYSTACKSIZE)
return;
valstk[++valptr]=val;
}
ParserVal val_pop()
{
if (valptr<0)
return new ParserVal();
return valstk[valptr--];
}
void val_drop(int cnt)
{
int ptr;
ptr=valptr-cnt;
if (ptr<0)
return;
valptr = ptr;
}
ParserVal val_peek(int relative)
{
int ptr;
ptr=valptr-relative;
if (ptr<0)
return new ParserVal();
return valstk[ptr];
}
final ParserVal dup_yyval(ParserVal val)
{
ParserVal dup = new ParserVal();
dup.ival = val.ival;
dup.dval = val.dval;
dup.sval = val.sval;
dup.obj = val.obj;
return dup;
}
//#### end semantic value section ####
public final static short FIN=257;
public final static short NUM=258;
public final static short CLASSTYPE=259;
public final static short ID=260;
public final static short NIL=261;
public final static short TRUE=262;
public final static short FALSE=263;
public final static short NEW=264;
public final static short INSTANCEOF=265;
public final static short SET=266;
public final static short GET=267;
public final static short CLASS=268;
public final static short EXTENDS=269;
public final static short IS=270;
public final static short NOT=271;
public final static short AND=272;
public final static short OR=273;
public final static short EQ=274;
public final static short LT=275;
public final static short ADD=276;
public final static short SUB=277;
public final static short MUL=278;
public final static short DIV=279;
public final static short RETURN=280;
public final static short WRITELN=281;
public final static short IF=282;
public final static short THEN=283;
public final static short ELSE=284;
public final static short PROGRAM=285;
public final static short BEGIN=286;
public final static short END=287;
public final static short LET=288;
public final static short IN=289;
public final static short VARS=290;
public final static short METHODS=291;
public final static short DO=292;
public final static short WHILE=293;
public final static short YYERRCODE=256;
final static short yylhs[] = { -1,
0, 10, 10, 11, 11, 12, 12, 3, 13, 14,
14, 15, 15, 16, 16, 2, 2, 17, 17, 18,
19, 19, 20, 21, 21, 22, 7, 7, 8, 8,
9, 4, 4, 5, 5, 5, 6, 6, 6, 6,
6, 6, 6, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 23, 23, 24, 24,
};
final static short yylen[] = { 2,
4, 0, 1, 1, 2, 0, 3, 3, 6, 0,
2, 0, 2, 0, 2, 1, 1, 1, 2, 3,
1, 3, 1, 1, 2, 7, 0, 1, 3, 1,
2, 0, 1, 3, 2, 1, 6, 5, 3, 2,
2, 6, 4, 1, 1, 1, 1, 1, 3, 6,
2, 3, 3, 3, 3, 3, 3, 3, 3, 2,
3, 3, 0, 1, 1, 3,
};
final static short yydefred[] = { 0,
0, 0, 0, 0, 3, 0, 23, 0, 0, 0,
5, 0, 0, 16, 17, 0, 0, 18, 0, 1,
11, 0, 0, 0, 7, 19, 47, 44, 45, 46,
0, 0, 0, 0, 0, 0, 0, 0, 0, 33,
0, 0, 0, 0, 20, 0, 60, 0, 48, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 8, 0, 0, 0, 0, 9,
22, 0, 0, 0, 62, 61, 0, 0, 0, 0,
0, 0, 0, 0, 0, 34, 0, 0, 0, 24,
0, 0, 43, 0, 0, 0, 25, 0, 0, 0,
0, 0, 0, 0, 0, 42, 0, 0, 0, 0,
0, 30, 50, 0, 31, 0, 0, 0, 29, 26,
};
final static short yydgoto[] = { 2,
38, 16, 20, 39, 40, 41, 110, 111, 112, 4,
5, 10, 6, 13, 44, 70, 17, 18, 23, 49,
89, 90, 102, 103,
};
final static short yysindex[] = { -271,
-250, 0, -219, -244, 0, -250, 0, -221, -235, -234,
0, -235, -206, 0, 0, -219, -243, 0, -40, 0,
0, -222, 8, 27, 0, 0, 0, 0, 0, 0,
-235, 158, 158, 158, 158, 158, 158, -167, -214, 0,
15, -186, -235, -210, 0, -219, 0, -185, 0, -73,
-73, -107, -188, 136, -235, -219, 158, 158, 158, 158,
158, 158, 158, 158, 0, -40, 158, -235, -235, 0,
0, -219, -234, -234, 0, 0, -32, -185, -94, -135,
-135, -94, -94, -185, -185, 0, -73, -219, -235, 0,
54, -189, 0, 158, 158, 57, 0, 158, -234, -73,
-73, 60, 58, -235, 74, 0, 0, 158, -219, 76,
67, 0, 0, -73, 0, -244, -235, -234, 0, 0,
};
final static short yyrindex[] = { 0,
-227, 0, 0, -159, 0, -223, 0, -142, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, -158, 0,
0, -259, 0, 81, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-154, 176, 0, -233, 0, 0, 0, -8, 0, -58,
-57, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, -152, 0, -249, 0, 0,
0, 0, 0, 0, 0, 0, 191, 13, 75, -31,
-10, 95, 115, 34, 55, 0, -55, 0, -230, 0,
-29, 0, 0, 0, 112, 0, 0, 112, 0, -54,
-38, 0, 116, 120, 0, 0, 160, 0, 0, 0,
121, 0, 0, -1, 0, -159, 0, 0, 0, 0,
};
final static short yygindex[] = { 0,
88, 14, -52, 0, 97, 0, 0, 0, 47, 0,
169, 63, 0, 0, 0, 0, 137, -6, 135, 4,
0, 98, 90, 0,
};
final static int YYTABLESIZE=470;
static short yytable[];
static { yytable();}
static void yytable(){
yytable = new short[]{ 37,
40, 41, 65, 39, 38, 65, 8, 95, 12, 58,
26, 49, 58, 1, 49, 14, 15, 3, 13, 24,
92, 93, 42, 14, 15, 21, 12, 58, 12, 49,
59, 12, 51, 59, 14, 51, 13, 15, 13, 66,
7, 13, 66, 9, 47, 25, 106, 12, 59, 24,
51, 19, 14, 52, 14, 15, 52, 15, 2, 77,
2, 26, 4, 22, 4, 120, 45, 43, 76, 42,
46, 52, 65, 66, 56, 91, 55, 56, 72, 67,
69, 72, 88, 57, 58, 59, 60, 61, 62, 63,
64, 96, 56, 98, 99, 57, 104, 55, 57, 56,
107, 108, 88, 74, 57, 58, 59, 60, 61, 62,
63, 64, 115, 57, 113, 53, 116, 109, 53, 48,
50, 51, 52, 53, 54, 117, 6, 10, 32, 55,
109, 72, 36, 53, 35, 54, 57, 58, 54, 21,
61, 62, 63, 64, 78, 79, 80, 81, 82, 83,
84, 85, 63, 54, 87, 55, 64, 55, 55, 72,
27, 28, 86, 119, 57, 58, 59, 60, 61, 62,
63, 64, 72, 55, 11, 73, 75, 57, 118, 68,
71, 100, 101, 63, 64, 101, 97, 105, 0, 0,
0, 55, 0, 72, 0, 114, 0, 37, 57, 58,
59, 60, 61, 62, 63, 64, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 27, 37, 7,
28, 29, 30, 31, 0, 0, 0, 0, 40, 41,
32, 39, 38, 94, 0, 49, 0, 49, 0, 33,
34, 35, 49, 49, 49, 49, 49, 49, 49, 49,
0, 58, 36, 49, 0, 58, 51, 49, 0, 0,
58, 0, 49, 51, 51, 51, 51, 51, 51, 51,
51, 0, 59, 0, 51, 0, 59, 52, 51, 0,
0, 59, 0, 51, 52, 52, 52, 52, 52, 52,
52, 52, 0, 0, 0, 52, 0, 0, 56, 52,
0, 0, 0, 0, 52, 56, 56, 56, 56, 56,
56, 56, 56, 0, 0, 0, 56, 0, 0, 57,
56, 0, 0, 0, 0, 56, 57, 57, 57, 57,
57, 57, 57, 57, 0, 0, 0, 57, 0, 53,
0, 57, 0, 0, 0, 0, 57, 53, 53, 53,
53, 53, 0, 0, 0, 0, 0, 53, 0, 54,
0, 53, 0, 0, 0, 0, 53, 54, 54, 54,
54, 54, 0, 0, 0, 0, 0, 54, 0, 55,
0, 54, 0, 0, 0, 0, 54, 55, 55, 55,
55, 55, 0, 0, 0, 0, 0, 55, 0, 0,
55, 55, 72, 0, 0, 0, 55, 57, 58, 59,
60, 61, 62, 63, 64, 27, 0, 7, 28, 29,
30, 31, 0, 0, 50, 0, 50, 0, 32, 0,
0, 50, 50, 50, 50, 50, 50, 50, 50, 0,
48, 0, 48, 0, 0, 0, 37, 48, 48, 48,
48, 48, 48, 48, 48, 49, 0, 49, 0, 0,
0, 0, 49, 49, 49, 49, 49, 49, 49, 49,
};
}
static short yycheck[];
static { yycheck(); }
static void yycheck() {
yycheck = new short[] { 40,
59, 59, 41, 59, 59, 44, 3, 40, 268, 41,
17, 41, 44, 285, 44, 259, 260, 268, 268, 16,
73, 74, 19, 259, 260, 12, 286, 59, 288, 59,
41, 291, 41, 44, 268, 44, 286, 268, 288, 41,
260, 291, 44, 288, 31, 289, 99, 269, 59, 46,
59, 286, 286, 41, 288, 286, 44, 288, 286, 56,
288, 68, 286, 270, 288, 118, 59, 290, 55, 66,
44, 59, 287, 59, 41, 72, 265, 44, 267, 266,
291, 267, 69, 272, 273, 274, 275, 276, 277, 278,
279, 88, 59, 40, 284, 41, 40, 265, 44, 267,
41, 44, 89, 292, 272, 273, 274, 275, 276, 277,
278, 279, 109, 59, 41, 41, 41, 104, 44, 32,
33, 34, 35, 36, 37, 59, 286, 270, 287, 265,
117, 267, 287, 59, 287, 41, 272, 273, 44, 59,
276, 277, 278, 279, 57, 58, 59, 60, 61, 62,
63, 64, 41, 59, 67, 41, 41, 265, 44, 267,
41, 41, 66, 117, 272, 273, 274, 275, 276, 277,
278, 279, 267, 59, 6, 283, 41, 272, 116, 43,
46, 94, 95, 278, 279, 98, 89, 98, -1, -1,
-1, 265, -1, 267, -1, 108, -1, 40, 272, 273,
274, 275, 276, 277, 278, 279, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, 258, 59, 260,
261, 262, 263, 264, -1, -1, -1, -1, 287, 287,
271, 287, 287, 266, -1, 265, -1, 267, -1, 280,
281, 282, 272, 273, 274, 275, 276, 277, 278, 279,
-1, 283, 293, 283, -1, 287, 265, 287, -1, -1,
292, -1, 292, 272, 273, 274, 275, 276, 277, 278,
279, -1, 283, -1, 283, -1, 287, 265, 287, -1,
-1, 292, -1, 292, 272, 273, 274, 275, 276, 277,
278, 279, -1, -1, -1, 283, -1, -1, 265, 287,
-1, -1, -1, -1, 292, 272, 273, 274, 275, 276,
277, 278, 279, -1, -1, -1, 283, -1, -1, 265,
287, -1, -1, -1, -1, 292, 272, 273, 274, 275,
276, 277, 278, 279, -1, -1, -1, 283, -1, 265,
-1, 287, -1, -1, -1, -1, 292, 273, 274, 275,
276, 277, -1, -1, -1, -1, -1, 283, -1, 265,
-1, 287, -1, -1, -1, -1, 292, 273, 274, 275,
276, 277, -1, -1, -1, -1, -1, 283, -1, 265,
-1, 287, -1, -1, -1, -1, 292, 273, 274, 275,
276, 277, -1, -1, -1, -1, -1, 283, -1, -1,
265, 287, 267, -1, -1, -1, 292, 272, 273, 274,
275, 276, 277, 278, 279, 258, -1, 260, 261, 262,
263, 264, -1, -1, 265, -1, 267, -1, 271, -1,
-1, 272, 273, 274, 275, 276, 277, 278, 279, -1,
265, -1, 267, -1, -1, -1, 287, 272, 273, 274,
275, 276, 277, 278, 279, 265, -1, 267, -1, -1,
-1, -1, 272, 273, 274, 275, 276, 277, 278, 279,
};
}
final static short YYFINAL=2;
final static short YYMAXTOKEN=293;
final static String yyname[] = {
"end-of-file",null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,"'('","')'",null,null,"','",
null,null,null,null,null,null,null,null,null,null,null,null,null,null,"';'",
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
null,null,null,null,null,"FIN","NUM","CLASSTYPE","ID","NIL","TRUE","FALSE",
"NEW","INSTANCEOF","SET","GET","CLASS","EXTENDS","IS","NOT","AND","OR","EQ",
"LT","ADD","SUB","MUL","DIV","RETURN","WRITELN","IF","THEN","ELSE","PROGRAM",
"BEGIN","END","LET","IN","VARS","METHODS","DO","WHILE",
};
final static String yyrule[] = {
"$accept : Prog",
"Prog : PROGRAM Classes Locals InstrList",
"Classes :",
"Classes : NonEmptyClasses",
"NonEmptyClasses : Class",
"NonEmptyClasses : Class NonEmptyClasses",
"Locals :",
"Locals : LET VarDecs IN",
"InstrList : BEGIN InstrSeq END",
"Class : CLASS Id Extends IS VarDecList MethodList",
"Extends :",
"Extends : EXTENDS ClassType",
"VarDecList :",
"VarDecList : VARS VarDecs",
"MethodList :",
"MethodList : METHODS Methods",
"ClassType : CLASSTYPE",
"ClassType : ID",
"VarDecs : VarDec",
"VarDecs : VarDecs VarDec",
"VarDec : ClassType Ids ';'",
"Ids : Id",
"Ids : Id ',' Ids",
"Id : ID",
"Methods : Method",
"Methods : Methods Method",
"Method : ClassType Id '(' ArgDecList ')' Locals InstrList",
"ArgDecList :",
"ArgDecList : ArgDecs",
"ArgDecs : ArgDecs ';' ArgDec",
"ArgDecs : ArgDec",
"ArgDec : ClassType Id",
"InstrSeq :",
"InstrSeq : InstrSeqNonEmpty",
"InstrSeqNonEmpty : Instr ';' InstrSeqNonEmpty",
"InstrSeqNonEmpty : Instr ';'",
"InstrSeqNonEmpty : Instr",
"Instr : Expression GET Id '(' ArgList ')'",
"Instr : Expression GET Id SET Expression",
"Instr : Id SET Expression",
"Instr : RETURN Expression",
"Instr : WRITELN Expression",
"Instr : IF Expression THEN InstrList ELSE InstrList",
"Instr : WHILE Expression DO InstrList",
"Expression : NIL",
"Expression : TRUE",
"Expression : FALSE",
"Expression : NUM",
"Expression : Id",
"Expression : Expression GET Id",
"Expression : Expression GET Id '(' ArgList ')'",
"Expression : NOT Expression",
"Expression : Expression AND Expression",
"Expression : Expression OR Expression",
"Expression : Expression ADD Expression",
"Expression : Expression SUB Expression",
"Expression : Expression MUL Expression",
"Expression : Expression DIV Expression",
"Expression : Expression EQ Expression",
"Expression : Expression LT Expression",
"Expression : NEW ClassType",
"Expression : Expression INSTANCEOF ClassType",
"Expression : '(' Expression ')'",
"ArgList :",
"ArgList : Args",
"Args : Expression",
"Args : Args ',' Expression",
};
//#line 224 "lexer/bopl.y"
private Yylex lexer;
public static IAST ast;
private int yylex(){
int yyl_return = -1;
try{
yylval = new ParserVal(0);
yyl_return = lexer.yylex();
}
catch(IOException e){
System.err.println("IO Error : " + e);
}
return yyl_return;
}
public void yyerror(String error){
System.err.println("Error : " + error);
}
public Parser (Reader r){
lexer = new Yylex(r, this);
}
public void parse(String fileName){
Parser yyparser = null;
try{
yyparser = new Parser(new FileReader(fileName));
}
catch(FileNotFoundException e){
System.err.println("Not found");
return;
}
yyparser.yyparse();
System.out.println("Parsing complete, have a nice day!");
}
public IAST getAST(){ return this.ast; }
//#line 453 "Parser.java"
//###############################################################
// method: yylexdebug : check lexer state
//###############################################################
void yylexdebug(int state,int ch)
{
String s=null;
if (ch < 0) ch=0;
if (ch <= YYMAXTOKEN) //check index bounds
s = yyname[ch]; //now get it
if (s==null)
s = "illegal-symbol";
debug("state "+state+", reading "+ch+" ("+s+")");
}
//The following are now global, to aid in error reporting
int yyn; //next next thing to do
int yym; //
int yystate; //current parsing state from state table
String yys; //current token string
//###############################################################
// method: yyparse : parse input and execute indicated items
//###############################################################
int yyparse()
{
boolean doaction;
init_stacks();
yynerrs = 0;
yyerrflag = 0;
yychar = -1; //impossible char forces a read
yystate=0; //initial state
state_push(yystate); //save it
val_push(yylval); //save empty value
while (true) //until parsing is done, either correctly, or w/error
{
doaction=true;
if (yydebug) debug("loop");
//#### NEXT ACTION (from reduction table)
for (yyn=yydefred[yystate];yyn==0;yyn=yydefred[yystate])
{
if (yydebug) debug("yyn:"+yyn+" state:"+yystate+" yychar:"+yychar);
if (yychar < 0) //we want a char?
{
yychar = yylex(); //get next token
if (yydebug) debug(" next yychar:"+yychar);
//#### ERROR CHECK ####
if (yychar < 0) //it it didn't work/error
{
yychar = 0; //change it to default string (no -1!)
if (yydebug)
yylexdebug(yystate,yychar);
}
}//yychar<0
yyn = yysindex[yystate]; //get amount to shift by (shift index)
if ((yyn != 0) && (yyn += yychar) >= 0 &&
yyn <= YYTABLESIZE && yycheck[yyn] == yychar)
{
if (yydebug)
debug("state "+yystate+", shifting to state "+yytable[yyn]);
//#### NEXT STATE ####
yystate = yytable[yyn];//we are in a new state
state_push(yystate); //save it
val_push(yylval); //push our lval as the input for next rule
yychar = -1; //since we have 'eaten' a token, say we need another
if (yyerrflag > 0) //have we recovered an error?
--yyerrflag; //give ourselves credit
doaction=false; //but don't process yet
break; //quit the yyn=0 loop
}
yyn = yyrindex[yystate]; //reduce
if ((yyn !=0 ) && (yyn += yychar) >= 0 &&
yyn <= YYTABLESIZE && yycheck[yyn] == yychar)
{ //we reduced!
if (yydebug) debug("reduce");
yyn = yytable[yyn];
doaction=true; //get ready to execute
break; //drop down to actions
}
else //ERROR RECOVERY
{
if (yyerrflag==0)
{
yyerror("syntax error");
yynerrs++;
}
if (yyerrflag < 3) //low error count?
{
yyerrflag = 3;
while (true) //do until break
{
if (stateptr<0) //check for under & overflow here
{
yyerror("stack underflow. aborting..."); //note lower case 's'
return 1;
}
yyn = yysindex[state_peek(0)];
if ((yyn != 0) && (yyn += YYERRCODE) >= 0 &&
yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE)
{
if (yydebug)
debug("state "+state_peek(0)+", error recovery shifting to state "+yytable[yyn]+" ");
yystate = yytable[yyn];
state_push(yystate);
val_push(yylval);
doaction=false;
break;
}
else
{
if (yydebug)
debug("error recovery discarding state "+state_peek(0)+" ");
if (stateptr<0) //check for under & overflow here
{
yyerror("Stack underflow. aborting..."); //capital 'S'
return 1;
}
state_pop();
val_pop();
}
}
}
else //discard this token
{
if (yychar == 0)
return 1; //yyabort
if (yydebug)
{
yys = null;
if (yychar <= YYMAXTOKEN) yys = yyname[yychar];
if (yys == null) yys = "illegal-symbol";
debug("state "+yystate+", error recovery discards token "+yychar+" ("+yys+")");
}
yychar = -1; //read another
}
}//end error recovery
}//yyn=0 loop
if (!doaction) //any reason not to proceed?
continue; //skip action
yym = yylen[yyn]; //get count of terminals on rhs
if (yydebug)
debug("state "+yystate+", reducing "+yym+" by rule "+yyn+" ("+yyrule[yyn]+")");
if (yym>0) //if count of rhs not 'nil'
yyval = val_peek(yym-1); //get current semantic value
yyval = dup_yyval(yyval); //duplicate yyval if ParserVal is used as semantic value
switch(yyn)
{
//########## USER-SUPPLIED ACTIONS ##########
case 1:
//#line 74 "lexer/bopl.y"
{ this.ast=new ASTProgram((ArrayList<ASTClass>)val_peek(2).obj,(ArrayList<ASTDeclaration>)val_peek(1).obj,(ASTSequence)val_peek(0).obj); }
break;
case 2:
//#line 77 "lexer/bopl.y"
{yyval.obj = new ArrayList<ASTClass>();}
break;
case 3:
//#line 78 "lexer/bopl.y"
{ yyval.obj = val_peek(0).obj;}
break;
case 4:
//#line 81 "lexer/bopl.y"
{ArrayList<ASTClass> classes=new ArrayList<ASTClass>();
classes.add((ASTClass)val_peek(0).obj);
yyval.obj=classes;}
break;
case 5:
//#line 84 "lexer/bopl.y"
{ArrayList<ASTClass> classes=(ArrayList<ASTClass>)val_peek(0).obj;
classes.add(0,(ASTClass)val_peek(1).obj);
yyval.obj=classes;}
break;
case 6:
//#line 89 "lexer/bopl.y"
{ yyval.obj = new ArrayList<ASTDeclaration>(); }
break;
case 7:
//#line 90 "lexer/bopl.y"
{ yyval.obj = val_peek(1).obj; }
break;
case 8:
//#line 93 "lexer/bopl.y"
{ yyval.obj = val_peek(1).obj; }
break;
case 9:
//#line 96 "lexer/bopl.y"
{ yyval.obj = new ASTClass((ASTid)val_peek(4).obj,(ASTClassType)val_peek(3).obj,(ArrayList<ASTDeclaration>)val_peek(1).obj,(ArrayList<ASTMethod>)val_peek(0).obj); }
break;
case 10:
//#line 99 "lexer/bopl.y"
{ yyval.obj = new ASTClassType("obj"); }
break;
case 11:
//#line 100 "lexer/bopl.y"
{ yyval.obj = val_peek(0).obj; }
break;
case 12:
//#line 103 "lexer/bopl.y"
{ yyval.obj = new ArrayList<ASTDeclaration>(); }
break;
case 13:
//#line 104 "lexer/bopl.y"
{ yyval.obj = val_peek(0).obj; }
break;
case 14:
//#line 108 "lexer/bopl.y"
{ yyval.obj = new ArrayList<ASTMethod>(); }
break;
case 15:
//#line 109 "lexer/bopl.y"
{ yyval.obj = val_peek(0).obj; }
break;
case 16:
//#line 112 "lexer/bopl.y"
{ yyval.obj = new ASTClassType(val_peek(0).sval); }
break;
case 17:
//#line 113 "lexer/bopl.y"
{ yyval.obj = new ASTClassType(val_peek(0).sval); }
break;
case 18:
//#line 116 "lexer/bopl.y"
{ ArrayList<ASTDeclaration> declarations = new ArrayList<ASTDeclaration>();
declarations.add((ASTDeclaration)val_peek(0).obj);
yyval.obj = declarations; }
break;
case 19:
//#line 119 "lexer/bopl.y"
{ ArrayList<ASTDeclaration> declarations = (ArrayList<ASTDeclaration>) val_peek(1).obj;
declarations.add(0,(ASTDeclaration)val_peek(0).obj);
yyval.obj = declarations; }
break;
case 20:
//#line 124 "lexer/bopl.y"
{ yyval.obj = new ASTDeclaration((ASTClassType)val_peek(2).obj,(ArrayList<ASTid>)val_peek(1).obj); }
break;
case 21:
//#line 127 "lexer/bopl.y"
{ ArrayList<ASTid> ids = new ArrayList<ASTid>();
ids.add((ASTid)val_peek(0).obj);
yyval.obj = ids; }
break;
case 22:
//#line 130 "lexer/bopl.y"
{ ArrayList<ASTid> ids = (ArrayList<ASTid>) val_peek(0).obj;
ids.add(0,(ASTid)val_peek(2).obj);
yyval.obj = ids; }
break;
case 23:
//#line 135 "lexer/bopl.y"
{ yyval.obj = new ASTid(val_peek(0).sval); }
break;
case 24:
//#line 138 "lexer/bopl.y"
{ ArrayList<ASTMethod> methods= new ArrayList<ASTMethod>();
methods.add((ASTMethod)val_peek(0).obj);
yyval.obj = methods; }
break;
case 25:
//#line 141 "lexer/bopl.y"
{ ArrayList<ASTMethod> methods=(ArrayList<ASTMethod> ) val_peek(1).obj;
methods.add(0,(ASTMethod)val_peek(0).obj);
yyval.obj = methods; }
break;
case 26:
//#line 146 "lexer/bopl.y"
{ yyval.obj = new ASTMethod((ASTClassType)val_peek(6).obj,(ASTid)val_peek(5).obj,(ArrayList<ASTDeclaration>)val_peek(3).obj,(ArrayList<ASTDeclaration>)val_peek(1).obj,(ASTSequence)val_peek(0).obj); }
break;
case 27:
//#line 149 "lexer/bopl.y"
{ yyval.obj = new ArrayList<ASTDeclaration>(); }
break;
case 28:
//#line 150 "lexer/bopl.y"
{ yyval.obj = val_peek(0).obj; }
break;
case 29:
//#line 153 "lexer/bopl.y"
{ ArrayList<ASTDeclaration> declarations = (ArrayList<ASTDeclaration>)val_peek(2).obj;
declarations.add((ASTDeclaration)val_peek(0).obj);
yyval.obj = declarations; }
break;
case 30:
//#line 156 "lexer/bopl.y"
{ ArrayList<ASTDeclaration> declarations = new ArrayList<ASTDeclaration>();
declarations.add((ASTDeclaration)val_peek(0).obj);
yyval.obj = declarations; }
break;
case 31:
//#line 161 "lexer/bopl.y"
{ yyval.obj = new ASTDeclaration((ASTClassType)val_peek(1).obj,(ASTid)val_peek(0).obj); }
break;
case 32:
//#line 164 "lexer/bopl.y"
{ yyval.obj = new ASTSequence(new ArrayList<IASTInstruction>()); }
break;
case 33:
//#line 165 "lexer/bopl.y"
{ yyval.obj = val_peek(0).obj; }
break;
case 34:
//#line 169 "lexer/bopl.y"
{((ASTSequence) val_peek(0).obj).push((IASTInstruction)val_peek(2).obj);
yyval.obj = val_peek(0).obj; }
break;
case 35:
//#line 171 "lexer/bopl.y"
{ ASTSequence seq = new ASTSequence(new ArrayList<IASTInstruction>());
seq.push((IASTInstruction)val_peek(1).obj);
yyval.obj = seq; }
break;
case 36:
//#line 174 "lexer/bopl.y"
{ ASTSequence seq = new ASTSequence(new ArrayList<IASTInstruction>());
seq.push((IASTInstruction)val_peek(0).obj);
yyval.obj = seq; }
break;
case 37:
//#line 180 "lexer/bopl.y"
{ yyval.obj = new ASTCall((IASTExpression)val_peek(5).obj,(ASTid)val_peek(3).obj,(ArrayList<IASTExpression>)val_peek(1).obj); }
break;
case 38:
//#line 181 "lexer/bopl.y"
{ yyval.obj = new ASTSetField((IASTExpression)val_peek(4).obj,(ASTid)val_peek(2).obj,(IASTExpression)val_peek(0).obj); }
break;
case 39:
//#line 182 "lexer/bopl.y"
{ yyval.obj = new ASTSetVar((ASTid)val_peek(2).obj,(IASTExpression)val_peek(0).obj); }
break;
case 40:
//#line 183 "lexer/bopl.y"
{ yyval.obj = new ASTReturn((IASTExpression)val_peek(0).obj);}
break;
case 41:
//#line 184 "lexer/bopl.y"
{ yyval.obj = new ASTWrite((IASTExpression)val_peek(0).obj); }
break;
case 42:
//#line 185 "lexer/bopl.y"
{ yyval.obj = new ASTAlternative((IASTExpression)val_peek(4).obj,(ASTSequence)val_peek(2).obj,(ASTSequence)val_peek(0).obj); }
break;
case 43:
//#line 186 "lexer/bopl.y"
{ yyval.obj = new ASTWhile((IASTExpression)val_peek(2).obj,(ASTSequence)val_peek(0).obj); }
break;
case 44:
//#line 190 "lexer/bopl.y"
{ yyval.obj = ASTExpression.NULL; }
break;
case 45:
//#line 191 "lexer/bopl.y"
{ yyval.obj = ASTExpression.TRUE; }
break;
case 46:
//#line 192 "lexer/bopl.y"
{ yyval.obj = ASTExpression.FALSE; }
break;
case 47:
//#line 193 "lexer/bopl.y"
{ yyval.obj = new ASTNum(val_peek(0).dval); }
break;
case 48:
//#line 194 "lexer/bopl.y"
{ yyval.obj = val_peek(0).obj; }
break;
case 49:
//#line 195 "lexer/bopl.y"
{ yyval.obj = new ASTGet((IASTExpression)val_peek(2).obj,(ASTid)val_peek(0).obj); }
break;
case 50:
//#line 196 "lexer/bopl.y"
{ yyval.obj = new ASTCall((IASTExpression)val_peek(5).obj,(ASTid)val_peek(3).obj,(ArrayList<IASTExpression>)val_peek(1).obj); }
break;
case 51:
//#line 197 "lexer/bopl.y"
{ yyval.obj = new NotOperator((IASTExpression)val_peek(0).obj); }
break;
case 52:
//#line 198 "lexer/bopl.y"
{ yyval.obj = new AndOperator((IASTExpression)val_peek(2).obj,(IASTExpression)val_peek(0).obj); }
break;
case 53:
//#line 199 "lexer/bopl.y"
{ yyval.obj = new OrOperator((IASTExpression)val_peek(2).obj,(IASTExpression)val_peek(0).obj); }
break;
case 54:
//#line 200 "lexer/bopl.y"
{ yyval.obj = new AddOperator((IASTExpression)val_peek(2).obj,(IASTExpression)val_peek(0).obj); }
break;
case 55:
//#line 201 "lexer/bopl.y"
{ yyval.obj = new SubOperator((IASTExpression)val_peek(2).obj,(IASTExpression)val_peek(0).obj); }
break;
case 56:
//#line 202 "lexer/bopl.y"
{ yyval.obj = new MultOperator((IASTExpression)val_peek(2).obj,(IASTExpression)val_peek(0).obj); }
break;
case 57:
//#line 203 "lexer/bopl.y"
{ yyval.obj = new DivOperator((IASTExpression)val_peek(2).obj,(IASTExpression)val_peek(0).obj); }
break;
case 58:
//#line 204 "lexer/bopl.y"
{ yyval.obj = new EqualsOperator((IASTExpression)val_peek(2).obj,(IASTExpression)val_peek(0).obj); }
break;
case 59:
//#line 205 "lexer/bopl.y"
{ yyval.obj = new LessThanOperator((IASTExpression)val_peek(2).obj,(IASTExpression)val_peek(0).obj); }
break;
case 60:
//#line 206 "lexer/bopl.y"
{ yyval.obj = new ASTNew((ASTClassType)val_peek(0).obj); }
break;
case 61:
//#line 207 "lexer/bopl.y"
{ yyval.obj = new ASTInstanceOf((IASTExpression)val_peek(2).obj,(ASTClassType)val_peek(0).obj); }
break;
case 62:
//#line 208 "lexer/bopl.y"
{ yyval.obj = val_peek(1).obj; }
break;
case 63:
//#line 211 "lexer/bopl.y"
{ yyval.obj = new ArrayList<IASTExpression>(); }
break;
case 64:
//#line 212 "lexer/bopl.y"
{ yyval.obj = val_peek(0).obj; }
break;
case 65:
//#line 215 "lexer/bopl.y"
{ ArrayList<IASTExpression> expressions=new ArrayList<IASTExpression>();
expressions.add((IASTExpression)val_peek(0).obj);
yyval.obj = expressions; }
break;
case 66:
//#line 218 "lexer/bopl.y"
{ ArrayList<IASTExpression> expressions=(ArrayList<IASTExpression>)val_peek(2).obj;
expressions.add((IASTExpression)val_peek(0).obj);
yyval.obj = expressions; }
break;
//#line 895 "Parser.java"
//########## END OF USER-SUPPLIED ACTIONS ##########
}//switch
//#### Now let's reduce... ####
if (yydebug) debug("reduce");
state_drop(yym); //we just reduced yylen states
yystate = state_peek(0); //get new state
val_drop(yym); //corresponding value drop
yym = yylhs[yyn]; //select next TERMINAL(on lhs)
if (yystate == 0 && yym == 0)//done? 'rest' state and at first TERMINAL
{
if (yydebug) debug("After reduction, shifting from state 0 to state "+YYFINAL+"");
yystate = YYFINAL; //explicitly say we're done
state_push(YYFINAL); //and save it
val_push(yyval); //also save the semantic value of parsing
if (yychar < 0) //we want another character?
{
yychar = yylex(); //get next character
if (yychar<0) yychar=0; //clean, if necessary
if (yydebug)
yylexdebug(yystate,yychar);
}
if (yychar == 0) //Good exit (if lex returns 0 ;-)
break; //quit the loop--all DONE
}//if yystate
else //else not done yet
{ //get next state and push, for next yydefred[]
yyn = yygindex[yym]; //find out where to go
if ((yyn != 0) && (yyn += yystate) >= 0 &&
yyn <= YYTABLESIZE && yycheck[yyn] == yystate)
yystate = yytable[yyn]; //get new state
else
yystate = yydgoto[yym]; //else go to new defred
if (yydebug) debug("after reduction, shifting from state "+state_peek(0)+" to state "+yystate+"");
state_push(yystate); //going again, so push state & val...
val_push(yyval); //for next action
}
}//main loop
return 0;//yyaccept!!
}
//## end of method parse() ######################################
//## run() --- for Thread #######################################
/**
* A default run method, used for operating this parser
* object in the background. It is intended for extending Thread
* or implementing Runnable. Turn off with -Jnorun .
*/
public void run()
{
yyparse();
}
//## end of method run() ########################################
//## Constructors ###############################################
/**
* Default constructor. Turn off with -Jnoconstruct .
*/
public Parser()
{
//nothing to do
}
/**
* Create a parser, setting the debug to true or false.
* @param debugMe true for debugging, false for no debug.
*/
public Parser(boolean debugMe)
{
yydebug=debugMe;
}
//###############################################################
}
//################### END OF CLASS ##############################
| true |
75028d9e4eb45e4d12d593940e34953c84bd6ecc | Java | leo-la/repo1 | /WeCrowdFunding_manager_impl/src/main/java/com/leo/manager/controller/PermissionController.java | UTF-8 | 12,840 | 2.125 | 2 | [] | no_license | package com.leo.manager.controller;
import com.leo.manager.service.IPermissionService;
import com.leo.manager.service.IUserService;
import com.leo.pojo.*;
import com.leo.utils.ParamConverterUtils;
import com.leo.utils.UserInfoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
* 权限控制器
*/
@Controller
@RequestMapping("/permission")
public class PermissionController {
/**
* 权限服务
*/
@Autowired
IPermissionService permissionService;
/**
* 用户服务
*/
@Autowired
IUserService userService;
/**
* 跳转用户维护
* @param model
* @return
*/
@RequestMapping("/toUser")
public String toUser(Model model){
UserInfoUtils.addUserInfo(model);
return "user";
}
/**
* 跳转用户分配角色
* @param model
* @return
*/
@RequestMapping("/toAssignRole")
public String toAssignRole(Model model){
UserInfoUtils.addUserInfo(model);
return "assignRole";
}
/**
*用户维护-查询用户页面信息
* @param pageBean
* @return
*/
@ResponseBody
@RequestMapping("/searchUserPage")
public PageBean searchUserPage(@RequestBody PageBean pageBean){
pageBean = permissionService.searchUserPage(pageBean);
return pageBean;
}
/**
* 用户维护-查询客户页面数据
* @param pageBean
* @return
*/
@ResponseBody
@RequestMapping("/searchMemberPage")
public PageBean searchMemberPage(@RequestBody PageBean pageBean){
pageBean = permissionService.searchMemberPage(pageBean);
return pageBean;
}
/**
* 用户维护-删除用户
* @param userInfo
* @return
*/
@ResponseBody
@RequestMapping("/deleteUser")
public boolean deleteOne(@RequestBody UserInfo userInfo){
Integer integer = permissionService.deleteUserById(userInfo.getId());
if(integer==1){
return true;
}else{
return false;
}
}
/**
* 用户维护-删除多个用户
* @param deletes
* @return
*/
@ResponseBody
@RequestMapping("/deleteUsers")
public Integer deleteSelect(@RequestBody String deletes){
String s1 = deletes.split(":")[1];
String[] strings = s1.replace("[", "").replace("]", "")
.replace("}", "").split(",");
int deleteCount = 0;
for (String string : strings) {
int id = Integer.parseInt(string.substring(1, string.length() - 1));
Integer integer = permissionService.deleteUserById(id);
if(integer==1){
deleteCount ++;
}
}
System.out.println("删除选中:"+deletes);
return deleteCount;
}
/**
* 用户维护-更新用户分配角色
* @param assignRoleBean
* @return
*/
@ResponseBody
@RequestMapping("/updateUserRole")
public boolean updateUserRole(@RequestBody AssignRoleBean assignRoleBean){
System.out.println("分配角色控制层:"+assignRoleBean);
return permissionService.updateRoles(assignRoleBean);
}
/**
* 用户维护-条件查询用户
* @param pageBean
* @return
*/
@ResponseBody
@RequestMapping("/conditionSearchUsers")
public PageBean conditionSearch(@RequestBody PageBean pageBean){
pageBean = permissionService.searchUserPageCondition(pageBean);
return pageBean;
}
/**
* 用户维护-条件查询客户信息
* @param pageBean
* @return
*/
@ResponseBody
@RequestMapping("/conditionSearchMembers")
public PageBean conditionSearchMembers(@RequestBody PageBean pageBean){
pageBean = permissionService.searchMemberpageByCondition(pageBean);
return pageBean;
}
/**
* 用户维护-查询用户分配角色页面信息
* @param assignRoleBean
* @return
*/
@ResponseBody
@RequestMapping("/searchAssignRoleInformation")
public AssignRoleBean searchAssignRoleInformation(@RequestBody AssignRoleBean assignRoleBean){
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = userDetails.getUsername();
Integer id = userService.findUserIdByName(username);
assignRoleBean.setUserid(id);
permissionService.searchAssignRoleInformation(assignRoleBean);
return assignRoleBean;
}
/**
* 跳转角色维护
* @param model
* @return
*/
@RequestMapping("/toRole")
public String toRole(Model model){
UserInfoUtils.addUserInfo(model);
return "role";
}
/**
* 跳转新增角色
* @param model
* @return
*/
@RequestMapping("/toAddRole")
public String toAddRole(Model model){
UserInfoUtils.addUserInfo(model);
return "addRole";
}
/**
*跳转角色分配权限
* @param s
* @param model
* @return
*/
@RequestMapping("/toAssignPermissions/{roleid}")
public String toAssignPermissions(@PathVariable("roleid") String s, Model model){
System.out.println("toAssignPermissions:"+s);
Integer roleid = ParamConverterUtils.restFulConverter(s);
UserInfoUtils.addUserInfo(model);
model.addAttribute("roleid",roleid);
return "assignPermission";
}
/**
* 跳转更新角色
* @param s
* @param model
* @return
*/
@RequestMapping("/toUpdateRole/{roleid}")
public String toUpdateRole(@PathVariable("roleid") String s, Model model){
System.out.println("toUpdateRole:"+s);
Integer roleid = ParamConverterUtils.restFulConverter(s);
Role role = permissionService.findRoleById(roleid);
UserInfoUtils.addUserInfo(model);
model.addAttribute("role",role);
return "updateRole";
}
/**
* 角色维护-查询角色页面信息
* @param pageBean
* @return
*/
@ResponseBody
@RequestMapping("/searchRolePage")
public PageBean searchRolePage(@RequestBody PageBean pageBean){
pageBean = permissionService.searchRolePage(pageBean);
return pageBean;
}
/**
* 角色维护-删除角色
* @param role
* @return
*/
@ResponseBody
@RequestMapping("/deleteRole")
public boolean deleteRole(@RequestBody Role role){
Integer integer = permissionService.deleteRoleById(role.getId());
System.out.println("删除与否:"+integer);
if(integer==1){
return true;
}else{
return false;
}
}
/**
* 角色维护-删除多个角色
* @param deletes
* @return
*/
@ResponseBody
@RequestMapping("/deleteRoles")
public Integer deleteRoles(@RequestBody String deletes){
List<Integer> integers = ParamConverterUtils.listJsonConverter(deletes);
int deleteCount = 0;
for (Integer id : integers) {
Integer integer = permissionService.deleteRoleById(id);
if(integer==1){
deleteCount ++;
}
}
System.out.println("删除选中:"+deletes);
return deleteCount;
}
/**
*角色维护-分配许可
* @param permissionid
* @param s
* @return
*/
@ResponseBody
@RequestMapping("/assignPermission/{roleid}")
public boolean assignPermission(@RequestBody String permissionid,@PathVariable("roleid") String s){
Integer roleid = ParamConverterUtils.restFulConverter(s);
List<Integer> integers = ParamConverterUtils.listJsonConverter(permissionid);
boolean isSuccess = permissionService.addRolePermissions(roleid, integers);
System.out.println("添加许可:"+permissionid);
return isSuccess;
}
/**
*角色维护-更新角色
* @param role
* @return
*/
@ResponseBody
@RequestMapping("/updateRole")
public boolean updateRole(@RequestBody Role role){
System.out.println("修改角色控制层:"+role);
return permissionService.updateRole(role);
}
/**
* 角色维护-新增角色
* @param role
* @return
*/
@ResponseBody
@RequestMapping("/addRole")
public boolean addRole(@RequestBody Role role){
System.out.println("添加角色控制层:"+role);
return permissionService.addRole(role);
}
/**
* 角色维护-条件查询角色
* @param pageBean
* @return
*/
@ResponseBody
@RequestMapping("/conditionSearchRoles")
public PageBean conditionSearchRoles(@RequestBody PageBean pageBean){
pageBean = permissionService.searchRolePageCondition(pageBean);
return pageBean;
}
/**
* 角色维护-查询角色分配许可树
* @param s
* @return
*/
@ResponseBody
@RequestMapping("/searchRolePermissionTree/{roleid}")
public List<PermissionNode> searchRolePermissionTree(@PathVariable("roleid") String s){
Integer roleid = ParamConverterUtils.restFulConverter(s);
System.out.println("roleid:"+roleid);
List<PermissionNode> tree = permissionService.searchPermissionTree();
List<PermissionNode> roleTree = permissionService.searchRolePermissionTree(roleid,tree);
return roleTree;
}
/**
* 跳转许可维护
* @param model
* @return
*/
@RequestMapping("/toPermission")
public String toPermission(Model model){
UserInfoUtils.addUserInfo(model);
return "permission";
}
/**
* 跳转新增许可
* @param model
* @return
*/
@RequestMapping("/toAddPermission")
public String toAddPermission(Model model){
List<Icon> icons = permissionService.findAllIcon();
model.addAttribute("icons",icons);
List<Permission> permissions = permissionService.findAllPermissions();
model.addAttribute("allPermissions",permissions);
UserInfoUtils.addUserInfo(model);
return "addPermission";
}
/**
* 跳转更新许可
* @param s
* @param model
* @return
*/
@RequestMapping("/toUpdatePermission/{name}")
public String toUpdatePermission(@PathVariable("name") String s, Model model){
System.out.println("toUpdatePermission:"+s);
UserInfoUtils.addUserInfo(model);
String name = s.substring(1,s.length()-1);
Permission permission = permissionService.findPermissionByName(name);
model.addAttribute("permission",permission);
List<Icon> icons = permissionService.findAllIcon();
model.addAttribute("icons",icons);
List<Permission> permissions = permissionService.findAllPermissions();
model.addAttribute("allPermissions",permissions);
return "updatePermission";
}
/**
* 许可维护-删除许可
* @param s
* @return
*/
@ResponseBody
@RequestMapping("/deletePermission/{name}")
public boolean deletePermission(@PathVariable("name") String s){
System.out.println("deletePermission:"+s);
String name = s.substring(1,s.length()-1);
return permissionService.deletePermission(name);
}
/**
* 许可维护-更新许可
* @param permission
* @return
*/
@ResponseBody
@RequestMapping("/updatePermission")
public boolean updatePermission(@RequestBody Permission permission){
System.out.println("修改许可控制层:"+permission);
return permissionService.updatePermission(permission);
}
/**
* 许可维护-添加许可
* @param permission
* @return
*/
@ResponseBody
@RequestMapping("/addPermission")
public boolean addPermission(@RequestBody Permission permission){
System.out.println("添加许可控制层:"+permission);
return permissionService.addPermission(permission);
}
/**
* 许可维护-查询许可树
* @return
*/
@ResponseBody
@RequestMapping("/searchPermissionTree")
public List<PermissionNode> searchPermissionTree(){
List<PermissionNode> tree = permissionService.searchPermissionTree();
return tree;
}
}
| true |
9f0452e20d9621211a382cd36cef132a8be9a938 | Java | NotSweet/Get-it | /CampusSQL/Campus/src/dao/UserDao.java | GB18030 | 3,063 | 2.65625 | 3 | [] | no_license | package dao;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import utils.HibernateSessionFactory;
import domain.User;
public class UserDao implements IUserDao {
/* (non-Javadoc)
* @see dao.IUserDao#saveUser(domain.User)
*/
@Override
public void saveUser(User user){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
user.setCreate_time(dateFormat.format(date));
Session session = HibernateSessionFactory.getSession();
Transaction transaction = session.beginTransaction();
session.save(user);
transaction.commit();
session.close();
}
/* (non-Javadoc)
* @see dao.IUserDao#updateUser(domain.User)
*/
@Override
public void updateUser(User user){
Session session = HibernateSessionFactory.getSession();
Transaction transaction = session.beginTransaction();
session.update(user);
transaction.commit();
session.close();
}
/* (non-Javadoc)
* @see dao.IUserDao#findUserById(java.lang.Integer)
*/
public User findUserById(Integer id){
Session session = HibernateSessionFactory.getSession();
Transaction transaction = session.beginTransaction();
User user = (User) session.get(User.class,id);
transaction.commit();
session.close();
return user;
}
/* (non-Javadoc)
* @see dao.IUserDao#deleteUser(domain.User)
*/
@Override
public void deleteUser(User user){
Session session = HibernateSessionFactory.getSession();
Transaction transaction = session.beginTransaction();
session.delete(user);
transaction.commit();
session.close();
}
/* (non-Javadoc)
* @see dao.IUserDao#findAll()
*/
@Override
public List<User> findAll(){
Session session = HibernateSessionFactory.getSession();
Transaction transaction = session.beginTransaction();
//5.1 ʹhqlѯûѯ
String hql="from User";
Query query = session.createQuery(hql);
List<User> list1 = query.list();//ж¼ʹlist
transaction.commit();
session.close();
return list1;
}
/* (non-Javadoc)
* @see dao.IUserDao#findUserByLogin(java.lang.String, java.lang.String)
*/
//public User findUserByLogin(User user)
@Override
public User findUserByLogin(String username,String password){
Session session = HibernateSessionFactory.getSession();
Transaction transaction = session.beginTransaction();
//ûѯû
String hql="from User u where u.username=? and u.password=?";
Query query=session.createQuery(hql);
User user1 = (User) query.setString(0, username).setString(1, password).uniqueResult();
//User user1 = (User) query.setString(0, user.getUsername()).setString(1, user.getPassword()).uniqueResult();
transaction.commit();
HibernateSessionFactory.closeSession();
//session.close();
return user1;
}
}
| true |
e700c7ed007171cb5ebfef937a693559cc21d447 | Java | NikoSnow/Serializacion | /src/java/controlador/ServletP.java | UTF-8 | 3,381 | 2.421875 | 2 | [] | no_license | package controlador;
import dato.Activo;
import dato.Prestamo;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import servicios.Servicios;
/**
*
* @author B106 PC-11
*/
public class ServletP extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String txtActivo = request.getParameter("activo");
String txtCantidad = request.getParameter("cantidad");
Servicios servicio = new Servicios();
if(txtActivo==null && txtCantidad!= null || txtActivo.length()==0){
Activo activo = servicio.buscarActivo(txtActivo);
int cantidad = Integer.parseInt(txtCantidad);
dato.Prestamo prestamo = new dato.Prestamo(activo, cantidad);
//Falta persistir
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(Servlet.class.getName()).log(Level.SEVERE, null, ex);
request.setAttribute("Mensaje", "Problemas para listar los activos");
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| true |
863f633dcdc508f8a5d336cc8c3b0666f2ee277b | Java | sl247223231/R2000Demo | /app/src/main/java/com/uhf/r2000demo/utils/Configs.java | UTF-8 | 4,174 | 1.898438 | 2 | [] | no_license | package com.uhf.r2000demo.utils;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import com.uhf.r2000demo.R;
public class Configs {
//MainActivity
public static final int CONNECT = 0;// 连接页面页码
public static final int INVENTORY = 1;// 盘点页面页码
public static final int SETTING = 2;// 设置页面页码
public static final int POWER = 3;// 功率页面页码
public static final int RW = 4;// 读写页面页码
public static final int PERMISSION = 5;// 权限页面页码
public static final int LOCK = 6;// 锁定页面页码
//连接
public static String companyPower;
public static String serial;
public static final String CONNECT_OFF = "connect_off";// 断开连接
public static final String IS_EXIT = "is_exit";// 退出
public static final String UN_CONNECT = "un_connect";// 退出
public static final String CONNECT_SUCCESS = "connect_success";// 初始化成功
public static final String CONNECT_FAILED = "connect_failed";// 初始化失败
public static final String VERSION = "version";// 初始化失败
// 提示框
public static final String CONNECT_OFFING = "connect_offing";// 正在断开连接
public static final String CONNECT_WORKING = "connect_working";// 正在初始化设备
//盘点
public static final int FLUSH_DATA = 6;// 刷新新数据
public static final int INVENTORY_REFRESH = 1;// 提示刷新
public static final int INVENTORY_START = 222;// 盘点开始
public static final int INVENTORY_STOP = 333;// 盘点停止
public static final int INVENTORY_CLEAR = 555;// 盘点数据清除
//频率
public static final String SET_FREQUENCY_AREA = "set_frequency_area";// 设置频率区域
//功率
public static final String SAVE_POWER_VALUE = "save_power_value";// 功率值保存
//锁定
public static int flag = 0;
//InventoryDialog
public static final String TO_READ_WRITE = "to_read_write";
public static final String TO_LOCK_KILL = "to_lock_kill";
public static final String LABEL_INFO_RW = "label_info_rw";
public static final String LABEL_INFO_LK = "label_info_lk";
public static void send(Handler handler, int what) {
Message msg = new Message();
msg.what = what;
handler.sendMessage(msg);
}
public static void send(Handler handler, int what, int arg1, int arg2, Object obj) {
Message msg = new Message();
msg.what = what;
msg.arg1 = arg1;
msg.arg2 = arg2;
msg.obj = obj;
handler.sendMessage(msg);
}
/**
* 判断十六进制
*/
public static boolean IsHex(String str) {
boolean b = false;
char[] c = str.toUpperCase().toCharArray();
for (char aC : c) {
if ((aC >= '0' && aC <= '9') || (aC >= 'A' && aC <= 'F')) {
b = true;
} else {
b = false;
break;
}
}
return b;
}
/**
* 失败提示音
*
* @param context
*/
public static void callAlarmAsFailure(Context context) {
if (context == null) {
return;
}
AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE); // 播放提示音
int max = audioManager
.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);
int current = audioManager
.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
MediaPlayer player = MediaPlayer.create(context, R.raw.fail);
player.setVolume((float) current / (float) max, (float) current
/ (float) max); // 设置提示音量
player.start();// 播放提示音
}
/**
* 成功提示音
*
* @param context
*/
public static void callAlarmAsSuccess(Context context) {
if (context == null) {
return;
}
AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE); // 播放提示音
int max = audioManager
.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);
int current = audioManager
.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
MediaPlayer player = MediaPlayer.create(context, R.raw.success);
player.setVolume((float) current / (float) max, (float) current
/ (float) max); // 设置提示音量
player.start();// 播放提示音
}
}
| true |
31d1e2dcdef8553edb78e2c8152d5f4be001ec89 | Java | proAhmed/AsynctaskApp | /app/src/main/java/com/skook/skook/model/ContactUsModel.java | UTF-8 | 298 | 2.09375 | 2 | [] | no_license |
package com.skook.skook.model;
import com.google.gson.annotations.SerializedName;
public class ContactUsModel {
@SerializedName("data")
private Data mData;
public Data getData() {
return mData;
}
public void setData(Data data) {
mData = data;
}
}
| true |
e6e0e5b5725d0cee772392d36c2b31f14cf02736 | Java | ZhouSilverBullet/GuardianApp | /app/src/main/java/com/sdxxtop/guardianapp/ui/activity/SafeStaffDetailActivity.java | UTF-8 | 6,412 | 1.828125 | 2 | [] | no_license | package com.sdxxtop.guardianapp.ui.activity;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;
import com.sdxxtop.guardianapp.R;
import com.sdxxtop.guardianapp.base.BaseMvpActivity;
import com.sdxxtop.guardianapp.model.bean.EnterpriseSecurityBean;
import com.sdxxtop.guardianapp.model.bean.GridreportOperatorBean;
import com.sdxxtop.guardianapp.model.bean.TabTextBean;
import com.sdxxtop.guardianapp.presenter.SafeStaffDetailPresenter;
import com.sdxxtop.guardianapp.presenter.contract.SafeStaffDetailContract;
import com.sdxxtop.guardianapp.ui.adapter.SafeStaffDetailAdapter;
import com.sdxxtop.guardianapp.ui.widget.CustomEventLayout;
import com.sdxxtop.guardianapp.ui.widget.GERTimeSelectView;
import com.sdxxtop.guardianapp.ui.widget.TitleView;
import com.sdxxtop.guardianapp.utils.UIUtils;
import java.util.ArrayList;
import java.util.List;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
public class SafeStaffDetailActivity extends BaseMvpActivity<SafeStaffDetailPresenter> implements SafeStaffDetailContract.IView,
CustomEventLayout.OnTabClickListener {
@BindView(R.id.cel_view)
CustomEventLayout celView;
@BindView(R.id.recyclerView)
RecyclerView recyclerView;
@BindView(R.id.tv_name)
TextView tvName;
@BindView(R.id.title)
TitleView title;
@BindView(R.id.gertsv_view)
GERTimeSelectView gertsvView;
private int type;
private int resultId;
List<TabTextBean> list = new ArrayList<>();
private SafeStaffDetailAdapter adapter;
private String event_name;
private String name; // 网格员姓名
private String start_time = "";
private String end_time = "";
@Override
protected int getLayout() {
return R.layout.activity_safe_staff_detail;
}
@Override
protected void initInject() {
getActivityComponent().inject(this);
}
@Override
public void showError(String error) {
celView.setVisibility(View.GONE);
UIUtils.showToast(error);
}
@Override
protected void initData() {
super.initData();
if (type == 1) { // 网格员
mPresenter.gridreportOperator(resultId, "", "");
} else if (type == 2) { // 企业
mPresenter.enterpriseSecurity(resultId, "", "");
}
}
@Override
protected void initView() {
super.initView();
resultId = getIntent().getIntExtra("id", 0);
type = getIntent().getIntExtra("type", 0);
name = getIntent().getStringExtra("name");
if (type == 1) { //网格员
tvName.setText("网格员:" + name);
title.setTitleValue("网格员详情");
list.add(new TabTextBean(1, "--", "上报事件数"));
list.add(new TabTextBean(2, "--", "处理事件数"));
list.add(new TabTextBean(3, "--", "完成事件数"));
list.add(new TabTextBean(4, "--", "打卡数"));
} else if (type == 2) { //企业
tvName.setText(name);
title.setTitleValue("安全员巡逻详情");
list.add(new TabTextBean(1, "--", "安全管理员人数"));
list.add(new TabTextBean(2, "--", "学习培训次数"));
list.add(new TabTextBean(3, "--", "上报自查次数"));
list.add(new TabTextBean(4, "--", "打卡次数"));
}
celView.addLayout(list);
celView.setOnTabClickListener(this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new SafeStaffDetailAdapter(R.layout.item_sfae_staff_view, null);
recyclerView.setAdapter(adapter);
gertsvView.setOnTimeSelectListener(new GERTimeSelectView.OnTimeChooseListener() {
@Override
public void onTimeSelect(String startTime, String endTime) {
start_time = startTime;
end_time = endTime;
if (type == 1) { // 网格员
mPresenter.gridreportOperator(resultId, start_time, end_time);
} else if (type == 2) { // 企业
mPresenter.enterpriseSecurity(resultId, start_time, end_time);
}
}
});
}
@Override
public void onTabClick(int num) {
if (type==1){// 网格员
if (num>1){
return;
}
Intent intent = new Intent(this, GridreportUserreportActivity.class);
intent.putExtra("part_userid", resultId);
intent.putExtra("startTime", start_time);
intent.putExtra("endTime", end_time);
startActivity(intent);
}else if (type==2){// 企业
Intent intent = new Intent(this, SafeStaffDetail2Activity.class);
intent.putExtra("type", type);
intent.putExtra("partId", resultId);
intent.putExtra("title", event_name);
intent.putExtra("startTime", start_time);
intent.putExtra("endTime", end_time);
startActivity(intent);
}
}
@Override
public void showData(EnterpriseSecurityBean bean) {
event_name = bean.getEvent_name();
tvName.setText(event_name);
list.clear();
list.add(new TabTextBean(1, String.valueOf(bean.getUser_count()), "安全管理员人数"));
list.add(new TabTextBean(2, String.valueOf(bean.getTrai_count()), "学习培训次数"));
list.add(new TabTextBean(3, String.valueOf(bean.getReport_info()), "上报自查次数"));
list.add(new TabTextBean(4, String.valueOf(bean.getPart_count()), "打卡次数"));
celView.addLayout(list);
adapter.replaceData(bean.getSign_data());
}
@Override
public void showGridData(GridreportOperatorBean bean) {
tvName.setText("网格员:" + name);
list.clear();
list.add(new TabTextBean(1, String.valueOf(bean.getReport_count()), "上报事件数"));
list.add(new TabTextBean(2, String.valueOf(bean.getAdopt()), "处理事件数"));
list.add(new TabTextBean(3, String.valueOf(bean.getPending()), "完成事件数"));
list.add(new TabTextBean(4, String.valueOf(bean.getPart_count()), "打卡数"));
celView.addLayout(list);
adapter.replaceData(bean.getSign_data());
}
}
| true |
cd22d7506d086165d12c7d6e2750faa1bd1154a6 | Java | MrVladimort/TPO | /Czw/Czw3/src/zad1/Server.java | UTF-8 | 4,084 | 2.96875 | 3 | [] | no_license | package zad1;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.time.LocalDateTime;
import java.time.format.*;
import java.util.*;
public class Server extends JFrame implements Runnable {
private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
private Set<String> connectedClients = new TreeSet<>();
private Selector serverSelector;
private int port;
public static void main(String[] args) {
// Server server = new Server(Integer.parseInt(args[0]));
Server server = new Server(3000);
server.run();
}
private static void log(String str) {
System.out.println("Server: " + str);
}
Server(int port) {
this.port = port;
}
private void handleRequest(String request, SocketChannel client) throws IOException {
String[] commandAndData = request.split("/@/@/@/@/");
String command = commandAndData[0], data = commandAndData[1];
log(command + ": " + data);
switch (command) {
case "login": {
connectedClients.add(data);
log(connectedClients.toString());
broadcast("User " + data + " has joined the channel");
break;
}
case "message": {
broadcast(data);
break;
}
case "logout": {
connectedClients.remove(data);
log(connectedClients.toString());
broadcast("User " + data + " has left the channel");
break;
}
default:
break;
}
}
private void broadcast(String data) throws IOException {
String stringMessage = "[" + dtf.format(LocalDateTime.now()) + "] " + data;
byte[] message = stringMessage.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(message);
for (SelectionKey key : serverSelector.keys()) {
if (key.isValid() && key.channel() instanceof SocketChannel) {
SocketChannel sch = (SocketChannel) key.channel();
sch.write(buffer);
buffer.rewind();
}
}
buffer.clear();
}
@Override
public void run() {
try {
serverSelector = Selector.open();
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.bind(new InetSocketAddress(port));
serverSocketChannel.configureBlocking(false);
int ops = serverSocketChannel.validOps();
serverSocketChannel.register(serverSelector, ops, null);
while (serverSocketChannel.isOpen()) {
serverSelector.select();
Set<SelectionKey> selectionKeys = serverSelector.selectedKeys();
Iterator<SelectionKey> selectionKeyIterator = selectionKeys.iterator();
while (selectionKeyIterator.hasNext()) {
SelectionKey myKey = selectionKeyIterator.next();
if (myKey.isAcceptable()) {
SocketChannel clientChannel = serverSocketChannel.accept();
clientChannel.configureBlocking(false);
clientChannel.register(serverSelector, SelectionKey.OP_READ);
log("Connection Accepted: " + clientChannel.getRemoteAddress());
} else if (myKey.isReadable()) {
SocketChannel clientChannel = (SocketChannel) myKey.channel();
ByteBuffer clientBuffer = ByteBuffer.allocate(2048);
clientChannel.read(clientBuffer);
String result = new String(clientBuffer.array()).trim();
handleRequest(result, clientChannel);
}
selectionKeyIterator.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} | true |
6911f487636e78bc3752a5224ce0f1ecd8fed1fd | Java | pkgod7/j2me-flappybird | /src/Midlet.java | UTF-8 | 383 | 2.140625 | 2 | [] | no_license | import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class Midlet extends MIDlet
{
public FlappyBirdo c1=new FlappyBirdo();
public void startApp()
{
Display.getDisplay(this).setCurrent(c1);
//c1.run();
c1.draw();
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
}
| true |
3f25d14d8de548b0ee2c2b865dbc10dc5a33f209 | Java | IgZhuravlyov/KekToDo | /backend/crud/src/main/java/com/as181/crud/service/HabitService.java | UTF-8 | 235 | 1.890625 | 2 | [] | no_license | package com.as181.crud.service;
import java.util.List;
import com.as181.crud.models.HabitDTO;
public interface HabitService {
public List<HabitDTO> getAllHabits();
public HabitDTO updateHabit(String id, HabitDTO habit);
}
| true |
9df478bbe96dc52132b7685de888d47763da64d0 | Java | TatuPutto/Opinnaytetyo_legacy | /src/tatuputto/opinnaytetyo/connections/HandleLogout.java | UTF-8 | 1,127 | 2.34375 | 2 | [] | no_license | package tatuputto.opinnaytetyo.connections;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Tämä luokka hoitaa uloskirjautumisen.
*/
@WebServlet("/HandleLogout")
public class HandleLogout extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Tuhotaan sessio ja poistetaan eväste.
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getSession(false) != null) {
//Tuhotaan sessio
HttpSession session = request.getSession(false);
session.invalidate();
//Poistetaan access tokenin sisältävä eväste
Cookie tokenCookie = new Cookie("accesstoken", "");
tokenCookie.setMaxAge(0);
response.addCookie(tokenCookie);
response.sendRedirect("http://localhost:8080/Opinnaytetyo/jsps/Login.jsp");
}
}
}
| true |
cb18fa01ba3cef0943122b36150fb7adfd44e756 | Java | prdp89/interview | /src/com/interview/hackerrank/basicPractice/HackerRankInString.java | UTF-8 | 858 | 3.53125 | 4 | [
"Apache-2.0"
] | permissive | package com.interview.hackerrank.basicPractice;
import java.util.Scanner;
public class HackerRankInString {
//https://www.hackerrank.com/challenges/hackerrank-in-a-string/problem
public static void main( String[] args ) {
solve();
}
private static void solve() {
Scanner scanner = new Scanner(System.in);
String s = scanner.next();
String hacker = "hackerrank";
if (hacker.length() > s.length())
System.out.println("NO");
int count = 0;
for (int i = 0, j = 0; i < s.length(); i++) {
if (j < hacker.length() && s.charAt(i) == hacker.charAt(j)) {
count++;
j++;
}
}
if (count == hacker.length())
System.out.println("YES");
else
System.out.println("NO");
}
}
| true |
c6f847cada5bac20093698b670b2eefb59635450 | Java | booksaw/Corruption | /src/com/booksaw/corruption/controls/ControlsManager.java | UTF-8 | 2,744 | 3.0625 | 3 | [] | no_license | package com.booksaw.corruption.controls;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import com.booksaw.corruption.Config;
import com.booksaw.corruption.configuration.YamlConfiguration;
public class ControlsManager {
private static HashMap<String, Control> controls = new HashMap<>();
private static YamlConfiguration yaml;
/**
* Used to load the controls when the program is run
*/
public static void loadControls() {
File f = new File("controls.yaml");
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e1) {
}
try (OutputStream out = new FileOutputStream(f)) {
Files.copy(Paths.get(Config.ASSETSPATH + File.separator + "controls.yaml"), out);
} catch (Exception e) {
System.err.println("could not copy controls file");
}
}
yaml = new YamlConfiguration(f);
// looping through each option
List<String> search = yaml.getOptions("");
for (String str : search) {
List<String> temp = yaml.getOptions(str);
for (String s : temp) {
controls.put(str + "." + s, new Control(str + "." + s, yaml.getString(str + "." + s)));
}
}
}
/**
* Used to get the Control for a reference
*
* @param reference the reference for the key
* @return the Control object of that reference
*/
public static Control getKeyOptions(String reference) {
return controls.get(reference);
}
/**
* Returns if the key linked with that reference is being pressed
*
* @param reference the reference to the key (IE Up)
* @param e The key event to check
* @return if the key is being pressed
*/
public static boolean isKeyUsed(String reference, KeyEvent e) {
Control c = getKeyOptions(reference);
for (int i : c.keys) {
if (e.getKeyCode() == i) {
return true;
}
}
return false;
}
/**
* Returns if the key is linked with the reference is being pressed
*
* @param reference the reference to the key (IE up)
* @param e the key event to check
* @return if they key is being pressed
*/
public static boolean isKeyUsed(ControlList reference, KeyEvent e) {
return isKeyUsed(reference.toString(), e);
}
/**
*
* @return a hashmap of the controls with references
*/
public static HashMap<String, Control> getControls() {
return controls;
}
/**
* Used to save all the loaded controls
*/
public static void save() {
for (Entry<String, Control> temp : controls.entrySet()) {
yaml.set(temp.getKey(), temp.getValue());
}
yaml.saveConfiguration();
}
}
| true |
0b140c1817f6004712095a36838aa57f57ea4752 | Java | OptimistQAQ/SixInchLightServer | /src/main/java/com/example/optimist/SixInchApplication.java | UTF-8 | 444 | 1.679688 | 2 | [
"Apache-2.0"
] | permissive | package com.example.optimist;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author 65667
*/
@SpringBootApplication
@MapperScan("com.example.optimist.mapper")
public class SixInchApplication {
public static void main(String[] args) {
SpringApplication.run(SixInchApplication.class, args);
}
}
| true |
a074ffe5c41b046cc80db108b4c6c66746154d74 | Java | jugo8633/Calendar | /src/com/hp/ij/common/service/baseservice/RetrieveEventCommand.java | UTF-8 | 7,220 | 1.953125 | 2 | [] | no_license | //
// (c) Copyright 2009 Hewlett-Packard Development Company, L.P.
// Confidential computer software. Valid license from HP required for
// possession, use or copying. Consistent with FAR 12.211 and 12.212,
// Commercial Computer Software, Computer Software Documentation, and
// Technical Data for Commercial Items are licensed to the U.S. Government
// under vendor's standard commercial license.
package com.hp.ij.common.service.baseservice;
import java.io.IOException;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import com.hp.ij.common.service.client.IntentCommand;
import com.hp.ij.common.service.gdata.client.calendar.AllEvent;
import com.hp.ij.common.service.gdata.client.calendar.CalendarFeed;
import com.hp.ij.common.service.gdata.client.calendar.CalendarServer;
import com.hp.ij.common.service.gdata.client.calendar.CalendarServerFactory;
import com.hp.ij.common.service.gdata.client.calendar.CalendarState;
import com.hp.ij.common.service.gdata.client.calendar.Event;
import com.hp.ij.common.service.gdata.client.calendar.EventFeed;
import com.hp.ij.common.service.gdata.client.calendar.EventFeedFree;
import com.hp.ij.common.service.gdata.client.calendar.EventFeedProjection;
import com.hp.ij.common.service.gdata.client.calendar.SingleDayEvent;
import com.hp.ij.common.service.gdata.client.calendar.WidgetEvent;
import android.content.Intent;
import android.os.Bundle;
import androidx.LogX;
import androidx.util.TimeZoneUtil;
/**
* Retrieve Events with specify Calendar, Visibility, Projection
*
* @author Luke Liu
*
*/
public class RetrieveEventCommand implements ICommand {
private int intToken;
private BaseService mBaseService;
private CalendarServer mCalendarServer;
/**
* Date start and end.
*/
private String mStrDateStart, mStrDateEnd;
/**
* Which calendar, [{Calendar}, "default"].
*/
private String mStrCalendar;
/**
* Visibility, ["private", "public"].
*/
private String mStrVisibility;
/**
* Calendar projection, ["FULL", "FREE_BUSY"].
*/
private EventFeedProjection mProjection;
/**
* Initialize retrieve event command.
*
* @param strArguments, string index from 0 StrDateStart, StrDateEnd, Calendar, Visibility, Projection.
* @param intToken, token send to Activity.
* @param baseService, pass a BaseService for send Intent.
*/
public RetrieveEventCommand(String[] strArguments, int intToken, BaseService baseService) {
this.intToken = intToken;
this.mBaseService = baseService;
this.mStrDateStart = strArguments[0];
this.mStrDateEnd = strArguments[1];
this.mStrCalendar = strArguments[2];
this.mStrVisibility = strArguments[3];
if(strArguments[4].compareTo("FULL") == 0) this.mProjection = EventFeedProjection.FULL;
else if(strArguments[4].compareTo("FREE_BUSY") == 0) this.mProjection = EventFeedProjection.FREE_BUSY;
else this.mProjection = EventFeedProjection.FULL;
this.mCalendarServer = CalendarServerFactory.getServer(CalendarState.getStrUsername(), CalendarState.getGaiaSession().getToken(), mBaseService);
}
/**
* Iterate all calendars for retrieve its events, then generate a EventFeed[].
*/
public void execute() {
CalendarFeed calendarFeed;
if(CalendarState.getCalendarFeed() == null) return;
else calendarFeed = CalendarState.getCalendarFeed();
EventFeed[] eventFeeds = new EventFeed[calendarFeed.getmCalendars().length];
SingleDayEvent singleDayEvent = null;
try {
/*
* Exclusive all-day events(start:04-27 end:04-28) before today
*/
for (int i = 0; i < eventFeeds.length; i++) {
if(calendarFeed.getmCalendars()[0] == null) return;
String strCalendar = calendarFeed.getmCalendars()[i].getmId();
EventFeed eventFeed = mCalendarServer.getEventFeed(
strCalendar, mStrVisibility, mProjection,
getStrDate(mStrDateStart), getStrDateEnd(mStrDateStart), mBaseService);
LogX.i("Start to query calendar(day view) with date start: " + getStrDate(mStrDateStart) + " date end: " + getStrDateEnd(mStrDateStart));
if(eventFeed != null) {
ArrayList<Event> arrayListOfEvent = new ArrayList<Event>();
for(int j=0; j<eventFeed.getEvents().length; j++) {
if(!eventFeed.getEvents()[j].getWhen().getEndTime().equalsIgnoreCase(mStrDateStart)) {
eventFeed.getEvents()[j].checkEditOrNot(calendarFeed.getmCalendars()[i].getmAccessLevel());
arrayListOfEvent.add(eventFeed.getEvents()[j]);
}
}
Event[] events = arrayListOfEvent.toArray(new Event[0]);
eventFeed.setEvent(events);
eventFeeds[i] = eventFeed;
}
}
singleDayEvent = new SingleDayEvent(eventFeeds);
} catch (IOException e) {
Bundle bundleException = new Bundle();
singleDayEvent = new SingleDayEvent(false, Integer.parseInt(e.getMessage()));
bundleException.putSerializable("Data", singleDayEvent);
Intent intentException = new Intent(IntentCommand.INTENT_ACTION);
intentException.setFlags(IntentCommand.GOOGLE_CALENDAR_RETRIEVE_EVENT);
intentException.putExtras(bundleException);
mBaseService.sendBroadcast(intentException);
return;
}
singleDayEvent.setStrMYearMonthDay(mStrDateStart);
// ----- debug -----
for (int i = 0; i < singleDayEvent.getmEventFeeds().length; i++ ) {
LogX.i("Calendar(Day view): " + singleDayEvent.getmEventFeeds()[i].getTitle());
for (int j = 0; j < singleDayEvent.getmEventFeeds()[i].getEvents().length; j++) {
LogX.i(" Event(Day view): " + singleDayEvent.getmEventFeeds()[i].getEvents()[j].getTitle() + " date start:" + singleDayEvent.getmEventFeeds()[i].getEvents()[j].getWhen().getDateStart() + " date end: " + singleDayEvent.getmEventFeeds()[i].getEvents()[j].getWhen().getDateEnd());
}
}
// ----- debug -----
Bundle bundleSend = new Bundle();
bundleSend.putSerializable("Data", singleDayEvent);
Intent intentSend = new Intent(IntentCommand.INTENT_ACTION);
intentSend.setFlags(IntentCommand.GOOGLE_CALENDAR_RETRIEVE_EVENT);
intentSend.putExtras(bundleSend);
mBaseService.sendBroadcast(intentSend);
}
/**
* Convert "yyyy-MM-dd" to yyyy-MM-ddT00:00:00
*
* @param strDateStart
* @return
*/
public String getStrDate(String strDate) {
StringBuilder stringBuilderDate = new StringBuilder();
stringBuilderDate.append(strDate + "T00:00:00");
stringBuilderDate.append(TimeZoneUtil.getTimeZoneOffset());
return stringBuilderDate.toString();
}
public String getStrDateEnd(String strDate) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = simpleDateFormat.parse(getStrDate(strDate), new ParsePosition(0));
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.setTime(date);
gregorianCalendar.add(Calendar.DAY_OF_MONTH, 1);
gregorianCalendar.add(Calendar.SECOND, -1);
StringBuffer stringBufferDate = new StringBuffer();
simpleDateFormat.format(gregorianCalendar.getTime(), stringBufferDate, new FieldPosition(1));
stringBufferDate.append(TimeZoneUtil.getTimeZoneOffset());
return stringBufferDate.toString();
}
}
| true |
aafcd1662c2e64b610220b5183ec6ba9633ae5a0 | Java | lwj9045/SPA_JAVA | /JAVA_CLASS/src/class072001/BoardDTO.java | UTF-8 | 635 | 2.328125 | 2 | [] | no_license | package class072001;
public class BoardDTO {
private String id = "";
private String pw;
private String contents;
private int number;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPw() {
return pw;
}
public void setPw(String pw) {
this.pw = pw;
}
public String getContents() {
return contents;
}
public void setContents(String contents) {
this.contents = contents;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
BoardDTO() {
}
}
| true |
36ad9b0a771f665ee8be828ddbfc45de663de0e2 | Java | wdw87/wRpc | /src/main/java/com/wdw/wrpc/config/ServerConfig.java | UTF-8 | 536 | 2.21875 | 2 | [
"MIT"
] | permissive | package com.wdw.wrpc.config;
import com.wdw.wrpc.server.netty.NettyServer;
import lombok.Data;
import org.springframework.beans.factory.InitializingBean;
@Data
public class ServerConfig implements InitializingBean {
private String id;
private String ip;
private int port;
private int weight;
@Override
public void afterPropertiesSet() throws Exception {
new Thread(()->{
NettyServer nettyServer = new NettyServer(port, weight);
nettyServer.start();
}).start();
}
}
| true |
aa43a5537876a73c0edcf6e5d73220709d9cbd90 | Java | Hyeonju-Park/admin | /src/admin/controller/Admin_QnaController.java | UTF-8 | 1,201 | 2.296875 | 2 | [] | no_license | package admin.controller;
import java.io.File;
import javax.servlet.http.HttpServlet;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import admin.dao.Admin_FaqDao;
import admin.vo.Admin_FaqVo;
public class Admin_QnaController extends HttpServlet{
req.setCharacterEncoding("utf-8");
String saveDir=getServletContext().getRealPath("/upload");
MultipartRequest mr=new MultipartRequest(req, // request객체
saveDir, //업로드할 디렉토리 경로
1024*1024*5, // 최대 업로드 크기(바이트)
"utf-8", //인코딩방식
new DefaultFileRenamePolicy()//동일한 파일명이 존재할시 파일명뒤에 일련번호(1,2,3,..)을 붙여서 파일 생성
);
String fwriter=req.getParameter("fwriter");
String ftitle=req.getParameter("ftitle");
String fcontent=req.getParameter("fcontent");
String file1=req.getParameter("file1");
String orgFileName=mr.getOriginalFileName("file1");//전송된 파일명
Admin_FaqDao dao=new Admin_FaqDao();
Admin_FaqVo vo=new Admin_FaqVo(0, ftitle, fcontent, 0, null, 0, 0, saveFileName);
File f=new File(saveDir +"\\" + saveFileName);
}
| true |
7e77bee9ab2e62b9a6fad5022939e9d82802045a | Java | bublikdrdrdr/uBublik.Network | /src/main/java/ubublik/network/db/HibernateUtil.java | UTF-8 | 2,991 | 2.34375 | 2 | [] | no_license | package ubublik.network.db;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import ubublik.network.models.*;
import ubublik.network.models.security.Role;
import ubublik.network.models.security.User;
import javax.persistence.EntityManager;
import java.util.HashMap;
import java.util.Map;
public class HibernateUtil {
private static final SessionFactory sessionFactory = getSessionFactory();
private static StandardServiceRegistry registry;
public static SessionFactory getSessionFactory() {
try {
StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
Map<String, String> settings = new HashMap<>();
settings.put(Environment.DRIVER, "com.mysql.jdbc.Driver");
settings.put(Environment.URL, "jdbc:mysql://localhost:3306/network");
settings.put(Environment.USER, "root");
settings.put(Environment.PASS, "root");
settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQLDialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.FORMAT_SQL, "true");
registryBuilder.applySettings(settings);
MetadataSources metadataSources = new MetadataSources(
registryBuilder.build());
//entity classes mapping
metadataSources.addAnnotatedClass(User.class);
metadataSources.addAnnotatedClass(Role.class);
metadataSources.addAnnotatedClass(Profile.class);
metadataSources.addAnnotatedClass(Message.class);
metadataSources.addAnnotatedClass(FriendRelation.class);
metadataSources.addAnnotatedClass(Image.class);
metadataSources.addAnnotatedClass(ProfilePicture.class);
SessionFactory sessionFactory = metadataSources
.getMetadataBuilder().build()
.getSessionFactoryBuilder().build();
return sessionFactory;
} catch (Exception e) {
e.printStackTrace();
if (registry != null) {
StandardServiceRegistryBuilder.destroy(registry);
}
return null;
}
}
public static Session getSession()
throws HibernateException {
if (sessionFactory==null) throw new HibernateException("SessionFactory is null");
return sessionFactory.openSession();
}
public static EntityManager getEntityManager(){
return getSession().getEntityManagerFactory().createEntityManager();
}
} | true |
f7c69ce7380ae5916f7114f1cec902b6dc349bd4 | Java | glookast/glookast-fims-api-test-tool | /src/main/java/com/glookast/fimsclient/app/gui/components/ImportExportButtonPanel.java | UTF-8 | 1,378 | 2.375 | 2 | [
"Apache-2.0"
] | permissive | package com.glookast.fimsclient.app.gui.components;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JPanel;
public class ImportExportButtonPanel extends JPanel
{
private final JButton myImportButton;
private final JButton myExportButton;
public ImportExportButtonPanel(ActionListener actionListener)
{
super(new GridBagLayout());
myImportButton = new JButton("Import");
myImportButton.setActionCommand("Import");
myImportButton.addActionListener(actionListener);
myExportButton = new JButton("Export");
myExportButton.setActionCommand("Export");
myExportButton.addActionListener(actionListener);
GridBagConstraints c = new GridBagConstraints();
c.gridy = 0;
c.insets.right = 5;
add(myImportButton, c);
c.insets.left = 5;
c.insets.right = 0;
add(myExportButton, c);
c.insets.left = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
add(Box.createGlue(), c);
}
public JButton getImportButton()
{
return myImportButton;
}
public JButton getExportButton()
{
return myExportButton;
}
}
| true |
6282b6ba6a83d8b642e093fd1a0a72a5dc211ef3 | Java | dobrivoje/JavaApplication | /src/javaapplication/JavaAppERSTest.java | UTF-8 | 1,549 | 2.4375 | 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 javaapplication;
import ERS.TimeLine.Functionalities.Adapters.FirmaAdapter;
import ERS.TimeLine.Functionalities.ITimeLineCategory;
import ERS.TimeLine.Functionalities.ITimeLineDuration;
import ERS.TimeLine.Functionalities.ITimeLineObservableUnit;
import ERS.queries.ERSQuery;
import java.text.ParseException;
import java.util.Map;
import org.dobrivoje.calendarutilities.DobriKalendar;
/**
*
* @author dobri
*/
public class JavaAppERSTest {
public static void main(String[] args) throws ParseException {
String Datum = DobriKalendar.TODAY_DATE_STR;
ITimeLineObservableUnit OU = new FirmaAdapter(ERSQuery.PODRAZUMEVANA_FIRMA, Datum);
System.err.println("*** " + DobriKalendar.TODAY_DATE_STR);
//Test
for (Map.Entry<ITimeLineCategory, Map<Integer, ITimeLineDuration>> kat : ERSQuery.AllCategoresEvents(OU, Datum).entrySet()) {
String CAT = kat.getKey().getCategory();
Map<Integer, ITimeLineDuration> DOGADJAJI = kat.getValue();
System.out.println(CAT);
for (Map.Entry<Integer, ITimeLineDuration> e1 : DOGADJAJI.entrySet()) {
Integer I = e1.getKey();
ITimeLineDuration D = e1.getValue();
System.out.println(" " + I + " -> " + D);
}
}
}
}
| true |
79b3129d95e00123c878e8b7a1d1c5780a7ed83e | Java | jabautista/GeniisysSCA | /src/main/java/com/geniisys/gipi/service/impl/GIPIMCErrorLogServiceImpl.java | UTF-8 | 2,142 | 2.203125 | 2 | [] | no_license | /**
*
* Project Name: Geniisys Web
* Version:
* Author: Computer Professionals, Inc.
*
*/
package com.geniisys.gipi.service.impl;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.json.JSONException;
import org.json.JSONObject;
import com.geniisys.framework.util.TableGridUtil;
import com.geniisys.gipi.dao.GIPIMCErrorLogDAO;
import com.geniisys.gipi.entity.GIPIMCErrorLog;
import com.geniisys.gipi.service.GIPIMCErrorLogService;
/**
* The Class GIPIMCErrorLogServiceImpl.
*/
public class GIPIMCErrorLogServiceImpl implements GIPIMCErrorLogService {
/** The gipi mc error log dao. */
private GIPIMCErrorLogDAO gipiMCErrorLogDAO;
/* (non-Javadoc)
* @see com.geniisys.gipi.service.GIPIMCErrorLogService#getGipiMCErrorList(java.lang.String)
*/
@Override
public List<GIPIMCErrorLog> getGipiMCErrorList(String fileName) throws SQLException {
return this.getGipiMCErrorLogDAO().getGipiMCErrorList(fileName);
}
/**
* Sets the gipi mc error log dao.
*
* @param gipiMCErrorLogDAO the new gipi mc error log dao
*/
public void setGipiMCErrorLogDAO(GIPIMCErrorLogDAO gipiMCErrorLogDAO) {
this.gipiMCErrorLogDAO = gipiMCErrorLogDAO;
}
/**
* Gets the gipi mc error log dao.
*
* @return the gipi mc error log dao
*/
public GIPIMCErrorLogDAO getGipiMCErrorLogDAO() {
return gipiMCErrorLogDAO;
}
@Override
public JSONObject getGipiMCErrorList2(HttpServletRequest request) throws SQLException,
JSONException, ParseException {
Map<String, Object> params = new HashMap<String, Object>();
params.put("ACTION", "getGipiMCErrorList2");
String fileName = request.getParameter("fileName");
String slashType = (fileName.lastIndexOf("\\") > 0) ? "\\" : "/";// Windows or UNIX
int lastIndexOfSlash = fileName.lastIndexOf(slashType);
params.put("fileName", fileName.substring(lastIndexOfSlash+1));
Map<String, Object> map = TableGridUtil.getTableGrid(request, params);
JSONObject json = new JSONObject(map);
return json;
}
}
| true |
e9b87cc6eac6fa283c62599aedf396f46a441db4 | Java | binzuo/java0924 | /src/zuobin/Test.java | UTF-8 | 724 | 2.890625 | 3 | [] | no_license | package zuobin;
import java.util.logging.XMLFormatter;
/**
* Created by Administrator on 2016/9/24.
*/
public class Test {
//private int x;
//private double y;
public void method(){
int z=10;
System.out.println(z);
// int z=10;
for (x=1;x<10;x++){
System.out.println(x);
}
}
public void method1(){
double y=10.30;
System.out.println(this.y);
}
private int x;
private double y;
// public Test(int x, double y) {
// this.x = x;
//this.y = y;
//}
public static void main(String[] args) {
Test test=new Test();
//test.method1();
System.out.println(test.y);
}
}
| true |
82df40f9ff74881b4d706ef39dec0d17697875c2 | Java | Zachdogg1/Survival-of-the-most-fit | /core/src/com/mygdx/game/randomgeneration.java | UTF-8 | 415 | 2.203125 | 2 | [] | no_license | package com.mygdx.game;
import java.util.Random;
/**
* Created by 256233 on 1/31/2017.
*/
public class randomgeneration {
public static int characters ()
{
Random ch = new Random();
int finished = ch.nextInt(3 );
return finished;
}
public static int music()
{
Random ch = new Random();
int finished = ch.nextInt(4 );
return finished;
}
}
| true |
0bb37aada342bce4e61d1f9d0486b25a2a231a4e | Java | AyoubBenAissaFitA/FitAnalytics-WebWidget-Android | /Tests/TestRunner/src/main/java/com/fitanalytics/TestRunner/MainActivity.java | UTF-8 | 8,070 | 2.046875 | 2 | [
"MIT"
] | permissive | package com.fitanalytics.TestRunner;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.webkit.WebView;
import com.fitanalytics.webwidget.FITAWebWidget;
import com.fitanalytics.webwidget.FITAWebWidgetHandler;
import com.fitanalytics.webwidget.WidgetOptions;
import org.jdeferred.Deferred;
import org.jdeferred.Promise;
import org.jdeferred.android.AndroidDeferredObject;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity implements FITAWebWidgetHandler {
public FITAWebWidgetDriver mWidget;
public WebView mWebView;
private FITAWebWidgetHandler mHandler;
private Deferred readyDeferred = null;
private Deferred initDeferred = null;
private Deferred productLoadDeferred = null;
private Deferred openDeferred = null;
private Deferred closeDeferred = null;
private Deferred recommendDeferred = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//// Testing interface
public Promise initializeWidget() {
// set up the widget webview
mWebView = (WebView) findViewById(R.id.widget_webview);
final MainActivity self = this;
final Deferred def = new AndroidDeferredObject();
mWebView.post(new Runnable() {
@Override
public void run() {
self.mWidget = new FITAWebWidgetDriver(mWebView, self);
def.resolve(self.mWidget);
}
});
return def.promise();
}
public FITAWebWidgetDriver getWidget() {
return mWidget;
}
public Promise evaluateJavaScriptAsync(String code) {
return mWidget.evaluateJavascriptAsync(code);
}
public Promise initializeDriver() {
return mWidget.initializeDriver();
}
// for testing the messaging interface
public Promise sendProductLoadMessage(String productSerial, JSONObject details) {
productLoadDeferred = new AndroidDeferredObject();
JSONArray args = new JSONArray();
args.put(productSerial);
args.put(details);
mWidget.sendCallbackMessage("load", args);
return productLoadDeferred.promise();
}
public Promise widgetLoad() {
readyDeferred = new AndroidDeferredObject();
mWidget.load();
return readyDeferred.promise();
}
public Promise widgetCreate(String productSerial, WidgetOptions options) {
Promise promise;
if (productSerial != null) {
productLoadDeferred = new AndroidDeferredObject();
promise = productLoadDeferred.promise();
} else {
initDeferred = new AndroidDeferredObject();
promise = initDeferred.promise();
}
if (options != null) {
mWidget.create(productSerial, options);
} else if (productSerial != null) {
mWidget.create(productSerial);
} else {
mWidget.create(null);
}
return promise;
}
public Promise widgetOpen(String productSerial, WidgetOptions options) {
openDeferred = new AndroidDeferredObject();
if (options != null) {
mWidget.open(productSerial, options);
} else {
mWidget.open(productSerial);
}
return openDeferred.promise();
}
public Promise widgetReconfigure(String productSerial, WidgetOptions options) {
productLoadDeferred = new AndroidDeferredObject();
if (options != null) {
mWidget.reconfigure(productSerial, options);
} else {
mWidget.reconfigure(productSerial);
}
return productLoadDeferred.promise();
}
public Promise widgetClose() {
closeDeferred = new AndroidDeferredObject();
mWidget.close();
return closeDeferred.promise();
}
public Promise widgetRecommend(String productSerial, WidgetOptions options) {
recommendDeferred = new AndroidDeferredObject();
if (options != null) {
mWidget.recommend(productSerial, options);
} else {
mWidget.recommend(productSerial);
}
return recommendDeferred.promise();
}
//// FITAWebWidgetHandler event callbacks ////
private JSONObject buildArgs(String productSerial, String size, JSONObject details) {
JSONObject args = new JSONObject();
try {
if (productSerial != null)
args.put("productSerial", productSerial);
if (size != null)
args.put("size", size);
if (details != null)
args.put("details", details);
} catch (JSONException e) {};
return args;
}
public void onWebWidgetReady(FITAWebWidget widget) {
Log.d("fitaWidget", "READY");
if (readyDeferred != null) {
readyDeferred.resolve(new JSONObject());
readyDeferred = null;
}
}
public void onWebWidgetInit(FITAWebWidget widget) {
Log.d("fitaWidget", "INIT");
if (initDeferred != null) {
initDeferred.resolve(new JSONObject());
initDeferred = null;
}
}
public void onWebWidgetLoadError(FITAWebWidget widget, String message) {
Log.d("fitaWidget", "LOAD ERROR " + message);
if (productLoadDeferred != null) {
JSONObject details = new JSONObject();
try {
details.put("message", message);
} catch (JSONException e) {};
productLoadDeferred.reject(buildArgs(null, null, details));
productLoadDeferred = null;
}
}
public void onWebWidgetProductLoad(FITAWebWidget widget, String productId, JSONObject details) {
Log.d("fitaWidget", "LOAD " + productId + ", " + (details == null ? "null" : details.toString()));
if (productLoadDeferred != null) {
productLoadDeferred.resolve(buildArgs(productId, null, details));
productLoadDeferred = null;
}
}
public void onWebWidgetProductLoadError(FITAWebWidget widget, String productId, JSONObject details) {
Log.d("fitaWidget", "LOAD ERROR " + productId + ", " + (details == null ? "null" : details.toString()));
if (productLoadDeferred != null) {
productLoadDeferred.reject(buildArgs(productId, null, details));
productLoadDeferred = null;
}
}
public void onWebWidgetOpen(FITAWebWidget widget, String productId) {
Log.d("fitaWidget", "OPEN " + productId);
if (openDeferred != null) {
openDeferred.resolve(buildArgs(productId, null, null));
openDeferred = null;
}
}
public void onWebWidgetClose(FITAWebWidget widget, String productId, String size, JSONObject details) {
Log.d("fitaWidget", "CLOSE " + productId + ", " + size + ", " + (details == null ? "null" : details.toString()));
if (closeDeferred != null) {
closeDeferred.resolve(buildArgs(productId, size, details));
closeDeferred = null;
}
}
public void onWebWidgetAddToCart(FITAWebWidget widget, String productId, String size, JSONObject details) {
Log.d("fitaWidget", "CART " + productId + ", " + size + ", " + (details == null ? "null" : details.toString()));
if (closeDeferred != null) {
closeDeferred.resolve(buildArgs(productId, size, details));
closeDeferred = null;
}
}
public void onWebWidgetRecommend(FITAWebWidget widget, String productId, String size, JSONObject details) {
Log.d("fitaWidget", "RECOMMEND " + productId + ", " + size + ", " + (details == null ? "null" : details.toString()));
if (recommendDeferred != null) {
recommendDeferred.resolve(buildArgs(productId, size, details));
recommendDeferred = null;
}
}
}
| true |
a3f8297089bab2b0b7180bc1eea459bcf325d5ab | Java | EmilCreatePro/Some-Examples-of-OOP-patterns | /Decorator/MakePizza/Pizza.java | UTF-8 | 79 | 2.453125 | 2 | [] | no_license | public interface Pizza
{
public int cost();
public String desc();
} | true |
554361a2aad75354de41c827cfce4e7335b3ec0b | Java | openslice/io.openslice.tmf.api | /src/main/java/io/openslice/tmf/pcm620/api/ProductOfferingApiController.java | UTF-8 | 6,429 | 1.65625 | 2 | [
"Apache-2.0"
] | permissive | /*-
* ========================LICENSE_START=================================
* io.openslice.tmf.api
* %%
* Copyright (C) 2019 openslice.io
* %%
* 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.
* =========================LICENSE_END==================================
*/
package io.openslice.tmf.pcm620.api;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import io.openslice.centrallog.client.CLevel;
import io.openslice.centrallog.client.CentralLogger;
import io.openslice.tmf.pcm620.model.ProductOffering;
import io.openslice.tmf.pcm620.model.ProductOfferingCreate;
import io.openslice.tmf.pcm620.model.ProductOfferingUpdate;
import io.openslice.tmf.pcm620.reposervices.ProductOfferingRepoService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
@jakarta.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2019-10-19T00:15:57.249+03:00")
@Controller
@RequestMapping("/productCatalogManagement/v4/")
public class ProductOfferingApiController implements ProductOfferingApi {
Logger log = LoggerFactory.getLogger(ProductOfferingApiController.class);
private final ObjectMapper objectMapper;
private final HttpServletRequest request;
@Autowired
ProductOfferingRepoService productOfferingRepoService;
@Value("${spring.application.name}")
private String compname;
@Autowired
private CentralLogger centralLogger;
@org.springframework.beans.factory.annotation.Autowired
public ProductOfferingApiController(ObjectMapper objectMapper, HttpServletRequest request) {
this.objectMapper = objectMapper;
this.request = request;
}
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN')" )
@Override
public ResponseEntity<ProductOffering> createProductOffering(@Valid ProductOfferingCreate productOffering) {
try {
ProductOffering c = productOfferingRepoService.addProductOffering(productOffering);
return new ResponseEntity<ProductOffering>(c, HttpStatus.OK);
} catch (Exception e) {
log.error("Couldn't serialize response for content type application/json", e);
return new ResponseEntity<ProductOffering>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN')" )
@Override
public ResponseEntity<Void> deleteProductOffering(String id) {
try {
return new ResponseEntity<Void>(productOfferingRepoService.deleteByUuid(id), HttpStatus.OK);
} catch (Exception e) {
log.error("Couldn't serialize response for content type application/json", e);
return new ResponseEntity<Void>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Override
public ResponseEntity<List<ProductOffering>> listProductOffering(@Valid String fields, @Valid Integer offset,
@Valid Integer limit,
@Valid Map<String, String> allParams) {
try {
if (allParams != null) {
allParams.remove("fields");
allParams.remove("offset");
allParams.remove("limit");
} else {
allParams = new HashMap<>();
}
if ((fields == null) && (allParams.size() == 0)) {
String myfields = "lastUpdate,lifecycleStatus";
return new ResponseEntity<List<ProductOffering>>(
productOfferingRepoService.findAll( myfields, allParams), HttpStatus.OK);
// return new ResponseEntity<List<ServiceSpecification>>(serviceSpecificationRepoService.findAll(),
// HttpStatus.OK);
} else {
return new ResponseEntity<List<ProductOffering>>(
productOfferingRepoService.findAll(fields, allParams), HttpStatus.OK);
}
} catch (Exception e) {
log.error("Couldn't serialize response for content type application/json", e);
return new ResponseEntity<List<ProductOffering>>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN')" )
@Override
public ResponseEntity<ProductOffering> patchProductOffering(String id,
@Valid ProductOfferingUpdate productOffering) {
ProductOffering c = productOfferingRepoService.updateProductOffering(id, productOffering);
return new ResponseEntity<ProductOffering>(c, HttpStatus.OK);
}
@Override
public ResponseEntity<ProductOffering> retrieveProductOffering(String id, @Valid String fields) {
try {
Object attr = request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
if ( attr!=null) {
SecurityContextHolder.setContext( (SecurityContext) attr );
}
if ( SecurityContextHolder.getContext().getAuthentication() != null ) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
centralLogger.log( CLevel.INFO, "User " + authentication.getName() + " retrieve spec id: "+ id , compname );
} else {
centralLogger.log( CLevel.INFO, "Anonymous retrieve spec id: "+ id, compname );
}
return new ResponseEntity<ProductOffering>(productOfferingRepoService.findByUuid(id),
HttpStatus.OK);
} catch (Exception e) {
log.error("Couldn't serialize response for content type application/json", e);
return new ResponseEntity<ProductOffering>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
| true |
ddd99352c8d623eba9c0690940f2820d8194bfc7 | Java | Glebanister/server-comparasion | /src/main/java/server/ClientAcceptingServer.java | UTF-8 | 4,216 | 2.65625 | 3 | [] | no_license | package server;
import logger.ContextLogger;
import protocol.ListTransferringProtocol;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public abstract class ClientAcceptingServer extends ArraySortingServer {
private final List<ClientHandler> clients;
private final ExecutorService clientTaskExecutor;
private final Lock serverServeLock = new ReentrantLock();
private final Condition serverServed = serverServeLock.newCondition();
private boolean isServerServed = false;
public ClientAcceptingServer(ListTransferringProtocol protocol,
int port,
int taskExecutorThreads,
boolean logInfo) {
super(protocol, port, logInfo);
this.clients = new ArrayList<>();
this.clientTaskExecutor = Executors.newFixedThreadPool(taskExecutorThreads);
}
public ClientAcceptingServer(ListTransferringProtocol protocol,
int port,
boolean logInfo) {
this(protocol, port, Runtime.getRuntime().availableProcessors(), logInfo);
}
public void submitClientTask(Runnable task) {
clientTaskExecutor.submit(task);
}
protected abstract ClientHandler makeClientHandler(SocketChannel channel);
@Override
public void run() {
super.run();
serverLogger.info("Running");
try (ServerSocketChannel serverSocket = ServerSocketChannel.open()) {
serverSocket.bind(new InetSocketAddress(getPort()));
serverLogger.info("Bound to port");
serverServeLock.lock();
try {
isServerServed = true;
serverServed.signal();
} finally {
serverServeLock.unlock();
}
while (running()) {
try {
ClientHandler handler = makeClientHandler(serverSocket.accept());
serverLogger.info(String.format("Client connected: %s", handler.socket.getRemoteAddress()));
clients.add(handler);
handler.handle();
} catch (ClosedByInterruptException ignored) {
serverLogger.info("Server interrupted");
close();
}
}
} catch (IOException e) {
serverLogger.handleException(e);
}
}
@Override
public void awaitServed() {
serverServeLock.lock();
try {
while (!isServerServed) {
serverServed.await();
}
} catch (InterruptedException ignored) {
} finally {
serverServeLock.unlock();
}
}
@Override
public void close() throws IOException {
serverLogger.info("Closing");
super.close();
for (ClientHandler client : clients) {
client.close();
}
clientTaskExecutor.shutdownNow();
try {
if (!clientTaskExecutor.awaitTermination(2, TimeUnit.SECONDS)) {
throw new RuntimeException("Client task executor won't close");
}
} catch (InterruptedException ignored) {
}
serverLogger.info("Closed");
}
public abstract static class ClientHandler {
protected final SocketChannel socket;
protected final ContextLogger handlerLogger;
protected ClientHandler(SocketChannel socket, boolean logInfo) {
this.socket = socket;
this.handlerLogger = new ContextLogger("ClientHandler", logInfo);
}
public abstract void handle();
public void close() throws IOException {
socket.close();
}
}
}
| true |
8844bbe2af689cc7c8823505d4005f1e97c67bf9 | Java | RxL-Yogesh-Kumar/javaassi | /retain.java | UTF-8 | 643 | 2.953125 | 3 | [] | no_license | package com.company;
import java.net.StandardSocketOptions;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer>list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
System.out.println("list 1:"+list1);
ArrayList<Integer>list2= new ArrayList<Integer>();
list2.add(5);
list2.add(16);
list2.add(7);
list2.add(1);
System.out.println("list 2:"+list2);
list1.retainAll(list2);
System.out.println("common element :" +list1);
}
}
| true |
6158d3abd775896c8e30ed168463216196be1ad4 | Java | VoltK/Moviefier | /app/src/main/java/com/khud44/moviefier/utils/ThisWeek.java | UTF-8 | 948 | 3.046875 | 3 | [] | no_license | package com.khud44.moviefier.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class ThisWeek {
private static ThisWeek thisWeekInstance = null;
private String firstDayOfWeek;
private String lastDayOfWeek;
private ThisWeek(){
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, cal.MONDAY);
firstDayOfWeek = String.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
cal.add(Calendar.DAY_OF_WEEK, 6);
lastDayOfWeek = String.valueOf(new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
}
public static ThisWeek getInstance()
{
if (thisWeekInstance == null)
thisWeekInstance = new ThisWeek();
return thisWeekInstance;
}
public String getFirstDayOfWeek(){
return firstDayOfWeek;
}
public String getLastDayOfWeek(){
return lastDayOfWeek;
}
}
| true |
522e6f6afc8b669f6329875e2b5003a01befcede | Java | Agomnimedia/bremen-gtug | /projects/2012_02_18_GADC/MultiPlayerLabyrinth/src/org/gtugs/bremen/multilabyrinth/scene/impl/DefaultTheme.java | UTF-8 | 3,697 | 2.3125 | 2 | [] | no_license | package org.gtugs.bremen.multilabyrinth.scene.impl;
import java.io.IOException;
import org.andengine.audio.sound.Sound;
import org.andengine.audio.sound.SoundFactory;
import org.andengine.audio.sound.SoundManager;
import org.andengine.engine.Engine;
import org.andengine.opengl.texture.TextureManager;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.util.debug.Debug;
import org.gtugs.bremen.multilabyrinth.scene.api.Theme;
import android.content.Context;
public class DefaultTheme implements Theme{
private BitmapTextureAtlas bitmapTextureAtlas;
private ITextureRegion ballRegion;
private ITextureRegion trapRegion;
private ITextureRegion startRegion;
private ITextureRegion endRegion;
private ITextureRegion particleRegion;
private Sound trapSound;
private Sound hitWallSound;
private Sound finishBallSound;
public DefaultTheme(final Context context, final TextureManager textureManager, final SoundManager soundManager){
/* Textures. */
this.bitmapTextureAtlas = new BitmapTextureAtlas(textureManager, 64, 96, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
/* TextureRegions. */
this.ballRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.bitmapTextureAtlas, context, "ball.png", 0, 0);
this.trapRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.bitmapTextureAtlas, context, "trap.png", 32, 0);
this.startRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.bitmapTextureAtlas, context, "start.png", 0, 32);
this.endRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.bitmapTextureAtlas, context, "end.png", 0, 64);
this.particleRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.bitmapTextureAtlas, context, "particle_fire.png", 32, 64);
createSounds(context, soundManager);
}
private void createSounds(final Context context, final SoundManager soundManager) {
SoundFactory.setAssetBasePath("sfx/");
try {
this.trapSound = SoundFactory.createSoundFromAsset(soundManager, context, "trap.ogg");
this.hitWallSound = SoundFactory.createSoundFromAsset(soundManager, context, "hitWall.ogg");
this.finishBallSound = SoundFactory.createSoundFromAsset(soundManager, context, "finishBall.ogg");
} catch (final IOException e) {
Debug.e(e);
}
}
@Override
public BitmapTextureAtlas getBitmapTextureAtlas() {
return this.bitmapTextureAtlas;
}
@Override
public ITextureRegion getBallRegion() {
return this.ballRegion;
}
@Override
public ITextureRegion getTrapRegion() {
return this.trapRegion;
}
@Override
public ITextureRegion getStartRegion() {
return this.startRegion;
}
@Override
public ITextureRegion getEndRegion() {
return this.endRegion;
}
@Override
public ITextureRegion getParticleRegion() {
return this.particleRegion;
}
@Override
public Sound getTrapSound() {
return this.trapSound;
}
@Override
public Sound getHitWallSound() {
return this.hitWallSound;
}
@Override
public Sound getFinishBallSound() {
return this.finishBallSound;
}
@Override
public void loadTheme(final Engine engine) {
// load atlas
engine.getTextureManager().loadTexture(this.bitmapTextureAtlas);
}
} | true |
658b8aa3cb7852e969737a000a26f7efb2847432 | Java | zhongxingyu/Seer | /Diff-Raw-Data/3/3_0674b893e8b4501dfa7ed73eda65995f255d0185/ConnectionManager/3_0674b893e8b4501dfa7ed73eda65995f255d0185_ConnectionManager_s.java | UTF-8 | 21,170 | 1.640625 | 2 | [] | no_license | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldapbrowser.core;
import java.beans.ExceptionListener;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.directory.studio.ldapbrowser.core.events.BookmarkUpdateEvent;
import org.apache.directory.studio.ldapbrowser.core.events.BookmarkUpdateListener;
import org.apache.directory.studio.ldapbrowser.core.events.ConnectionRenamedEvent;
import org.apache.directory.studio.ldapbrowser.core.events.ConnectionUpdateEvent;
import org.apache.directory.studio.ldapbrowser.core.events.ConnectionUpdateListener;
import org.apache.directory.studio.ldapbrowser.core.events.EventRegistry;
import org.apache.directory.studio.ldapbrowser.core.events.SearchUpdateEvent;
import org.apache.directory.studio.ldapbrowser.core.events.SearchUpdateListener;
import org.apache.directory.studio.ldapbrowser.core.internal.model.Bookmark;
import org.apache.directory.studio.ldapbrowser.core.internal.model.Connection;
import org.apache.directory.studio.ldapbrowser.core.internal.model.Search;
import org.apache.directory.studio.ldapbrowser.core.model.BookmarkParameter;
import org.apache.directory.studio.ldapbrowser.core.model.ConnectionParameter;
import org.apache.directory.studio.ldapbrowser.core.model.IBookmark;
import org.apache.directory.studio.ldapbrowser.core.model.IConnection;
import org.apache.directory.studio.ldapbrowser.core.model.ISearch;
import org.apache.directory.studio.ldapbrowser.core.model.SearchParameter;
import org.apache.directory.studio.ldapbrowser.core.model.schema.Schema;
import org.apache.directory.studio.ldapbrowser.core.utils.LdifUtils;
import org.eclipse.core.runtime.IPath;
/**
* This class is used to manage {@link IConnection}s.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
public class ConnectionManager implements ConnectionUpdateListener, SearchUpdateListener, BookmarkUpdateListener
{
/** The list of connections. */
private List<IConnection> connectionList;
/**
* Creates a new instance of ConnectionManager.
*/
public ConnectionManager()
{
this.connectionList = new ArrayList<IConnection>();
loadConnections();
EventRegistry.addConnectionUpdateListener( this, BrowserCorePlugin.getDefault().getEventRunner() );
EventRegistry.addSearchUpdateListener( this, BrowserCorePlugin.getDefault().getEventRunner() );
EventRegistry.addBookmarkUpdateListener( this, BrowserCorePlugin.getDefault().getEventRunner() );
}
/**
* Gets the Schema Cache filename for the corresponding Connection name.
*
* @param connectionName
* the connection name
* @return
* the Schema Cache filename for the corresponding Connection name
*/
public static final String getSchemaCacheFileName( String connectionName )
{
return BrowserCorePlugin.getDefault().getStateLocation().append(
"schema-" + toSaveString( connectionName ) + ".ldif" ).toOSString(); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Gets the Modification Log filename for the corresponding Connection name.
*
* @param connectionName
* the connection name
* @return
* the Modification Log filename
*/
public static final String getModificationLogFileName( String connectionName )
{
IPath p = BrowserCorePlugin.getDefault().getStateLocation().append( "logs" ); //$NON-NLS-1$
File file = p.toFile();
if ( !file.exists() )
{
file.mkdir();
}
return p.append( "modifications-" + toSaveString( connectionName ) + "-%u-%g.ldiflog" ).toOSString(); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Gets the filename of the Connection Store.
*
* @return
* the filename of the Connection Store
*/
public static final String getConnectionStoreFileName()
{
String filename = BrowserCorePlugin.getDefault().getStateLocation().append( "connections.xml" ).toOSString(); //$NON-NLS-1$
File file = new File( filename );
if ( !file.exists() )
{
// try to convert old connections.xml:
// 1st search it in current workspace with the old ldapstudio plugin ID
// 2nd search it in old .ldapstudio workspace with the old ldapstudio plugin ID
String[] oldFilenames = new String[2];
oldFilenames[0] = filename.replace( "org.apache.directory.studio.ldapbrowser.core",
"org.apache.directory.ldapstudio.browser.core" );
oldFilenames[1] = oldFilenames[0].replace( ".ApacheDirectoryStudio",
".ldapstudio" );
for ( int i = 0; i < oldFilenames.length; i++ )
{
File oldFile = new File( oldFilenames[i] );
if ( oldFile.exists() )
{
try
{
String oldContent = FileUtils.readFileToString( oldFile, "UTF-8" );
String newContent = oldContent.replace( "org.apache.directory.ldapstudio.browser.core",
"org.apache.directory.studio.ldapbrowser.core" );
FileUtils.writeStringToFile( file, newContent, "UTF-8" );
break;
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
}
return filename;
}
/**
* Converts a String into a Saveable String.
*
* @param s
* the String to convert
* @return
* the converted String
*/
private static String toSaveString( String s )
{
if ( s == null )
{
return null;
}
byte[] b = LdifUtils.utf8encode( s );
StringBuffer sb = new StringBuffer();
for ( int i = 0; i < b.length; i++ )
{
if ( b[i] == '-' || b[i] == '_' || ( '0' <= b[i] && b[i] <= '9' ) || ( 'A' <= b[i] && b[i] <= 'Z' )
|| ( 'a' <= b[i] && b[i] <= 'z' ) )
{
sb.append( ( char ) b[i] );
}
else
{
int x = ( int ) b[i];
if ( x < 0 )
x = 256 + x;
String t = Integer.toHexString( x );
if ( t.length() == 1 )
t = "0" + t; //$NON-NLS-1$
sb.append( t );
}
}
return sb.toString();
}
/**
* Adds the connection to the end of the connection list. If there is
* already a connection with this name, the new connection is renamed.
*
* @param connection
*/
public void addConnection( IConnection connection )
{
addConnection( connectionList.size(), connection );
}
/**
* Adds the connection at the specified position of the connection list.
* If there is already a connection with this name the new connection is
* renamed.
*
* @param index
* @param connection
*/
public void addConnection( int index, IConnection connection )
{
if ( getConnection( connection.getName() ) != null )
{
String newConnectionName = BrowserCoreMessages.bind( BrowserCoreMessages.copy_n_of_s,
"", connection.getName() ); //$NON-NLS-1$
for ( int i = 2; getConnection( newConnectionName ) != null; i++ )
{
newConnectionName = BrowserCoreMessages.bind( BrowserCoreMessages.copy_n_of_s,
i + " ", connection.getName() ); //$NON-NLS-1$
}
connection.getConnectionParameter().setName( newConnectionName );
}
connectionList.add( index, connection );
EventRegistry.fireConnectionUpdated( new ConnectionUpdateEvent( connection,
ConnectionUpdateEvent.EventDetail.CONNECTION_ADDED ), this );
}
/**
* Gets a connection from its name.
*
* @param name
* the name of the Connection
* @return
* the corresponding Connection
*/
public IConnection getConnection( String name )
{
for ( Iterator it = connectionList.iterator(); it.hasNext(); )
{
IConnection conn = ( IConnection ) it.next();
if ( conn.getName().equals( name ) )
{
return conn;
}
}
return null;
}
/**
* Gets the index in the Connection list of the first occurrence of the specified Connection.
*
* @param connection
* the Connection to search for
* @return
* the index in the Connection list of the first occurrence of the specified Connection
*/
public int indexOf( IConnection connection )
{
return connectionList.indexOf( connection );
}
/**
* Removes the given Connection from the Connection list.
*
* @param conn
* the connection to remove
*/
public void removeConnection( IConnection conn )
{
connectionList.remove( conn );
EventRegistry.fireConnectionUpdated( new ConnectionUpdateEvent( conn,
ConnectionUpdateEvent.EventDetail.CONNECTION_REMOVED ), this );
}
/**
* Gets an array containing all the Connections.
*
* @return
* an array containing all the Connections
*/
public IConnection[] getConnections()
{
return ( IConnection[] ) connectionList.toArray( new IConnection[0] );
}
/**
* Gets the number of Connections.
*
* @return
* the number of Connections
*/
public int getConnectionCount()
{
return connectionList.size();
}
/**
* {@inheritDoc}
*/
public void connectionUpdated( ConnectionUpdateEvent connectionUpdateEvent )
{
if ( connectionUpdateEvent.getDetail() == ConnectionUpdateEvent.EventDetail.CONNECTION_ADDED
|| connectionUpdateEvent.getDetail() == ConnectionUpdateEvent.EventDetail.CONNECTION_REMOVED
|| connectionUpdateEvent.getDetail() == ConnectionUpdateEvent.EventDetail.CONNECTION_RENAMED
|| connectionUpdateEvent.getDetail() == ConnectionUpdateEvent.EventDetail.CONNECTION_PARAMETER_UPDATED )
{
saveConnections();
}
if ( connectionUpdateEvent instanceof ConnectionRenamedEvent )
{
String oldName = ( ( ConnectionRenamedEvent ) connectionUpdateEvent ).getOldName();
String newName = connectionUpdateEvent.getConnection().getName();
String oldSchemaFile = getSchemaCacheFileName( oldName );
String newSchemaFile = getSchemaCacheFileName( newName );
File oldFile = new File( oldSchemaFile );
File newFile = new File( newSchemaFile );
if ( oldFile.exists() )
{
oldFile.renameTo( newFile );
}
}
if ( connectionUpdateEvent.getDetail() == ConnectionUpdateEvent.EventDetail.SCHEMA_LOADED
|| connectionUpdateEvent.getDetail() == ConnectionUpdateEvent.EventDetail.CONNECTION_OPENED )
{
saveSchema( connectionUpdateEvent.getConnection() );
}
if ( connectionUpdateEvent.getDetail() == ConnectionUpdateEvent.EventDetail.CONNECTION_REMOVED )
{
File file = new File( getSchemaCacheFileName( connectionUpdateEvent.getConnection().getName() ) );
if ( file.exists() )
{
file.delete();
}
}
}
/**
* {@inheritDoc}
*/
public void searchUpdated( SearchUpdateEvent searchUpdateEvent )
{
if ( searchUpdateEvent.getDetail() == SearchUpdateEvent.EventDetail.SEARCH_ADDED
|| searchUpdateEvent.getDetail() == SearchUpdateEvent.EventDetail.SEARCH_REMOVED
|| searchUpdateEvent.getDetail() == SearchUpdateEvent.EventDetail.SEARCH_RENAMED
|| searchUpdateEvent.getDetail() == SearchUpdateEvent.EventDetail.SEARCH_PARAMETER_UPDATED )
{
saveConnections();
}
}
/**
* {@inheritDoc}
*/
public void bookmarkUpdated( BookmarkUpdateEvent bookmarkUpdateEvent )
{
if ( bookmarkUpdateEvent.getDetail() == BookmarkUpdateEvent.Detail.BOOKMARK_ADDED
|| bookmarkUpdateEvent.getDetail() == BookmarkUpdateEvent.Detail.BOOKMARK_REMOVED
|| bookmarkUpdateEvent.getDetail() == BookmarkUpdateEvent.Detail.BOOKMARK_UPDATED )
{
saveConnections();
}
}
/**
* Saves the Connections
*/
private void saveConnections()
{
Object[][] object = new Object[connectionList.size()][3];
Iterator connectionIterator = connectionList.iterator();
for ( int i = 0; connectionIterator.hasNext(); i++ )
{
IConnection conn = ( IConnection ) connectionIterator.next();
ConnectionParameter connectionParameters = conn.getConnectionParameter();
ISearch[] searches = conn.getSearchManager().getSearches();
SearchParameter[] searchParameters = new SearchParameter[searches.length];
for ( int k = 0; k < searches.length; k++ )
{
searchParameters[k] = searches[k].getSearchParameter();
}
IBookmark[] bookmarks = conn.getBookmarkManager().getBookmarks();
BookmarkParameter[] bookmarkParameters = new BookmarkParameter[bookmarks.length];
for ( int k = 0; k < bookmarks.length; k++ )
{
bookmarkParameters[k] = bookmarks[k].getBookmarkParameter();
}
object[i][0] = connectionParameters;
object[i][1] = searchParameters;
object[i][2] = bookmarkParameters;
}
save( object, getConnectionStoreFileName() );
}
/**
* Saves the Schema of the Connection
*
* @param connection
* the Connection
*/
private void saveSchema( IConnection connection )
{
try
{
String filename = getSchemaCacheFileName( connection.getName() );
FileWriter writer = new FileWriter( filename );
connection.getSchema().saveToLdif( writer );
writer.close();
}
catch ( Exception e )
{
e.printStackTrace();
}
}
/**
* Loads the Connections
*/
private void loadConnections()
{
try
{
Object[][] object = ( Object[][] ) this.load( getConnectionStoreFileName() );
if ( object != null )
{
try
{
for ( int i = 0; i < object.length; i++ )
{
IConnection conn = new Connection();
ConnectionParameter connectionParameters = ( ConnectionParameter ) object[i][0];
conn.setConnectionParameter( connectionParameters );
if ( object[i].length > 1 )
{
SearchParameter[] searchParameters = ( SearchParameter[] ) object[i][1];
for ( int k = 0; k < searchParameters.length; k++ )
{
ISearch search = new Search( conn, searchParameters[k] );
conn.getSearchManager().addSearch( search );
}
}
if ( object[i].length > 2 )
{
BookmarkParameter[] bookmarkParameters = ( BookmarkParameter[] ) object[i][2];
for ( int k = 0; k < bookmarkParameters.length; k++ )
{
IBookmark bookmark = new Bookmark( conn, bookmarkParameters[k] );
conn.getBookmarkManager().addBookmark( bookmark );
}
}
try
{
String schemaFilename = getSchemaCacheFileName( conn.getName() );
FileReader reader = new FileReader( schemaFilename );
Schema schema = new Schema();
schema.loadFromLdif( reader );
conn.setSchema( schema );
}
catch ( Exception e )
{
}
connectionList.add( conn );
}
}
catch ( ArrayIndexOutOfBoundsException e )
{
// Thrown by decoder.readObject(), signals EOF
}
catch ( Exception e )
{
e.printStackTrace();
}
}
}
catch ( Exception e )
{
}
}
/**
* Loads an Object from an XML file
*
* @param filename
* the filename of the XML file
* @return
* the deserialized Object
*/
private synchronized Object load( String filename )
{
try
{
Thread.currentThread().setContextClassLoader( getClass().getClassLoader() );
XMLDecoder decoder = new XMLDecoder( new BufferedInputStream( ( new FileInputStream( filename ) ) ) );
Object object = decoder.readObject();
decoder.close();
return object;
}
catch ( IOException ioe )
{
return null;
}
catch ( Exception e )
{
e.printStackTrace();
return null;
}
}
/**
* Saves an Object into a serialized XML file
*
* @param object
* the object to save
* @param filename
* the filename to save to
*/
private synchronized void save( Object object, String filename )
{
XMLEncoder encoder = null;
try
{
// to avoid a corrupt file, save object to a temp file first
String tempFilename = filename + "-temp";
Thread.currentThread().setContextClassLoader( getClass().getClassLoader() );
encoder = new XMLEncoder( new BufferedOutputStream( new FileOutputStream( tempFilename ) ) );
encoder.setExceptionListener( new ExceptionListener()
{
public void exceptionThrown( Exception e )
{
e.printStackTrace();
}
} );
encoder.writeObject( object );
// move temp file to good file
File file = new File( filename );
File tempFile = new File( tempFilename );
if( file.exists() ) {
file.delete();
}
tempFile.renameTo( file );
}
catch ( Exception e )
{
e.printStackTrace();
}
finally
{
if ( encoder != null )
{
encoder.close();
}
}
}
}
| true |
2a35d6d700fb3562d50ce1349557b8a846c0d092 | Java | atteo/dollarbrace | /dollarbrace/src/main/java/org/atteo/dollarbrace/PropertyNotFoundException.java | UTF-8 | 1,957 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2011 Atteo.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.atteo.dollarbrace;
/**
* Returned when property with the given name is not found.
*/
@SuppressWarnings("serial")
public class PropertyNotFoundException extends Exception {
private final String propertyName;
public PropertyNotFoundException(String propertyName) {
this.propertyName = propertyName;
}
public PropertyNotFoundException(String propertyName, Throwable cause) {
super(cause);
this.propertyName = propertyName;
}
public PropertyNotFoundException(String propertyName, PropertyNotFoundException cause) {
this.propertyName = propertyName;
if ( cause != null && !propertyName.equals(cause.propertyName)) {
initCause(cause);
}
}
public String getPropertyName() {
return propertyName;
}
@Override
public String getMessage() {
StringBuilder sb = new StringBuilder();
sb.append("'").append(propertyName).append("'");
Throwable cause = getCause();
String lastProperty = null;
while (cause != null) {
if (cause instanceof PropertyNotFoundException) {
lastProperty =((PropertyNotFoundException) cause).propertyName;
sb.append(" -> '").append(lastProperty).append("'");
}
cause = cause.getCause();
}
if (lastProperty == null) {
sb.insert(0, "Property not found: ");
} else {
sb.insert(0, "Property not found: '" + lastProperty + "' [");
sb.append("]");
}
return sb.toString();
}
}
| true |
31aaaab0714403a37fade88934d8c614d6defdf7 | Java | keerthucit/Toitnext2.8 | /src-pos/com/openbravo/pos/sales/restaurant/JRetailBufferWindow.java | UTF-8 | 4,316 | 2.265625 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.openbravo.pos.sales.restaurant;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;
/**
*
* @author shilpa
*/
//Class to show buffer popup
public class JRetailBufferWindow extends javax.swing.JDialog {
int x = 500;
int y = 300;
int width = 350;
int height = 220;
/**
* Creates new form JRetailBufferWindow
*/
public JRetailBufferWindow(java.awt.Frame frame, boolean modal) {
super(frame, true);
setBounds(x, y, width, height);
}
private JRetailBufferWindow(Dialog dialog, boolean b) {
super(dialog, true);
setBounds(x, y, width, height);
}
public static void showMessage(Component parent) {
Window window = getWindow(parent);
JRetailBufferWindow myMsg;
if (window instanceof Frame) {
myMsg = new JRetailBufferWindow((Frame) window, true);
} else {
myMsg = new JRetailBufferWindow((Dialog) window, true);
}
myMsg.loadContent();
}
public void loadContent() {
initComponents();
RefreshTickets autoRefresh = new RefreshTickets();
//timer to show popup for only 1 sec
Timer timer = new Timer(1000, autoRefresh);
//dont repeat th timer
timer.setRepeats(false);
timer.start();
setVisible(true);
}
private static Window getWindow(Component parent) {
if (parent == null) {
return new JFrame();
} else if (parent instanceof Frame || parent instanceof Dialog) {
return (Window) parent;
} else {
return getWindow(parent.getParent());
}
}
private class RefreshTickets implements ActionListener {
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("inside refresh");
setVisible(false);
dispose();
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/loading.gif"))); // NOI18N
jLabel2.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
jLabel2.setForeground(new java.awt.Color(251, 161, 58));
jLabel2.setText(" The table is being accessed by another User!");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
.addComponent(jLabel1)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
// End of variables declaration//GEN-END:variables
}
| true |
13538b9fd30c55cc7cb98ec3e9bd9dd99dc54296 | Java | JusofunAppMobile/GXCAndroid | /app/src/main/java/com/jusfoun/jusfouninquire/net/model/SearchContactListModel.java | UTF-8 | 897 | 1.789063 | 2 | [] | no_license | package com.jusfoun.jusfouninquire.net.model;
import java.io.Serializable;
import java.util.List;
public class SearchContactListModel extends BaseModel implements Serializable {
public int totalCount;
public List<DataBean> data;
public static class DataBean implements Serializable {
/**
* id : 7727314
* type : 个体工商户
* operatingPeriodStart : null
* establishDate : 1268668800000
* legalPerson : 王芳芳
* name : 百度面馆
* phone : 15109774464,18946877680
*/
public String id;
public String type;
public Object operatingPeriodStart;
public String establishDate;
public String legalPerson;
public String name;
public List<String> phoneArr;
public boolean isOpen = false;
public boolean isSelect = false;
}
}
| true |