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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
658071230e994cf8da18019321f6c531169c324c | Java | xyggs/MVVM-Base | /base/src/main/java/com/android/base/ui/BaseActivity.java | UTF-8 | 2,613 | 2.359375 | 2 | [] | no_license | package com.android.base.ui;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;
import com.android.base.R;
import com.android.base.bean.Event;
import com.android.base.util.AppManager;
import com.android.base.util.EventBusUtil;
import com.android.base.util.StatusBarHelper;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
/**
* Created by android on 2019/7/5
*/
public abstract class BaseActivity extends AppCompatActivity implements LifecycleOwner {
public BaseActivity activity;
public Context context;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
activity = this;
context = this;
if (getContentViewId() != 0) {
setContentView(getContentViewId());
}
initData();
initView();
initListener();
if (isRegisterEventBus()) {
EventBusUtil.register(this);
}
AppManager.getAppManager().addActivity(activity);
}
@Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
setStatusBar();
}
protected void setStatusBar(){
StatusBarHelper.setStatusBar(activity, ContextCompat.getColor(context,R.color.white));
}
protected abstract int getContentViewId();
protected abstract void initData();
protected abstract void initView();
protected abstract void initListener();
/**
* 是否注册事件分发
*
* @return true绑定EventBus事件分发,默认不绑定,子类需要绑定的话复写此方法返回true.
*/
protected boolean isRegisterEventBus() {
return false;
}
//接收到分发到事件再转发
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventBusCome(Event event) {
if (event != null) {
receiveEvent(event);
}
}
/**
* 收到转发
*
* @param event 事件
*/
protected void receiveEvent(Event event) {
}
@Override
protected void onDestroy() {
super.onDestroy();
AppManager.getAppManager().finishActivity(activity);
if (isRegisterEventBus()) {
EventBusUtil.unregister(this);
}
}
}
| true |
71e7f48bfaf14bff68dc98ac4496e4f5b126e4e1 | Java | zhouchao4664/spring-boot-demo | /jsoup-demo/src/main/java/com/zhouchao/domain/Shop.java | UTF-8 | 836 | 1.90625 | 2 | [] | no_license | package com.zhouchao.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
/**
* <p>
*
* </p>
*
* @author zhouchao
* @since 2022-01-01
*/
@Data
@TableName("shop")
public class Shop implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@TableField("house_id")
private String houseId;
@TableField("shop_name")
private String shopName;
@TableField("address")
private String address;
@TableField("price")
private String price;
@TableField("url")
private String url;
}
| true |
d5d38d873ae097d2f922daaf745583e088540eed | Java | PangyiGo/lampblack-admin | /lampblack-common/src/main/java/com/osen/cloud/common/enums/InfoMessage.java | UTF-8 | 1,604 | 2.328125 | 2 | [] | no_license | package com.osen.cloud.common.enums;
import com.osen.cloud.common.utils.ConstUtil;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
/**
* User: PangYi
* Date: 2019-08-28
* Time: 17:46
* Description: 统一信息体
*/
@NoArgsConstructor
@AllArgsConstructor
public enum InfoMessage {
/**
* 异常信息体
*/
UnknownSystem_Error(ConstUtil.UNOK, "系统未知异常"),
NoFound_Error(ConstUtil.UNOK, "页面不存在"),
InsertUser_Error(ConstUtil.UNOK, "账号重复添加"),
InsertDevice_Error(ConstUtil.UNOK, "设备ID重复添加"),
/**
* 成功信息体
*/
Success_OK(ConstUtil.OK, "请求成功"),
Failed_Error(ConstUtil.UNOK, "请求失败"),
Refresh_Failed(ConstUtil.UNOK, "令牌刷新异常"),
/**
* 提示信息体
*/
User_Need_Authorization(ConstUtil.UNOK, "用户未登录"),
User_Login_Failed(ConstUtil.UNOK, "账号或密码错误"),
User_Login_Success(ConstUtil.OK, "登录成功"),
User_NO_Access(ConstUtil.UNOK, "用户无权访问"),
User_Logout_Success(ConstUtil.OK, "用户已成功退出登录"),
User_Logout_Failed(ConstUtil.UNOK, "退出登录异常"),
User_Login_Guoqi(ConstUtil.UNOK, "登录状态过期");
private Integer code;
private String message;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| true |
0613016e26cebfade8ccde7ec045b1cf0dbfe6ae | Java | mgsx-dev/rainstick | /core/src/net/mgsx/rainstick/model/Rainstick.java | UTF-8 | 428 | 2.234375 | 2 | [
"Apache-2.0"
] | permissive | package net.mgsx.rainstick.model;
public class Rainstick {
public String title = "";
public String credits = "";
public String path = "";
public String preview = "";
public String description = "";
public void set(Rainstick rainstick) {
this.title = rainstick.title;
this.credits = rainstick.credits;
this.path = rainstick.path;
this.preview = rainstick.preview;
this.description = rainstick.description;
}
}
| true |
738255872f3b2bbf5f9c29bd92752aa9258b8dcc | Java | tbs005/BikeServer | /src/main/java/org/ccframe/subsys/core/search/MemberAccountSearchRepository.java | UTF-8 | 431 | 1.726563 | 2 | [] | no_license | package org.ccframe.subsys.core.search;
import java.util.List;
import org.ccframe.subsys.core.domain.entity.MemberAccount;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface MemberAccountSearchRepository extends ElasticsearchRepository<MemberAccount, Integer> {
public List<MemberAccount> findByUserIdAndOrgIdAndAccountTypeCode(Integer userId, Integer orgId, String code);
}
| true |
563cec0cd3586757af382b6907d17468fb41d67b | Java | rs1907/softwareentwicklung | /src/main/java/de/fham/softwareentwicklung/zwei/stack/StackInterface.java | UTF-8 | 155 | 2.140625 | 2 | [] | no_license | package de.fham.softwareentwicklung.zwei.stack;
public interface StackInterface {
boolean isEmpty();
void push(String i);
String pop();
}
| true |
a61adb7fc4116c4aeb526ec8bbd8a4cebc8af59f | Java | Carl-K/Trading-System | /Project/src/messages/FillMessage.java | UTF-8 | 792 | 2.8125 | 3 | [] | no_license | package messages;
import customExceptions.InvalidEnumException;
//import customExceptions.InvalidPriceOperation;
import customExceptions.InvalidVolumeException;
import price.Price;
import enums.BookSide;
public class FillMessage extends Messages implements Comparable<FillMessage> {
public FillMessage(String userIn, String productIn, Price priceIn, int volumeIn, String detailsIn, BookSide sideIn, String idIn) throws InvalidVolumeException, InvalidEnumException {
super(userIn, productIn, priceIn, volumeIn, detailsIn, sideIn, idIn);
}
public int compareTo(FillMessage o) {
/*
try //this is bad
{
return getPrice().compareTo( o.getPrice() ) ;
}
catch ( InvalidPriceOperation e )
{
}
return 0;
*/
return getPrice().compareTo( o.getPrice() ) ;
}
}
| true |
a04821df8fe5aada8a4432688ebb4b48fe7361e3 | Java | Terasology/Dialogs | /src/main/java/org/terasology/dialogs/DialogScreen.java | UTF-8 | 3,011 | 1.875 | 2 | [
"Apache-2.0"
] | permissive | // Copyright 2021 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.terasology.dialogs;
import com.google.common.collect.Lists;
import org.terasology.dialogs.action.PlayerAction;
import org.terasology.engine.entitySystem.entity.EntityRef;
import org.terasology.engine.rendering.assets.texture.TextureRegion;
import org.terasology.engine.rendering.nui.CoreScreenLayer;
import org.terasology.engine.rendering.nui.widgets.browser.data.html.HTMLDocument;
import org.terasology.engine.rendering.nui.widgets.browser.ui.BrowserWidget;
import org.terasology.gestalt.assets.ResourceUrn;
import org.terasology.nui.UIWidget;
import org.terasology.nui.databinding.ReadOnlyBinding;
import org.terasology.nui.layouts.ColumnLayout;
import org.terasology.nui.widgets.UIButton;
import org.terasology.nui.widgets.UIImage;
import java.util.List;
public class DialogScreen extends CoreScreenLayer {
public static final ResourceUrn ASSET_URI = new ResourceUrn("Dialogs:DialogScreen");
private ColumnLayout responseButtons;
private ColumnLayout responseImage;
private BrowserWidget browser;
private final HTMLDocument emptyPage = new HTMLDocument(null);
@Override
public void initialise() {
responseButtons = find("responseButtons", ColumnLayout.class);
responseImage = find("responseImage", ColumnLayout.class);
browser = find("browser", BrowserWidget.class);
}
@Override
public boolean isModal() {
return true;
}
public void setDocument(HTMLDocument documentData) {
browser.navigateTo(documentData);
}
public void reset() {
browser.navigateTo(emptyPage);
for (UIWidget widget : Lists.newArrayList(responseButtons)) {
responseButtons.removeWidget(widget);
}
for (UIWidget widget : Lists.newArrayList(responseImage)) {
responseImage.removeWidget(widget);
}
// // HACK! implement ColumnLayout.removeWidget()
// Iterator<UIWidget> it = responseButtons.iterator();
// while (it.hasNext()) {
// it.next();
// it.remove();
// }
}
public void addResponseOption(EntityRef charEnt, EntityRef talkTo, String text, TextureRegion image,
List<PlayerAction> actions) {
UIButton newButton = new UIButton();
UIImage newImage = new UIImage();
newButton.setText(text);
newImage.setImage(image);
newImage.setFamily("imageColumn");
newImage.bindVisible(new ReadOnlyBinding<>() {
@Override
public Boolean get() {
return newButton.getMode().equals(UIButton.HOVER_MODE);
}
});
newButton.subscribe(widget -> {
for (PlayerAction action : actions) {
action.execute(charEnt, talkTo);
}
});
responseImage.addWidget(newImage, null);
responseButtons.addWidget(newButton, null);
}
}
| true |
7ded6064eba2053a04053f09a90b1bb507c8158d | Java | fpellegrinet/university_app | /University/app/src/main/java/com/university/ui/OptionsList.java | UTF-8 | 1,148 | 2.21875 | 2 | [] | no_license | package com.university.ui;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import com.university.R;
import com.university.domain.User;
public class OptionsList extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options_list);
Intent intent = getIntent();
User user = (User) intent.getSerializableExtra("user");
String[] activities = intent.getStringArrayExtra("activityList");
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
}
};
RelativeLayout activityList = (RelativeLayout)findViewById(R.id.activityList);
for (String activity : activities) {
Button button = new Button(this);
button.setText(activity);
button.setOnClickListener(onClickListener);
activityList.addView(button);
}
}
}
| true |
526d93bfab9d5638b0b2f0fa2b218eb689411d6d | Java | ninthworld/CAGE | /src/cage/core/scene/SceneNode.java | UTF-8 | 2,412 | 2.6875 | 3 | [
"MIT"
] | permissive | package cage.core.scene;
import cage.core.model.Model;
import cage.core.scene.camera.OrthographicCamera;
import cage.core.scene.camera.PerspectiveCamera;
import cage.core.scene.light.AmbientLight;
import cage.core.scene.light.DirectionalLight;
import cage.core.scene.light.PointLight;
public class SceneNode extends Node {
private SceneManager sceneManager;
public SceneNode(SceneManager sceneManager, Node parent) {
super(parent);
this.sceneManager = sceneManager;
}
public SceneNode createSceneNode() {
SceneNode node = new SceneNode(sceneManager, this);
return node;
}
public SceneEntity createSceneEntity(Model model) {
SceneEntity node = new SceneEntity(sceneManager, this, model);
return node;
}
public PerspectiveCamera createPerspectiveCamera() {
PerspectiveCamera camera = new PerspectiveCamera(sceneManager, this);
camera.setSize(getSceneManager().getWindow().getWidth(), getSceneManager().getWindow().getHeight());
camera.setSizableParent(getSceneManager().getWindow());
getSceneManager().registerCamera(camera);
return camera;
}
public OrthographicCamera createOrthographicCamera() {
OrthographicCamera camera = new OrthographicCamera(sceneManager, this);
addNode(camera);
getSceneManager().registerCamera(camera);
return camera;
}
public AmbientLight createAmbientLight() {
AmbientLight light = new AmbientLight(sceneManager, this);
getSceneManager().registerLight(light);
return light;
}
public PointLight createPointLight() {
PointLight light = new PointLight(sceneManager, this);
getSceneManager().registerLight(light);
return light;
}
public DirectionalLight createDirectionalLight() {
DirectionalLight light = new DirectionalLight(sceneManager, this);
getSceneManager().registerLight(light);
return light;
}
public SceneManager getSceneManager() {
return sceneManager;
}
public void setSceneManager(SceneManager sceneManager) {
this.sceneManager = sceneManager;
}
@Override
public void destroy() {
if(getParentNode() != null) {
getParentNode().removeNode(this);
}
}
}
| true |
e3f4f9768747a714c3222a125cb05fbc05a9a121 | Java | tianhongbo/CMPE275_Lab2 | /src/main/java/edu/sjsu/cmpe275/lab2/dao/OrgDao.java | UTF-8 | 879 | 2.109375 | 2 | [] | no_license | package edu.sjsu.cmpe275.lab2.dao;
import edu.sjsu.cmpe275.lab2.model.Organization;
/**
* Project Name: cmpe275lab2
* Packet Name: edu.sjsu.cmpe275.lab2.dao
* Author: Scott
* Created Date: 11/5/15 4:53 PM
* Copyright (c) 2015, 2015 All Right Reserved, http://sjsu.edu/
* This source is subject to the GPL2 Permissive License.
* Please see the License.txt file for more information.
* All other rights reserved.
* <p>
* THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
* PARTICULAR PURPOSE.
*/
public interface OrgDao {
public void create(Organization organization);
public Organization get(long id);
public Organization update(Organization organization);
public Organization delete(long id);
}
| true |
86e62b345d08456729a41f949d03ceba36db7f29 | Java | elvionania/Chess | /Chess/src/org/elvio/chess/process/Joueur.java | UTF-8 | 1,249 | 2.9375 | 3 | [] | no_license | package org.elvio.chess.process;
import org.elvio.chess.elements.Board;
import org.elvio.chess.elements.pieces.Piece;
import org.elvio.chess.time.IGestionDuTemps;
public abstract class Joueur {
protected Byte couleur;
protected IGestionDuTemps temps;
protected long tempsAuCommencement;
public void setCouleur(byte couleur) {
this.couleur = couleur;
}
public void setTempsCourant(long milliSeconde){
temps.setTempsCourant(milliSeconde - this.tempsAuCommencement);
}
public byte getCouleur() {
return this.couleur;
}
public boolean isBlanc() {
return Piece.isBlanc(couleur);
}
public boolean isNoir() {
return !Piece.isBlanc(couleur);
}
public IGestionDuTemps getTemps(){
return temps;
}
public abstract Board jouer(Board board, int numeroDuCoup);
public void setTempsAuCommencement(long tempsAuCommencement) {
this.tempsAuCommencement = tempsAuCommencement;
}
public Byte getCouleurDeLAutreJoueur(){
return this.getCouleur() == Piece.BLANC ? Piece.NOIR : Piece.BLANC;
}
}
| true |
2f877360fe4b179ea6e18371dc9f591d8ee0ae72 | Java | jmg216/tsi2-g1-2012 | /GeoRed-Business-JPA/src/com/geored/dominio/Evento.java | UTF-8 | 2,536 | 2.03125 | 2 | [] | no_license | package com.geored.dominio;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
@Entity
@Table(name="evento")
public class Evento implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 7607595252285552941L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="ID", nullable=false)
private Long id;
@Column(name="NOMBRE", nullable=false)
private String nombre;
@Column(name="DESCRIPCION", nullable=false)
private String descripcion;
@Column(name="UBICACION_GEOGRAFICA", nullable=false)
private String ubicacionGeografica;
@Column(name="FECHA_INICIO", nullable=false)
private Timestamp fechaInicio;
@Column(name="FECHA_FIN", nullable=false)
private Timestamp fechaFin;
@ManyToMany(fetch=FetchType.LAZY)
@JoinTable(name="evento_tematica",
joinColumns =
{
@JoinColumn(name = "EVENTO_FK")
},
inverseJoinColumns =
{
@JoinColumn(name = "TEMATICA_FK")
})
private List<Tematica> listaTematicas;
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getNombre()
{
return nombre;
}
public void setNombre(String nombre)
{
this.nombre = nombre;
}
public String getDescripcion()
{
return descripcion;
}
public void setDescripcion(String descripcion)
{
this.descripcion = descripcion;
}
public String getUbicacionGeografica()
{
return ubicacionGeografica;
}
public void setUbicacionGeografica(String ubicacionGeografica)
{
this.ubicacionGeografica = ubicacionGeografica;
}
public Timestamp getFechaInicio()
{
return fechaInicio;
}
public void setFechaInicio(Timestamp fechaInicio)
{
this.fechaInicio = fechaInicio;
}
public Timestamp getFechaFin()
{
return fechaFin;
}
public void setFechaFin(Timestamp fechaFin)
{
this.fechaFin = fechaFin;
}
public List<Tematica> getListaTematicas()
{
return listaTematicas;
}
public void setListaTematicas(List<Tematica> listaTematicas)
{
this.listaTematicas = listaTematicas;
}
} | true |
f39762d2e7d14b2d0ff8ddd2c6388b977f2f9a38 | Java | PranilDahal/Catering-Management-App | /src/DatabaseConfig.java | UTF-8 | 307 | 1.867188 | 2 | [] | no_license |
public class DatabaseConfig {
public static final String MYSQL_HOST = "server name";
public static final String MYSQL_USERNAME = "user";
public static final String MYSQL_PASSWORD = "password";
public static final int MYSQL_PORT = 3306;
public static final String MYSQL_DATABASE_TO_USE = "schema";
}
| true |
72bc68aae19b2a1f1720c613d8d74e297e43a091 | Java | Gopinath9/new | /One/Ten.java | UTF-8 | 213 | 2.453125 | 2 | [] | no_license |
public class Ten {
int a=2;
int b=0;
public static void main(String[] args) {
try {
c=a/b;
}catch(ArithmeticException e)
System.err.println("exception occured:"+c);
}
}
| true |
92d9b3c0a026e2b1d2f01c076d4e903d41b9a46a | Java | shuixingge/WeEat | /app/src/main/java/com/bupt/weeat/presenter/WeekRankPresenter.java | UTF-8 | 3,193 | 2 | 2 | [] | no_license | package com.bupt.weeat.presenter;
import android.content.Context;
import com.bupt.weeat.apis.DishApi;
import com.bupt.weeat.apis.RxService.WeekRankDishService;
import com.bupt.weeat.model.entity.DishBean;
import com.bupt.weeat.model.entity.Window;
import com.bupt.weeat.model.response.WeekRankDishResponse;
import com.bupt.weeat.utils.LogUtils;
import com.bupt.weeat.view.mvpView.DishBeanListView;
import java.util.List;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
/**
* Created by zhaoruolei1992 on 2016/5/22.
*/
public class WeekRankPresenter extends BasePresenter<DishBeanListView> {
private Subscription mSubscription;
private WeekRankDishService service;
public WeekRankPresenter(Context context) {
service = DishApi.createApi(context, WeekRankDishService.class);
}
public void loadList(final int page) {
checkViewAttached();
mSubscription = service.getWeekRankList()
.subscribeOn(Schedulers.io())
.map(new Func1<WeekRankDishResponse, List<DishBean>>() {
@Override
public List<DishBean> call(WeekRankDishResponse response) {
List<Window> windows = response.getData().getWindows();
List<DishBean> beans = response.getData().getDishes();
for (int i = 0; i < beans.size(); i++) {
DishBean bean = beans.get(i);
DishBean.DishWindow window = new DishBean.DishWindow();
window.setName(windows.get(i).getWindow_Cover().getName());
bean.setDish_Window(window);
}
return beans;
}
})
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<DishBean>>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(List<DishBean> beanList) {
if (page == 1) {
getMvpView().refresh(beanList);
LogUtils.i("tag", beanList.toString());
} else {
getMvpView().loadMore(beanList);
}
}
});
}
@Override
public void attachView(DishBeanListView mvpView) {
super.attachView(mvpView);
}
@Override
public void detachView() {
super.detachView();
if (mSubscription != null) mSubscription.unsubscribe();
}
@Override
public boolean isViewAttached() {
return super.isViewAttached();
}
@Override
public DishBeanListView getMvpView() {
return super.getMvpView();
}
@Override
public void checkViewAttached() {
super.checkViewAttached();
}
}
| true |
97cf71fb6b0cb1f749041664c4b854e1e72bc01a | Java | AngelRawencraw/DMOJ-stuff | /ccc04j3.java | UTF-8 | 764 | 2.921875 | 3 | [
"MIT"
] | permissive | import java.util.Scanner;
/**
* Created by edwinfinch on 14-11-12.
*/
public class Main {
static public void main(String wussup[]){
Scanner scanner = new Scanner(System.in);
int amountOfAdj = scanner.nextInt();
int amountOfNoun = scanner.nextInt();
String[] adjs = new String[amountOfAdj];
String[] nouns = new String[amountOfNoun];
for(int i = 0; i < amountOfAdj; i++){
adjs[i] = scanner.next();
}
for(int i = 0; i < amountOfNoun; i++){
nouns[i] = scanner.next();
}
for(int i = 0; i < amountOfAdj; i++){
for(int j = 0; j < amountOfNoun; j++){
System.out.println(adjs[i] + " as " + nouns[j]);
}
}
}
}
| true |
38279c4d7dc2f6c97b7cc31e2a9f3ec015d2a460 | Java | rickdynasty/TwsPluginFramework | /TwsPluginShareLib/src/main/java/com/tencent/tws/assistant/interpolator/BaseInterpolator.java | UTF-8 | 442 | 2.4375 | 2 | [] | no_license | package com.tencent.tws.assistant.interpolator;
import android.view.animation.Interpolator;
public abstract class BaseInterpolator implements Interpolator{
@Override
public float getInterpolation(float input) {
float t = 100 * input;
float b = 0f;
float c = 1.0f;
float d = 100;
return calculate(t, b, c, d);
}
public abstract Float calculate(float t, float b, float c, float d);
}
| true |
e36d848cadac65c9316b5e0c2fe8b5dc16d65c81 | Java | natanaelafonso/metro_cptm | /src/br/com/natanael/task/EnviaMensagemGCMServerTask.java | ISO-8859-1 | 3,065 | 2.375 | 2 | [] | no_license | package br.com.natanael.task;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.atomic.AtomicInteger;
import javax.net.ssl.HttpsURLConnection;
import br.com.natanael.Application.GCMApplication;
import br.com.natanael.gcm.Constantes;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
public class EnviaMensagemGCMServerTask extends AsyncTask<Void, Void, String>{
private GCMApplication app;
private static final String REGISTRATION_ID = "registrationId";
AtomicInteger msgId = new AtomicInteger();
public EnviaMensagemGCMServerTask (GCMApplication app){
this.app = app;
}
@Override
protected String doInBackground(Void... params) {
String registrationID = this.app.getSharedPreferences("configs", Activity.MODE_PRIVATE).getString(REGISTRATION_ID, null);
if(registrationID != null){
/*Bundle data = new Bundle();
data.putString("my_message", "Hello World");
data.putString("my_action",
"com.google.android.gcm.demo.app.ECHO_NOW");
String id = Integer.toString(msgId.incrementAndGet());
try{
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this.app);
gcm.send(Constantes.GCM_SERVER_ID + "@gcm.googleapis.com", id, data);
Log.i("GCM_SERVER_MSG","Enviando requisio ao GCM Server:\n"+id+"\n"+data);
}catch(Exception e){
Log.e("GCM_SEND_MSG","Erro ao enviar requisio ao servidor! "+e.getMessage());
}
try{
String msgJson = "{\"data\": { \"mensagem\":\"Mensagem de Teste\"},\"registration_ids\":[\"" + registrationID
+"\"]}";
byte[] data = msgJson.getBytes("UTF-8");
URL url = new URL(
"https://android.googleapis.com/gcm/send");
HttpsURLConnection conexao =
(HttpsURLConnection)url.openConnection();
conexao.addRequestProperty("Authorization",
"key="+"AIzaSyCQctafU1AteIHxHhDf-0hB4-fcXn-oUfU");
conexao.addRequestProperty(
"Content-Type", "application/json");
conexao.setRequestMethod("POST");
conexao.setDoOutput(true);
conexao.setUseCaches(false);
conexao.connect();
OutputStream os = conexao.getOutputStream();
os.write(data);
os.close();
if (conexao.getResponseCode() == HttpURLConnection.HTTP_OK){
Log.i("GCM_SEND_MSG","Mensagem enviada");
} else {
Log.e("GCM_SEND_MSG","Erro ao enviar requisio ao servidor! "+ conexao.getResponseCode() +" - "+conexao.getResponseMessage());
}
}catch(Exception e){
Log.e("GCM_SEND_MSG","Erro ao enviar requisio ao servidor! "+e.getMessage());
}*/
}else{
Log.e("GCM_SERVER_MSG","RegistrationID nulo");
}
Log.i("GCM_SERVER_MSG","Requisio ao GCM Server enviada");
return null;
}
}
| true |
090d00e000b2d77295f590337efbd45faffa7417 | Java | ericknavarro97/covid19api | /src/main/java/com/ericknavarro/covidapi/controllers/EquipamientoController.java | UTF-8 | 2,432 | 2.203125 | 2 | [] | no_license | package com.ericknavarro.covidapi.controllers;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ericknavarro.covidapi.models.Equipamiento;
import com.ericknavarro.covidapi.models.Hospital;
import com.ericknavarro.covidapi.service.EquipamientoService;
import lombok.AllArgsConstructor;
@RestController
@RequestMapping("/${api.version}/equipamientos")
@AllArgsConstructor
public class EquipamientoController {
private EquipamientoService service;
@GetMapping
public ResponseEntity<List<Equipamiento>> findAllEquipamientos() {
return new ResponseEntity<>(service.findAllEquipamientos(), HttpStatus.OK);
}
@GetMapping("/{id}")
public ResponseEntity<Equipamiento> findEquipamientoById(@PathVariable("id") Integer equipamientoId) {
return new ResponseEntity<>(service.findEquipamientoById(equipamientoId), HttpStatus.OK);
}
@PostMapping("/{id}/hospitales")
public ResponseEntity<Equipamiento> addHospitalToEquipamiento(@PathVariable("id") Integer equipamientoId, @RequestBody Hospital hospital){
return new ResponseEntity<Equipamiento>(service.addHospitalToEquipamiento(equipamientoId, hospital.getHospitalId()), HttpStatus.OK);
}
@PostMapping
public ResponseEntity<Equipamiento> saveEquipamiento(@RequestBody Equipamiento equipamiento) {
return new ResponseEntity<>(service.saveEquipamiento(equipamiento), HttpStatus.CREATED);
}
@PutMapping("/{id}")
public ResponseEntity<Equipamiento> updateEquipamiento(@PathVariable("id") Integer equipamientoId, @RequestBody Equipamiento equipamiento) {
return new ResponseEntity<>(service.updateEquipamiento(equipamientoId, equipamiento), HttpStatus.OK);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteEquipamiento(@PathVariable("id") Integer equipamientoId) {
service.deleteEquipamiento(equipamientoId);
return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
}
}
| true |
7137840521c36cc32dcbea7bd9e9bab24711ca12 | Java | ialazzon/ComponentAllocationProblem | /ComponentAllocationProblem/src/componentAllocation/impl/ComponentImpl.java | UTF-8 | 6,520 | 1.65625 | 2 | [] | no_license | /**
*/
package componentAllocation.impl;
import componentAllocation.Component;
import componentAllocation.ComponentAllocationPackage;
import componentAllocation.ResConsumption;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Component</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link componentAllocation.impl.ComponentImpl#getCompName <em>Comp Name</em>}</li>
* <li>{@link componentAllocation.impl.ComponentImpl#getResConsumptions <em>Res Consumptions</em>}</li>
* </ul>
*
* @generated
*/
public class ComponentImpl extends MinimalEObjectImpl.Container implements Component {
/**
* The default value of the '{@link #getCompName() <em>Comp Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCompName()
* @generated
* @ordered
*/
protected static final String COMP_NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getCompName() <em>Comp Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCompName()
* @generated
* @ordered
*/
protected String compName = COMP_NAME_EDEFAULT;
/**
* The cached value of the '{@link #getResConsumptions() <em>Res Consumptions</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getResConsumptions()
* @generated
* @ordered
*/
protected EList<ResConsumption> resConsumptions;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ComponentImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return ComponentAllocationPackage.Literals.COMPONENT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getCompName() {
return compName;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCompName(String newCompName) {
String oldCompName = compName;
compName = newCompName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ComponentAllocationPackage.COMPONENT__COMP_NAME,
oldCompName, compName));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<ResConsumption> getResConsumptions() {
if (resConsumptions == null) {
resConsumptions = new EObjectWithInverseResolvingEList<ResConsumption>(ResConsumption.class, this,
ComponentAllocationPackage.COMPONENT__RES_CONSUMPTIONS,
ComponentAllocationPackage.RES_CONSUMPTION__COMPONENT);
}
return resConsumptions;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case ComponentAllocationPackage.COMPONENT__RES_CONSUMPTIONS:
return ((InternalEList<InternalEObject>) (InternalEList<?>) getResConsumptions()).basicAdd(otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case ComponentAllocationPackage.COMPONENT__RES_CONSUMPTIONS:
return ((InternalEList<?>) getResConsumptions()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ComponentAllocationPackage.COMPONENT__COMP_NAME:
return getCompName();
case ComponentAllocationPackage.COMPONENT__RES_CONSUMPTIONS:
return getResConsumptions();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ComponentAllocationPackage.COMPONENT__COMP_NAME:
setCompName((String) newValue);
return;
case ComponentAllocationPackage.COMPONENT__RES_CONSUMPTIONS:
getResConsumptions().clear();
getResConsumptions().addAll((Collection<? extends ResConsumption>) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ComponentAllocationPackage.COMPONENT__COMP_NAME:
setCompName(COMP_NAME_EDEFAULT);
return;
case ComponentAllocationPackage.COMPONENT__RES_CONSUMPTIONS:
getResConsumptions().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ComponentAllocationPackage.COMPONENT__COMP_NAME:
return COMP_NAME_EDEFAULT == null ? compName != null : !COMP_NAME_EDEFAULT.equals(compName);
case ComponentAllocationPackage.COMPONENT__RES_CONSUMPTIONS:
return resConsumptions != null && !resConsumptions.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy())
return super.toString();
StringBuilder result = new StringBuilder(super.toString());
result.append(" (compName: ");
result.append(compName);
result.append(')');
return result.toString();
}
} //ComponentImpl
| true |
e6e5c8a159cddb20ebc6d25515e0d985cd20e541 | Java | icorecool/smart-NetLight | /src/com/example/android/BluetoothChat/GroupDBHelper.java | UTF-8 | 2,814 | 2.546875 | 3 | [] | no_license | package com.example.android.BluetoothChat;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class GroupDBHelper extends SQLiteOpenHelper {
private final static String DATABASE_NAME = "group_addr.db";
private final static int DATABASE_VERSION = 1;
private final static String TABLE_NAME = "group_addr";
public final static String GROUP_ID = "_id";
public final static String GROUP_NAME = "name";
public final static String GROUP_ADDR = "address";
public final static String GROUP_LEAF = "leaf";
Context context;
SQLiteDatabase groupDB;
public GroupDBHelper(Context context) {
// TODO Auto-generated constructor stub
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// 创建table
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLE_NAME + " (" + GROUP_ID
+ " INTEGER primary key autoincrement, " + GROUP_NAME
+ " text, " + GROUP_ADDR
+ " text, "+ GROUP_LEAF + " text);";
db.execSQL(sql);
}
public void openDataBase(GroupDBHelper helper){
groupDB = helper.getWritableDatabase();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "DROP TABLE IF EXISTS " + TABLE_NAME;
db.execSQL(sql);
onCreate(db);
}
public Cursor select() {
Cursor cursor = groupDB
.query(TABLE_NAME, null, null, null, null, null, null);
return cursor;
}
// 增加操作
public long insert(String groupName, String groupAddr, String leaf) {
/* ContentValues */
ContentValues cv = new ContentValues();
cv.put(GROUP_NAME, groupName);
cv.put(GROUP_ADDR, groupAddr);
cv.put(GROUP_LEAF, leaf);
long row = groupDB.insert(TABLE_NAME, null, cv);
return row;
}
// 删除操作
public void delete(int id) {
String where = GROUP_ID + " = ?";
String[] whereValue = { Integer.toString(id) };
groupDB.delete(TABLE_NAME, where, whereValue);
}
// 修改操作
public void update(int id, String groupName, String groupAddr, String leaf) {
String where = GROUP_ID + " = ?";
String[] whereValue = { Integer.toString(id) };
ContentValues cv = new ContentValues();
cv.put(GROUP_NAME, groupName);
cv.put(GROUP_ADDR, groupAddr);
cv.put(GROUP_LEAF, leaf);
groupDB.update(TABLE_NAME, cv, where, whereValue);
}
} | true |
72f39e7d7dcbecf51d4812e5f7bf9dde9ea13470 | Java | Monksc/ml_neuralnetwork_image_digit_detector | /SaveData.java | UTF-8 | 2,360 | 3.171875 | 3 | [] | no_license | import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class SaveData {
public SaveData() {
}
public static void saveData(String fileName, Layer[] layers) {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileName), "utf-8"))) {
for (Layer l : layers) {
for (Node n : l.getNodes()) {
for (double d : n.getConnectionStrengths()) {
writer.write(d + "\n");
}
}
}
}
catch(Exception e) {
}
}
public static Layer[] getData(String fileName, int[] formation) {
try(BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line = br.readLine();
ArrayList<String> lines = new ArrayList<String>();
while (line != null) {
lines.add(line);
line = br.readLine();
}
int linesIndex = 0;
Layer[] layers = new Layer[formation.length];
for (int i = 0; i < layers.length; i++) {
int nextFormationSize = 0;
if (i < formation.length - 1) { nextFormationSize = formation[i+1]; }
Layer layer = new Layer(formation[i], nextFormationSize);
for (int l = 0; l < formation[i] + 1; l++) {
Node node = new Node(nextFormationSize);//formation[l+1]);
for (int n = 0; n < nextFormationSize; n++) {//formation[l+1]; n++) {
//Connection conn = new Connection(Double.parseDouble(lines.get(linesIndex++)), Math.random());
//neuron.setConnection(conn, n);
double conn = Double.parseDouble(lines.get(linesIndex++));
node.setConnection(conn, n);
}
layer.setNode(node, l);
}
layers[i] = layer;
}
return layers;
} catch(Exception e) {
System.out.println(e.toString());
}
return null;
}
} | true |
3607decb9c378824ec145cff9f8a85572d883581 | Java | KilmerLuizAleluia/CompartilhaUnB | /src/main/java/projetoES/converters/DisciplinaConverter.java | UTF-8 | 1,026 | 2.4375 | 2 | [] | no_license | package projetoES.converters;
import org.springframework.stereotype.Component;
import projetoES.model.entities.Disciplina;
import projetoES.model.entities.Pergunta;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import java.util.Map;
@Component("disciplinaConverter")
public class DisciplinaConverter implements Converter{
@Override
public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
if (s != null) {
return this.getAttributesFrom(uiComponent).get(s);
}
return null;
}
@Override
public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {
if (o != null) {
Disciplina disciplina = (Disciplina) o;
return disciplina.getNome();
}
return null;
}
protected Map<String, Object> getAttributesFrom(UIComponent component) {
return component.getAttributes();
}
}
| true |
0e6ee465ec82a12f716264685c81c8de90d52219 | Java | elascano/ESPE202105-OOP-TC-3730 | /assignments/heredial/unit1/HW06 CompleteProjectInventory/FutureTheOnAccentInventoryProducts/src/futuretheonaccent/inventory/productos/model/Quality.java | UTF-8 | 1,123 | 2.21875 | 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 futuretheonaccent.inventory.productos.model;
/**
*
* @author Luis Heredia Accent on the Future ESPE-DCC0
*/
public class Quality {
private int qualification;
private char credibility;
@Override
public String toString() {
return "Quality{" + "qualification=" + qualification + ", credibility=" + credibility + '}';
}
/**
* @return the qualification
*/
public int getQualification() {
return qualification;
}
/**
* @param qualification the qualification to set
*/
public void setQualification(int qualification) {
this.qualification = qualification;
}
/**
* @return the credibility
*/
public char getCredibility() {
return credibility;
}
/**
* @param credibility the credibility to set
*/
public void setCredibility(char credibility) {
this.credibility = credibility;
}
}
| true |
928df84ab2b53e45f3b3ea24bb23cc081ecdcea3 | Java | srinivaskulkarni1/shridarshan | /automation-test/src/main/java/com/shridarshan/in/automation_test/Utility.java | UTF-8 | 1,834 | 2.921875 | 3 | [] | no_license | package com.shridarshan.in.automation_test;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class Utility {
@SuppressWarnings("rawtypes")
public static List<Object> getCollection(Collection collection){
List<Object> objList = new ArrayList<Object>();
for (Object object : collection) {
objList.add(getValues(object));
}
return objList;
}
private static Object getValues(Object object) {
List<Object> objList = new ArrayList<Object>();
try {
BeanInfo info = Introspector.getBeanInfo(object.getClass());
for(PropertyDescriptor d : info.getPropertyDescriptors()){
Method get = d.getReadMethod();
if(get != null){
objList.add(list(d.getName(), get.invoke(object)));
}
}
} catch (IntrospectionException e) {
System.out.println("Exception in method Utility.getValues(): " + "IntrospectionException");
e.printStackTrace();
} catch (IllegalAccessException e) {
System.out.println("Exception in method Utility.getValues(): " + "IllegalAccessException");
e.printStackTrace();
} catch (IllegalArgumentException e) {
System.out.println("Exception in method Utility.getValues(): " + "IllegalArgumentException");
e.printStackTrace();
} catch (InvocationTargetException e) {
System.out.println("Exception in method Utility.getValues(): " + "InvocationTargetException");
e.printStackTrace();
}
return objList;
}
@SuppressWarnings("unchecked")
public static <T> List<T> list(T... objects){
List<T> list = new ArrayList<T>();
for(T obj : objects){
list.add(obj);
}
return list;
}
}
| true |
5c57ad81635bc191b8fa693a24fefcd3571fbbaa | Java | ashrafbaig/Validating-Enrollee-And-Dependent-Page | /src/main/java/com/qa/PageClasses/SelfServiceLoginPage.java | UTF-8 | 1,111 | 2.015625 | 2 | [] | no_license | package com.qa.PageClasses;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.testng.Assert;
import IES_TestBaseClass.SelfServiceBaseClass;
public class SelfServiceLoginPage extends SelfServiceBaseClass {
////////////////////////SelfService//////////////////////
@FindBy(id = "ContentPlaceHolder1_txtUserName")
WebElement SelfService_username;
@FindBy(id = "ContentPlaceHolder1_txtPassword")
WebElement SelfService_password;
@FindBy(id = "ContentPlaceHolder1_btnLogin")
WebElement SelfService_loginbutton;
public SelfServiceLoginPage() {
PageFactory.initElements(driver, this);
}
public SelfServiceCaseAndLocationPage IES_login() {
SelfService_username.sendKeys(wso.getRow(1).getCell(13).getStringCellValue().trim());
SelfService_password.sendKeys(wso.getRow(1).getCell(14).getStringCellValue().trim());
SelfService_loginbutton.click();
Assert.assertEquals(driver.getCurrentUrl(), wso.getRow(1).getCell(11).getStringCellValue().trim());
return new SelfServiceCaseAndLocationPage();
}
}
| true |
d3a69ce60aa57809a9d1f20fc56d626923af274e | Java | qcamei/yycg-2 | /src/main/java/com/cyb/yycg/controller/IndexController.java | UTF-8 | 420 | 1.773438 | 2 | [] | no_license | package com.cyb.yycg.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @ClassName IndexController
* @Descripttion TODO
* @Author chenyongbo
* @Date 2019/3/28 11:34
**/
@Controller
public class IndexController {
//欢迎页面
@RequestMapping("/welcome")
public String welcome(){
return "/base/welcome";
}
}
| true |
4b7ff51c011a7e59c272fd0162d124a7651426cc | Java | princebak/empmanager_repo | /src/main/java/com/blh/empmanager/restrepositories/EmployeeRestRepository.java | UTF-8 | 639 | 1.875 | 2 | [] | no_license | package com.blh.empmanager.restrepositories;
import com.blh.empmanager.entities.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.CrossOrigin;
@CrossOrigin("http://localhost:3000")
@RepositoryRestResource(collectionResourceRel = "employees",path = "employees")
public interface EmployeeRestRepository extends JpaRepository<Employee, Long> {
//Boolean getEmployeesByFnamemp(String fnamemp);
Boolean existsByFnamemp(String fnamemp);
}
| true |
c273fe06005012ef552f69cc16c73ef0ac254ca1 | Java | crnk-project/crnk-framework | /crnk-gen/crnk-gen-java/src/test/resources/TypedQuerySpecTest.java | UTF-8 | 804 | 1.953125 | 2 | [
"Apache-2.0"
] | permissive | package test;
import io.crnk.core.queryspec.FilterOperator;
import io.crnk.core.queryspec.FilterSpec;
import io.crnk.core.queryspec.QuerySpec;
import io.crnk.core.queryspec.SortSpec;
import static test.UserPathSpec.*;
public class TypedQuerySpecTest {
public QuerySpec createQuerySpec() {
UserQuerySpec querySpec = new UserQuerySpec();
querySpec.sort().loginId().desc();
querySpec.filter().projects().id().filter(FilterOperator.EQ, 12);
querySpec.field().loginId();
querySpec.include().projects();
return querySpec;
}
public FilterSpec createFilterSpec() {
return userPathSpec.projects().id().filter(FilterOperator.EQ, 12);
}
public SortSpec createSortSpec() {
return userPathSpec.projects().id().desc();
}
}
| true |
407f2fb8980aabd845c70afe9079ee912982b905 | Java | NailyaD/Java-Course | /dbdemo/src/main/java/de/telran/repository/StudentRepository.java | UTF-8 | 931 | 2.234375 | 2 | [] | no_license | package de.telran.repository;
import de.telran.entity.StudentEntity;
import de.telran.dto.StudentsByCourseDto;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import javax.transaction.Transactional;
import java.util.List;
public interface StudentRepository extends JpaRepository<StudentEntity, Long> {
@Transactional
@Modifying
@Query("UPDATE StudentEntity s SET s.courseId = :courseId WHERE s.studentId = :studentId")
int assignStudentToCourse(@Param("studentId") long studentId, @Param("courseId") long courseId);
@Query("select new StudentsByCourseDto (c.title, s.firstName, s.lastName) " +
"from Course as c join Student s on s.courseId = c.courseId")
List<StudentsByCourseDto> getStudentsByCourseId();
}
| true |
b4149f3c521c05bccfd8b04e8cb49e702416fe28 | Java | mahbub123-gif/java_all | /lab5/src/lab5/Lab4ProblemA.java | UTF-8 | 504 | 2.671875 | 3 | [] | no_license | package lab5;
public class Lab4ProblemA {
public static void main(String[] args) {
Icecream obj1=new Icecream();
obj1.icecreamType="vanilla";
obj1.icecreamCompany="Igloo";
obj1.icecreamPrice= 10;
Icecream obj2=new Icecream();
obj2.icecreamType="Chocolate";
obj2.icecreamCompany="Igloo";
obj2.icecreamPrice=20;
obj1.toString();
obj2.toString();
obj1.display();
obj2.display();
}
} | true |
6e0db0be7577c5d590473131fdfc1c6889372b4a | Java | ibrcic/torvalds-senior-dev | /android/ISTInventoryManagement/app/src/main/java/torvalds/istinventorymanagement/bus/RxBusReservation.java | UTF-8 | 716 | 2.359375 | 2 | [] | no_license | package torvalds.istinventorymanagement.bus;
import com.jakewharton.rxrelay2.BehaviorRelay;
import io.reactivex.Observable;
import torvalds.istinventorymanagement.model.Student;
/**
* Created by ivan on 4/14/17.
*/
public class RxBusReservation {
private static RxBusReservation instance;
private BehaviorRelay<Long> relay = BehaviorRelay.create();
public static RxBusReservation instanceOf() {
if (instance == null) {
instance = new RxBusReservation();
}
return instance;
}
public void reservationMade(long borrowerId) {
relay.accept(borrowerId);
}
public Observable<Long> getReservationUpdates() {
return relay;
}
}
| true |
328f16f82cc2556519f47752f3f2dd6404cc140c | Java | AndyTsangChun/UoB_LeapVisualizationSystem | /src/ui/awt/panel/LVSOverLayerPanel.java | UTF-8 | 9,965 | 2.203125 | 2 | [] | no_license | package ui.awt.panel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import system.controller.LeapMotionFrameController;
import system.controller.OverLayerController;
import system.general.SystemPreference;
import system.model.OverLayerButton;
import ui.awt.dialog.edit.tracking.TrackingModel;
import ui.awt.overlayer.SliceTranslateButton;
import ui.awt.res.LVSSwingInfo;
import ui.awt.res.SwingTextureManager;
import com.leapmotion.leap.Finger;
import com.leapmotion.leap.FingerList;
import com.leapmotion.leap.Frame;
import com.leapmotion.leap.Hand;
import com.leapmotion.leap.InteractionBox;
import com.leapmotion.leap.Vector;
/** ************************************************************
* This class extends LVSPanel, an over layer display finger
* tracking ,gesture status and all other addition Graphics.
*
* @author Andy Tsang
* @version 1.2
* ***********************************************************/
public class LVSOverLayerPanel extends JPanel {
private static final int DOT_SIZE = 20;
private static final int GESTURE_OFFSET_X = 50;
private static final int GESTURE_OFFSET_Y = 100;
public static final int GESTURE_IMAGE_W = 75;
public static final int GESTURE_IMAGE_H = 100;
private Frame frame;
private InteractionBox iBox;
private boolean hasGesture;
private OverLayerController overLayerController;
private LeapMotionFrameController frameController;
private Image gestureImage;
private String gestureString;
private List<OverLayerButton> componentList;
/**
* Constructor
* @param overLayerController Controller of this over layer panel
*/
public LVSOverLayerPanel(OverLayerController overLayerController) {
super();
this.overLayerController = overLayerController;
this.frameController = getOverLayerController().getSystemController().getLeapMotionFrameController();
componentList = new ArrayList<OverLayerButton>();
OverLayerButton moveSlice = new SliceTranslateButton(this, 0, SwingTextureManager.DEFAULT_SLICE_TRANSLATE_ICON_IMAGE);
moveSlice.setEnableIcon(SwingTextureManager.ENABLE_SLICE_TRANSLATE_ICON_IMAGE);
componentList.add(moveSlice);
}
/**
* Set up the panel
*/
public void setup(){
this.setLayout(null);
}
/**
* Update Leap Motion Frame Information
* @param frame Leap Motion Frame
*/
public void updateFrame(Frame frame){
this.frame = frame;
}
/**
* Function call to update every component position
*/
public void updateComponentPos(){
for (int i = 0 ; i < componentList.size() ; i++){
componentList.get(i).updatePosition();
}
}
@Override
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D)g;
// clear all old item before drawing
g2d.clearRect(0, 0, overLayerController.getSystemPreference().getScreenWidth(), overLayerController.getSystemPreference().getScreenHeight());
// draw swing component
for (int i = 0 ; i < componentList.size() ; i++){
OverLayerButton button = componentList.get(i);
if (button.isButtonVisible()){
button.setVisible(true);
}else{
button.setVisible(false);
}
}
this.paintComponents(g);
// draw gesture guide
if (overLayerController.isGestureGuideVisible()){
int width = this.overLayerController.getSystemPreference().getScreenWidth();
int height = this.overLayerController.getSystemPreference().getScreenHeight();
int w = (int)(width * 0.8);
int h = (int)(height * 0.9);
int x = (width - w) / 2;
int y = (height - h) / 2;
g2d.drawImage(SwingTextureManager.TUT_GESTURE_IMAGE, x, y, w, h, null);
}
// draw other component
if (frame != null && frame.hands().count() > 0){
if (overLayerController.getSystemController().getLeapMotionController().isConnected()){
if(overLayerController.isGestureStatusVisible())
drawGestureStatus(g2d);
if(overLayerController.isTrackingVisible())
drawFingersTracking(g2d);
}
}
}
/**
* Draw gesture status
* @param g2d Java Graphics
*/
public void drawGestureStatus(Graphics2D g2d){
g2d.setColor(Color.WHITE);
double w = this.getSize().getWidth();
double h = this.getSize().getHeight();
if (hasGesture){
if (gestureImage != null && !gestureImage.equals("")){
g2d.drawImage(gestureImage, (int)(w - GESTURE_IMAGE_W - GESTURE_OFFSET_X), GESTURE_OFFSET_Y , GESTURE_IMAGE_W, GESTURE_IMAGE_H, null);
}
if (gestureString != null && !gestureString.equals("")){
g2d.drawString(gestureString, (int)(w - GESTURE_IMAGE_W - GESTURE_OFFSET_X), GESTURE_OFFSET_Y + GESTURE_IMAGE_H + 20);
}
}
}
/**
* Draw fingers
* @param g2d Java Graphics
*/
public void drawFingersTracking(Graphics2D g2d){
TrackingModel trackingModel = this.getOverLayerController().getSystemController().getSwingController().getTrackingModel();
iBox = frame.interactionBox();
if (frameController.hasHand()){
Hand hand = frameController.getLeftHand();
if (hand !=null){
if (trackingModel.isShowLeftPalm()){
drawHand(hand, g2d);
}
FingerList fingerList = hand.fingers();
if (fingerList != null && fingerList.count() > 0){
if (overLayerController.getSystemPreference().getFinger_color() != null)
g2d.setColor(overLayerController.getSystemPreference().getFinger_color());
else
g2d.setColor(Color.GREEN);
for (int i = 0; i < fingerList.count(); i++) {
Finger finger = fingerList.get(i);
if (finger.type() == Finger.Type.TYPE_THUMB && trackingModel.isShowLeftThumb())
drawFinger(finger, g2d);
if (finger.type() == Finger.Type.TYPE_INDEX && trackingModel.isShowLeftIndex())
drawFinger(finger, g2d);
if (finger.type() == Finger.Type.TYPE_MIDDLE && trackingModel.isShowLeftMiddle())
drawFinger(finger, g2d);
if (finger.type() == Finger.Type.TYPE_RING && trackingModel.isShowLeftRing())
drawFinger(finger, g2d);
if (finger.type() == Finger.Type.TYPE_PINKY && trackingModel.isShowLeftPinky())
drawFinger(finger, g2d);
}
}
}
hand = frameController.getRightHand();
if (hand !=null){
if (trackingModel.isShowRightPalm()){
drawHand(hand, g2d);
}
FingerList fingerList = hand.fingers();
if (fingerList != null && fingerList.count() > 0){
if (overLayerController.getSystemPreference().getFinger_color() != null)
g2d.setColor(overLayerController.getSystemPreference().getFinger_color());
else
g2d.setColor(Color.GREEN);
for (int i = 0; i < fingerList.count(); i++) {
Finger finger = fingerList.get(i);
if (finger.type() == Finger.Type.TYPE_THUMB && trackingModel.isShowRightThumb())
drawFinger(finger, g2d);
if (finger.type() == Finger.Type.TYPE_INDEX && trackingModel.isShowRightIndex())
drawFinger(finger, g2d);
if (finger.type() == Finger.Type.TYPE_MIDDLE && trackingModel.isShowRightMiddle())
drawFinger(finger, g2d);
if (finger.type() == Finger.Type.TYPE_RING && trackingModel.isShowRightRing())
drawFinger(finger, g2d);
if (finger.type() == Finger.Type.TYPE_PINKY && trackingModel.isShowRightPinky())
drawFinger(finger, g2d);
}
}
}
}
}
public void drawHand (Hand hand, Graphics g2d){
if (overLayerController.getSystemPreference().getPalm_color() != null)
g2d.setColor(overLayerController.getSystemPreference().getPalm_color());
else
g2d.setColor(Color.BLUE);
int[] plamPos = frameController.getNormalizedHandPosition(hand);
g2d.fillOval(plamPos[0], plamPos[1] - SystemPreference.MENU_BAR_OFFSET, DOT_SIZE, DOT_SIZE);
}
public void drawFinger(Finger finger, Graphics g2d){
Vector leapPoint = finger.stabilizedTipPosition();
Vector normalizedPoint = iBox.normalizePoint(leapPoint, true);
float cursor_X = normalizedPoint.getX() * overLayerController.getSystemPreference().getScreenWidth();
float cursor_Y = (1 - normalizedPoint.getY()) * overLayerController.getSystemPreference().getScreenHeight();
g2d.fillOval((int) cursor_X, (int) cursor_Y, DOT_SIZE, DOT_SIZE);
}
/**
* Perform button function
*
* @param rect
*/
public void checkComponent(int x1, int y1, boolean isDown) {
int x2 = x1 + 1, y2 = y1 + 1;
Rectangle2D rect = new Rectangle2D.Double((x1 < x2) ? x1 : x2, (y1 < y2) ? y1
: y2, Math.abs(x2 - x1) + 1, Math.abs(y2 - y1) + 1);
double posX,posY;
int width, height;
Iterator<OverLayerButton> buttonIterator = componentList.iterator();
while (buttonIterator.hasNext()) {
OverLayerButton object = buttonIterator.next();
posX = object.getPosX();
posY = object.getPosY();
width = object.getWidth();
height = object.getHeight();
// compare their rectangular area
if (rect.intersects(new Rectangle2D.Double(posX, posY, width, height))){
if(isDown){
object.performAction();
}else{
System.out.println("2");
}
}else{
if(!isDown){
}
}
}
}
// Attributes Set and Get
public Image getGestureImage() {
return gestureImage;
}
public void setGestureImage(Image gestureImage) {
this.gestureImage = gestureImage;
}
public String getGestureString() {
return gestureString;
}
public void setGestureString(String gestureString) {
this.gestureString = gestureString;
}
public OverLayerController getOverLayerController() {
return overLayerController;
}
public void setOverLayerController(OverLayerController overLayerController) {
this.overLayerController = overLayerController;
}
public boolean hasGesture() {
return hasGesture;
}
public void setHasGesture(boolean hasGesture) {
this.hasGesture = hasGesture;
}
public List<OverLayerButton> getComponentList() {
return componentList;
}
public void setComponentList(List<OverLayerButton> componentList) {
this.componentList = componentList;
}
}
| true |
b79f631b715bf3122d1ce0661358bea81742dea9 | Java | Clownvin/Lumina | /src/com/clownvin/lumina/world/Chunk.java | UTF-8 | 993 | 3.046875 | 3 | [] | no_license | package com.clownvin.lumina.world;
import java.util.ArrayList;
import com.clownvin.lumina.entity.Entity;
public class Chunk {
private final String name;
private final int width, height;
private ArrayList<Entity> tileSet = new ArrayList<>();
private ArrayList<Entity> entities = new ArrayList<>();
public Chunk(String name, int width, int height) {
this.name = name;
this.width = width;
this.height = height;
}
public void addEntity(Entity e) {
entities.add(e);
}
public int getHeight() {
return height;
}
public String getName() {
return name;
}
public int getWidth() {
return width;
}
public void removeEntity(Entity e) {
entities.remove(e);
}
public void renderEntities() {
for (Entity e : entities) {
e.render();
}
}
public void renderTiles() {
for (Entity e : tileSet) {
e.render();
}
}
public void setTileSet(ArrayList<Entity> tileSet) {
this.tileSet = tileSet;
}
}
| true |
bc28d5b87b84a85be2acad492590142e55f7f321 | Java | DoodleBobBuffPants/CypherSQL | /cypher-translator/src/main/java/cyphersql/ast/match/where/WhereCondition.java | UTF-8 | 229 | 1.914063 | 2 | [
"Apache-2.0"
] | permissive | package cyphersql.ast.match.where;
public class WhereCondition {
public WhereArgument leftArgument = new WhereArgument();
public String comparisonOperator;
public WhereArgument rightArgument = new WhereArgument();
}
| true |
650b53dc41b07160ce7b53374e4441c5994c7ff3 | Java | stanislaw-tokarski/github-discovery | /github-discovery-service/src/main/java/com/github/stanislawtokarski/githubdiscovery/exception/GithubApiException.java | UTF-8 | 284 | 2.140625 | 2 | [] | no_license | package com.github.stanislawtokarski.githubdiscovery.exception;
import lombok.Getter;
public class GithubApiException extends RuntimeException {
@Getter
private final int errorCode;
public GithubApiException(int errorCode) {
this.errorCode = errorCode;
}
}
| true |
56482b3bce5f470de0b8d1408be1be789ded5663 | Java | 0704mm/mm | /src/main/java/com/yc/biz/IMenberInfoBiz.java | UTF-8 | 275 | 1.835938 | 2 | [] | no_license | package com.yc.biz;
import com.yc.po.MenberInfo;
public interface IMenberInfoBiz {
/**
* 登录
* @param bf
* @return
*/
public MenberInfo login(MenberInfo mf);
/**
* 注册
* @param bf
* @return
*/
public int add(MenberInfo mf);
}
| true |
c716d91a0e528e9642bfe23a980124f3e7c7c182 | Java | sin-orb/Simyukkuri2021 | /src/util/YukkuriUtil.java | UTF-8 | 19,494 | 2.296875 | 2 | [
"Apache-2.0"
] | permissive | package src.util;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import src.SimYukkuri;
import src.attachment.Ants;
import src.base.Body;
import src.draw.Terrarium;
import src.enums.Attitude;
import src.enums.Intelligence;
import src.enums.YukkuriType;
import src.game.Dna;
import src.yukkuri.Ayaya;
import src.yukkuri.Deibu;
import src.yukkuri.DosMarisa;
import src.yukkuri.HybridYukkuri;
import src.yukkuri.Kimeemaru;
import src.yukkuri.Marisa;
import src.yukkuri.MarisaKotatsumuri;
import src.yukkuri.MarisaTsumuri;
import src.yukkuri.Reimu;
import src.yukkuri.Tarinai;
import src.yukkuri.TarinaiReimu;
import src.yukkuri.WasaReimu;
/***************************************************
* ゆっくり処理クラス
*/
public class YukkuriUtil {
/**
* クラス名からタイプ取得
* @param className クラス名
* @return ゆっくりのタイプ
*/
public static final YukkuriType getYukkuriType(String className) {
YukkuriType ret = null;
for (YukkuriType y : YukkuriType.values()) {
if (y.className.equals(className)) {
ret = y;
break;
}
}
return ret;
}
/**
* タイプからクラス名取得
* @param type タイプ
* @return ゆっくりのクラス名
*/
public static final String getYukkuriClassName(int type) {
String ret = null;
for (YukkuriType y : YukkuriType.values()) {
if (y.typeID == type) {
ret = y.className;
break;
}
}
return ret;
}
/**
* 両親から赤ゆ一匹分のDNAを作成。
* forceCreateをtrueで確実に赤ゆができる。まれに茎に1つも赤ゆができないのを回避できる
* @param mother 母ゆ
* @param father 父ゆ
* @param iFatherType 父のタイプ
* @param fatherrAtt 父の性格
* @param fatherInt 父の知性
* @param isRape レイプでできた子か
* @param fatherDamage 父のダメージ
* @param forceCreate 強制作成フラグ
* @return 赤ゆのDNA
*/
public static final Dna createBabyDna(Body mother, Body father, int iFatherType, Attitude fatherrAtt,
Intelligence fatherInt, boolean isRape, boolean fatherDamage, boolean forceCreate) {
Dna ret = null;
// 母がいないのはあり得ないのでエラー
if (mother == null) {
return null;
}
// 種別の決定
int babyType;
int motherType = mother.getType();
int fatherType = iFatherType;
List<Integer> motherAncestorList = mother.getAncestorList();
if (motherAncestorList != null && motherAncestorList.size() != 0) {
if (SimYukkuri.RND.nextInt(100) == 0) {
// 先祖返り
int nSize = motherAncestorList.size();
int nIndex = SimYukkuri.RND.nextInt(nSize);
motherType = motherAncestorList.get(nIndex);
}
}
if (father != null) {
List<Integer> fatherAncestorList = father.getAncestorList();
if (fatherAncestorList != null && fatherAncestorList.size() != 0) {
if (SimYukkuri.RND.nextInt(100) == 0) {
// 先祖返り
int nSize = fatherAncestorList.size();
int nIndex = SimYukkuri.RND.nextInt(nSize);
fatherType = fatherAncestorList.get(nIndex);
}
}
}
boolean hybrid = false;
boolean hybrid2 = false;
if (SimYukkuri.RND.nextInt(2) == 0 && !forceCreate) {
// 作成失敗
return null;
}
// ハイブリッド判定
// 両方ハイブリッドではない
if ((fatherType != HybridYukkuri.type) && (motherType != HybridYukkuri.type)) {
// 同じタイプならハイブッリドを作らない
if (fatherType != motherType) {
// 両方普通
if (SimYukkuri.RND.nextInt(70) == 0) {
hybrid = true;
hybrid2 = true;
}
}
} else if ((fatherType == HybridYukkuri.type) && (motherType == HybridYukkuri.type)) {
// 両方ハイブリッド
if (SimYukkuri.RND.nextInt(20) == 0)
hybrid = true;
} else {
// 片方ハイブリッド
if (SimYukkuri.RND.nextInt(50) == 0)
hybrid = true;
}
// どちらかがドスまりさなら処理の都合でハイブリッドはなし
if (fatherType == DosMarisa.type || motherType == DosMarisa.type) {
hybrid = false;
}
if (hybrid) {
if (hybrid2 && mother != null && SimYukkuri.RND.nextBoolean()) {
babyType = mother.getHybridType(fatherType);
} else {
babyType = HybridYukkuri.type;
}
} else {
if (SimYukkuri.RND.nextBoolean()) {
babyType = fatherType;
} else {
babyType = motherType;
}
// ドスまりさはただのまりさに変換
if (babyType == DosMarisa.type) {
babyType = Marisa.type;
}
if (babyType == Deibu.type) {
babyType = Reimu.type;
}
}
// チェンジリング判定
// 上でどんな結果になろうと、チェンジリングが1/100の確率で発生する
if (SimYukkuri.RND.nextInt(100) == 0) {
babyType = getChangelingBabyType();
}
// ディフューザーでハイブリッド薬がまかれていたら強制的にハイブリッドにする
if (Terrarium.hybridSteam) {
if ((fatherType == Reimu.type) && (motherType == Marisa.type) && (mother != null)
&& SimYukkuri.RND.nextBoolean()) {
babyType = mother.getHybridType(fatherType);
} else if ((fatherType == Marisa.type) && (motherType == Reimu.type) && (mother != null)
&& SimYukkuri.RND.nextBoolean()) {
babyType = mother.getHybridType(fatherType);
} else if (fatherType != motherType) {
babyType = HybridYukkuri.type;
}
}
// 突然変異
if ((babyType == Reimu.type) && SimYukkuri.RND.nextInt(20) == 0) {
babyType = WasaReimu.type;
} else if ((babyType == WasaReimu.type) && SimYukkuri.RND.nextInt(20) != 0) {
babyType = Reimu.type;
} else if ((babyType == Marisa.type || babyType == MarisaKotatsumuri.type) && SimYukkuri.RND.nextInt(20) == 0) {
babyType = MarisaTsumuri.type;
} else if ((babyType == Marisa.type || babyType == MarisaTsumuri.type) && SimYukkuri.RND.nextInt(20) == 0) {
babyType = MarisaKotatsumuri.type;
} else if ((babyType == MarisaTsumuri.type || babyType == MarisaKotatsumuri.type) && SimYukkuri.RND.nextInt(20) != 0) {
babyType = Marisa.type;
} else if ((babyType == Kimeemaru.type) && SimYukkuri.RND.nextInt(20) != 0) {
babyType = Ayaya.type;
} else if ((babyType == Ayaya.type) && SimYukkuri.RND.nextInt(20) == 0) {
babyType = Kimeemaru.type;
}
if (mother.isOverPregnantLimit() || mother.isSick() || mother.isDamagedHeavily() || fatherDamage) {
if (SimYukkuri.RND.nextBoolean() && (babyType == Reimu.type || babyType == WasaReimu.type)) {
babyType = TarinaiReimu.type;
} else {
babyType = Tarinai.type;
}
}
ret = new Dna();
ret.type = babyType;
ret.raperChild = isRape;
ret.mother = mother.getUniqueID();
ret.father = father.getUniqueID();
// 性格の設定
// 0(大善良+大善良)~8(ドゲス+ドゲス)
int attBase = mother.getAttitude().ordinal() + fatherrAtt.ordinal();
Attitude[] attitude = Attitude.values();
switch (attBase) {
case 0:
if (SimYukkuri.RND.nextInt(20) == 0) {
ret.attitude = attitude[2 + SimYukkuri.RND.nextInt(2)];
} else {
ret.attitude = attitude[SimYukkuri.RND.nextInt(3)];
}
break;
case 1:
case 2:
case 3:
if (SimYukkuri.RND.nextInt(15) == 0) {
ret.attitude = attitude[SimYukkuri.RND.nextInt(2)];
} else {
ret.attitude = attitude[1 + SimYukkuri.RND.nextInt(4)];
}
break;
case 4:
if (SimYukkuri.RND.nextInt(10) == 0) {
ret.attitude = attitude[SimYukkuri.RND.nextInt(3)];
} else {
ret.attitude = attitude[1 + SimYukkuri.RND.nextInt(4)];
}
break;
case 5:
case 6:
case 7:
if (SimYukkuri.RND.nextInt(15) == 0) {
ret.attitude = attitude[1 + SimYukkuri.RND.nextInt(3)];
} else {
ret.attitude = attitude[2 + SimYukkuri.RND.nextInt(3)];
}
break;
case 8:
if (SimYukkuri.RND.nextInt(20) == 0) {
ret.attitude = attitude[SimYukkuri.RND.nextInt(3)];
} else {
ret.attitude = attitude[3 + SimYukkuri.RND.nextInt(2)];
}
break;
}
// 知能の設定
// 0(天才)~4(馬鹿)
int intBase = mother.getIntelligence().ordinal() + fatherInt.ordinal();
Intelligence[] intel = Intelligence.values();
switch (intBase) {
case 0:
if (SimYukkuri.RND.nextInt(15) == 0) {
ret.intelligence = intel[1 + SimYukkuri.RND.nextInt(2)];
} else {
ret.intelligence = intel[SimYukkuri.RND.nextInt(2)];
}
break;
case 4:
if (SimYukkuri.RND.nextInt(15) == 0) {
ret.intelligence = intel[SimYukkuri.RND.nextInt(2)];
} else {
ret.intelligence = intel[1 + SimYukkuri.RND.nextInt(2)];
}
break;
default:
if (SimYukkuri.RND.nextInt(10) == 0) {
ret.intelligence = intel[SimYukkuri.RND.nextInt(3)];
} else {
ret.intelligence = intel[1];
}
}
return ret;
}
/**
* チェンジリングのゆっくりのタイプを取得する.
* チェンジリングとはいえ、親の餡とちがくなるとは限らない…
* @return チェンジリング後のゆっくりのタイプ
*/
public static int getChangelingBabyType() {
// 66%で通常種、33%で希少種
if (SimYukkuri.RND.nextInt(3) == 0) {
//希少種
return 1000 + SimYukkuri.RND.nextInt(12);
} else {
//通常種
int i = SimYukkuri.RND.nextInt(6);
if (i == 0) {//まりさ
switch (SimYukkuri.RND.nextInt(5)) {
case 1:
return 2004;//こたつむり
case 2:
return 2002;//つむり
default:
return 0;//普通のまりさ
}
} else if (i == 1) {//れいむ
switch (SimYukkuri.RND.nextInt(4)) {
case 2:
return 2001;//わされいむ
case 3:
return 2005;//でいぶ
default:
return 1;//普通のれいむ
}
} else {
return i;
}
}
}
// コピーしたくない変数はここで定義
// 主にゆっくり固有のステータス
private static final String[] NOCOPY_FIELD = {
"bodySpr",
"expandSpr",
"braidSpr",
"EATAMOUNT",
"WEIGHT",
"HUNGRYLIMIT",
"SHITLIMIT",
"DAMAGELIMIT",
"STRESSLIMIT",
"TANGLEVEL",
"BABYLIMIT",
"CHILDLIMIT",
"LIFELIMIT",
"LOVEPLAYERLIMIT",
"ROTTINGTIME",
"STEP",
"RELAXPERIOD",
"EXCITEPERIOD",
"PREGPERIOD",
"SLEEPPERIOD",
"ACTIVEPERIOD",
"ANGRYPERIOD",
"SCAREPERIOD",
"sameDest",
"DECLINEPERIOD",
"DISCIPLINELIMIT",
"BLOCKEDLIMIT",
"DIRTYPERIOD",
"ROBUSTNESS",
"STRENGTH",
"EYESIGHT",
"INCUBATIONPERIOD",
"speed",
"Ycost",
"YValue",
"AValue",
"anBabyName",
"anChildName",
"anAdultName",
"anMyName",
"anBabyNameD",
"anChildNameD",
"anAdultNameD",
"anMyNameD",
"baseBodyFileName"
};
/**
* ゆっくりのステータスをfrom->toへ複製
* シャローコピーなので複製元はbodyListから外しておかないと予期しない動作になるので注意
* @param to 変異後のゆっくり
* @param from 変異前のゆっくり
* @throws Exception リフレクションでコピー中に発生する例外
*/
public static final void changeBody(Body to, Body from) throws Exception {
Field[] fromField = null;
Class<?> toClass = null;
Field toField = null;
// Objクラスのコピー
fromField = from.getClass().getSuperclass().getSuperclass().getSuperclass().getDeclaredFields();
toClass = to.getClass().getSuperclass().getSuperclass().getSuperclass().getSuperclass();
for (int i = 0; i < fromField.length; i++) {
int mod = fromField[i].getModifiers();
if (Modifier.isFinal(mod)) {
continue;
}
if (Modifier.isStatic(mod)) {
continue;
}
if (isNoCopyField(fromField[i].getName())) {
continue;
}
toField = toClass.getDeclaredField(fromField[i].getName());
toField.setAccessible(true);
fromField[i].setAccessible(true);
toField.set(to, fromField[i].get(from));
}
// BodyAttributesクラスのコピー
fromField = from.getClass().getSuperclass().getSuperclass().getDeclaredFields();
toClass = to.getClass().getSuperclass().getSuperclass().getSuperclass();
for (int i = 0; i < fromField.length; i++) {
int mod = fromField[i].getModifiers();
if (Modifier.isFinal(mod)) {
continue;
}
if (Modifier.isStatic(mod)) {
continue;
}
if (isNoCopyField(fromField[i].getName())) {
continue;
}
toField = toClass.getDeclaredField(fromField[i].getName());
toField.setAccessible(true);
fromField[i].setAccessible(true);
toField.set(to, fromField[i].get(from));
}
// Bodyクラスのコピー
fromField = from.getClass().getSuperclass().getDeclaredFields();
toClass = to.getClass().getSuperclass().getSuperclass();
for (int i = 0; i < fromField.length; i++) {
int mod = fromField[i].getModifiers();
if (Modifier.isFinal(mod)) {
continue;
}
if (Modifier.isStatic(mod)) {
continue;
}
if (isNoCopyField(fromField[i].getName())) {
continue;
}
toField = toClass.getDeclaredField(fromField[i].getName());
toField.setAccessible(true);
fromField[i].setAccessible(true);
toField.set(to, fromField[i].get(from));
}
//まりさ、れいむクラスのコピーはしない(意味がない)
//--------------------------------------------------
// 家族関係の再設定
Body partner = getBodyInstance(from.getPartner());
if (partner != null && getBodyInstance(partner.getPartner()) == from) {
partner.setPartner(to.getUniqueID());
}
if (from.getChildrenList() != null) {
for (int c : from.getChildrenList()) {
Body child = getBodyInstance(c);
if (child.getParents()[0] == from.getUniqueID()) {
child.getParents()[0] = to.getUniqueID();
}
if (child.getParents()[1] == from.getUniqueID()) {
child.getParents()[1] = to.getUniqueID();
}
}
}
//--------------------------------------------------
// 身分の補正
to.setBodyRank(from.getBodyRank());
to.setPublicRank(from.getPublicRank());
// 年齢の補正
switch (from.getBodyAgeState()) {
case BABY:
to.setAge(0);
break;
case CHILD:
to.setAge(to.getBABYLIMITorg() + 1);
break;
case ADULT:
default:
to.setAge(to.getCHILDLIMITorg() + 1);
break;
}
}
private static boolean isNoCopyField(String name) {
for (String f : NOCOPY_FIELD) {
if (f.equals(name)) {
return true;
}
}
return false;
}
/**
* 新規でアリがたかるかどうか判定し、判定hitの場合はアリをたからせる。
* @param b アリがたかるかどうか判定したいゆっくりのインスタンス
*/
public static void judgeNewAnt(Body b) {
int antProbability = 1;// アリのたかる確率
switch (b.getBodyAgeState()) {
case BABY:
antProbability = 240000;
break;
case CHILD:
antProbability = 480000;
break;
case ADULT:
antProbability = 960000;
break;
default:
//NOP.
}
// 汚い、またはダメージを受けていると倍の確率でたかられる
if (b.isDirty() || b.isDamaged()) {
antProbability /= 2;
}
// ジャンプできない状態だとさらに倍の確率
if (b.isDontJump()) {
antProbability /= 2;
}
if (SimYukkuri.RND.nextInt(antProbability) == 1) {
b.addAttachment(new Ants(b));
b.clearEvent();
}
}
/**
* ランダムなゆっくりタイプを取得する.
* ドスが親の場合は他のまりさが出る。
* @param parent 親のゆっくり(ドスチェック)
* @return ランダムなタイプのゆっくりタイプ(int)
*/
public static int getRandomYukkuriType(Body parent) {
int babyType = 0;
int i = SimYukkuri.RND.nextInt(5);
if (i == 0 || i == 1) {
babyType = SimYukkuri.RND.nextInt(12);
switch (babyType) {
case 0: // まりさ
case 8:
babyType = getMarisaType();
break;
case 1: // れいむ
case 9:
switch (SimYukkuri.RND.nextInt(5)) {
case 0:
case 2:
babyType = 1;//普通のれいむ
break;
case 1:
babyType = 2001;//わされいむ
break;
case 4:
babyType = 2007;//たりないれいむ
break;
case 3:
babyType = 2005;//でいぶ
break;
default:
babyType = 1;
}
break;
case 3: // ありす
babyType = 2;
break;
case 4: // みょん
babyType = 5;
break;
case 5: // ちぇん
babyType = 4;
break;
case 6: // たりないゆ
babyType = 2000;
break;
case 7: // ゆるさなえ
babyType = 1000;
break;
case 10: // ぱちゅりー
babyType = 3;
break;
case 11: //希少種
babyType = 1000 + SimYukkuri.RND.nextInt(12);
break;
}
} else {
if (parent != null) {
babyType = parent.getType();
// 親がドスなら他のまりさが均等に出る
if (babyType == 2006) {
babyType = getMarisaType();
}
} else {
babyType = SimYukkuri.RND.nextInt(6);
}
}
return babyType;
}
/**
* まりさの子供は何のまりさかランダムで決定。
* @return まりさの子供タイプ
*/
public static int getMarisaType() {
switch (SimYukkuri.RND.nextInt(5)) {
case 1:
return 2004;//こたつむり
case 2:
return 2002;//つむり
default:
return 0;
}
}
/**
* ユニークIDからゆっくりのインスタンスを取得する
* @param i ユニークID
* @return ユニークIDが指し示すゆっくり
*/
public static Body getBodyInstance(int i) {
if (i == -1) {
return null;
}
Map<Integer, Body> bodies = SimYukkuri.world.getCurrentMap().body;
if (bodies.containsKey(i)) {
return bodies.get(i);
}
return null;
}
/**
* オブジェクトIDからゆっくりを引いてくる
* @param i オブジェクトID
* @return 対象のゆっくり
*/
public static Body getBodyInstanceFromObjId(int i) {
if (i == -1) {
return null;
}
for (Map.Entry<Integer, Body> entry : SimYukkuri.world.getCurrentMap().body.entrySet()) {
Body b = entry.getValue();
if (b.objId == i) {
return b;
}
}
return null;
}
/**
* 現在のマップに属するゆっくりを配列にして返す.
* @return 現在のマップに属するゆっくりの配列
*/
public static Body[] getBodyInstances() {
List<Body> bodies = new LinkedList<>();
for (Map.Entry<Integer, Body> entry : SimYukkuri.world.getCurrentMap().body.entrySet()) {
Body p = entry.getValue();
bodies.add(p);
}
return bodies.toArray(new Body[0]);
}
/**
* リストから数値その値のもの(indexではなく)を取り除く
* @param list 取り除きたいリスト
* @param num 取り除きたい値
*/
public static void removeContent(List<Integer> list, int num) {
int removal = -1;
for (int i = 0; i < list.size();i++) {
int val = list.get(i);
if (val == num) {
removal = i;
break;
}
}
if (removal != -1) {
list.remove(removal);
}
}
}
| true |
0fb123eab2e2eeb16e40728800279af800b11c17 | Java | yaoyue6/OnlineMusic | /music-server/src/main/java/com/rg171/music/mapper/CommentMapper.java | UTF-8 | 1,356 | 2.140625 | 2 | [] | no_license | package com.rg171.music.mapper;
import com.rg171.music.entity.Comment;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @description: 评论
* @author: WangDongXu
**/
@Repository
public interface CommentMapper {
/**
* 插入
* @param record
* @return
*/
int insert(Comment record);
/**
* 插入非空字段
* @param record
* @return
*/
int insertSelective(Comment record);
/**
* 根据主键查询
* @param id
* @return
*/
Comment selectByPrimaryKey(Integer id);
/**
* 根据主键更新
* @param record
* @return
*/
int updateByPrimaryKey(Comment record);
/**
* 更新评论
* @param record
* @return
*/
int updateCommentMsg(Comment record);
/**
* 根据主键删除评论
* @param id
* @return
*/
int deleteComment(Integer id);
/**
* 获取所有评论
* @return
*/
List<Comment> allComment();
/**
* 根据歌曲ID获取该歌曲的全部评论
* @param songId
* @return
*/
List<Comment> commentOfSongId(Integer songId);
/**
* 根据歌单ID获取该歌单的全部评论
* @param songListId
* @return
*/
List<Comment> commentOfSongListId(Integer songListId);
}
| true |
4a8c388ab97543a87ddc1a09ffcffed6e4f48c85 | Java | abhi007tyagi/JavaExperiments | /JavaExperiments/src/tyagiabhinav/leetcode/MedianOfTwoSortedArray.java | UTF-8 | 1,275 | 3.265625 | 3 | [
"MIT"
] | permissive | package tyagiabhinav.leetcode;
import java.util.LinkedHashMap;
public class MedianOfTwoSortedArray {
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
double mid1 = getMid(nums1);
double mid2 = getMid(nums2);
double res = 0.0;
if(mid1 != 0.0 && mid2 != 0.0) res = (mid1 + mid2)/2;
else if(mid1 == 0.0 && mid2 != 0.0) res = mid2;
else if(mid1 != 0.0 && mid2 == 0.0) res = mid1;
return res;
}
private static double getMid(int[] nums){
int size = nums.length;
if (size == 0) return 0;
if (size == 1) return (double) nums[0];
if (size == 2) return (double) (nums[0]+nums[1])/2;
if (size%2 == 0) return (double) (nums[(size/2)-1] + nums[size/2])/2;
else return (double) nums[size/2];
}
public static void main(String[] args) {
int[] arr1 = {1,200,201,300,457}; //231.8
int[] arr2 = {2,39,67,69,79,87,101}; // 63.4
System.out.println(findMedianSortedArrays(arr1, arr2));
}
class LRUCache extends LinkedHashMap<Integer, Integer>{
public LRUCache(int initialCapacity, float loadFactor, boolean accessOrder) {
super(initialCapacity, loadFactor, accessOrder);
}
}
}
| true |
fff232bd862a48acf7b7a41a98b269596ff01560 | Java | hehuazheng/excel-util | /src/main/java/com/hhz/excel/support/AbstractSheetDefinition.java | UTF-8 | 612 | 2.15625 | 2 | [] | no_license | package com.hhz.excel.support;
import java.util.List;
import com.google.common.collect.Lists;
import com.hhz.excel.poi.FieldWrapper;
public abstract class AbstractSheetDefinition {
private int titleRowIndex = 1;
protected List<FieldWrapper> fieldWrapperList;
public AbstractSheetDefinition() {
fieldWrapperList = Lists.newArrayList();
}
public int getTitleRowIndex() {
return titleRowIndex;
}
public void setTitleRowIndex(int titleRowIndex) {
this.titleRowIndex = titleRowIndex;
}
public List<FieldWrapper> getFieldWrapperList() {
return fieldWrapperList;
}
}
| true |
8c63834c0461b23c89e6c41b511c9dabeeef530c | Java | Talend/avro-schema-editor | /org.talend.avro.schema.editor/src/org/talend/avro/schema/editor/viewer/SchemaPopupMenuConfigurationImpl.java | UTF-8 | 1,778 | 2.171875 | 2 | [
"Apache-2.0"
] | permissive | package org.talend.avro.schema.editor.viewer;
import org.eclipse.jface.action.ContributionManager;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.ui.menus.IMenuService;
import org.talend.avro.schema.editor.context.AvroContext;
import org.talend.avro.schema.editor.edit.services.IEditorServiceProvider;
public class SchemaPopupMenuConfigurationImpl implements PopupMenuConfiguration {
public static final String POPUP_MENU_ID = "popup:org.talend.avro.schema.editor.viewer.tree"; //$NON-NLS-1$
public static final String NEW_SECTION = "New Section"; //$NON-NLS-1$
public static final String OPEN_SECTION = "Open Section"; //$NON-NLS-1$
public static final String EXPAND_SECTION = "Expand Section"; //$NON-NLS-1$
private static final String[] ORDERED_SECTIONS = new String[] { NEW_SECTION, OPEN_SECTION, EXPAND_SECTION };
private IEditorServiceProvider serviceProvider;
private AvroContext context;
public SchemaPopupMenuConfigurationImpl(IEditorServiceProvider serviceProvider, AvroContext context) {
super();
this.serviceProvider = serviceProvider;
this.context = context;
}
protected IEditorServiceProvider getServiceProvider() {
return serviceProvider;
}
protected AvroContext getContext() {
return context;
}
protected String getPopupMenuId() {
return POPUP_MENU_ID + "." + context.getKind().toString().toLowerCase();
}
@Override
public void fillPopupMenu(IMenuManager manager, SchemaViewer viewer) {
for (String section : ORDERED_SECTIONS) {
manager.add(new Separator(section));
}
IMenuService service = serviceProvider.getMenuService();
service.populateContributionManager((ContributionManager) manager, getPopupMenuId());
}
}
| true |
78ba48883645e3d00a6f025a078a870b53434b8c | Java | 275288698/AndroidSoapServer | /src/edu/agh/wsserver/utils/dto/LocationDto.java | UTF-8 | 372 | 2.234375 | 2 | [] | no_license | package edu.agh.wsserver.utils.dto;
public class LocationDto {
public final double latitude;
public final double longitude;
public LocationDto(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
@Override
public String toString() {
return "LocationDto [latitude=" + latitude + ", longitude=" + longitude + "]";
}
} | true |
d9fc4e25fd978c832ea6a0f898a91941e12649b9 | Java | Tobaay/pdj-music | /src/java/Database/DAO.java | UTF-8 | 249 | 2.0625 | 2 | [] | no_license |
package Database;
import model.User;
public interface DAO {
public User getUser(String username, String password);
public User getUser(String username);
public void setUser(String username, String password, String email);
}
| true |
4ae2df956c7785e40c3751ef0afad738aa7eeb55 | Java | NYCComptroller/Checkbook-BDD | /src/test/java/io/reisys/checkbook/citywide/datafeeds/budget/DFBudgetPage.java | UTF-8 | 4,702 | 1.929688 | 2 | [] | no_license | package io.reisys.checkbook.citywide.datafeeds.budget;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
import io.reisys.checkbook.bdd.common.CheckbookBasePageObject;
public class DFBudgetPage extends CheckbookBasePageObject {
//private static final By DATAFEEDS_TAB = By.xpath("//a[@href ='/datafeeds']");
//private static final By DATAFEEDS_TAB = By.cssSelector("a[href='/datafeeds']");
private static final By DATAFEEDS_TAB = By.linkText("Data Feeds");
public static final By Datafeeds_option = By.xpath("//*[@id=\"edit-type-budget\"]");
public static final By Datafeeds_option_submit = By.xpath("//*[@id=\"edit-type-next\"]");
public static final By Datafeeds_select_citywide = By.xpath("//*[@id=\"edit-datafeeds-budget-domain-filter-checkbook\"]");
public static final By Datafeeds_add_all = By.linkText("Add All");
public static final By Datafeeds_default_submit = By.xpath("//*[@id=\"edit-feeds-budget-next\"]");
public void navigateToDatafeedsPage() {
findElement(DATAFEEDS_TAB).click();
}
public void navigateToDatafeedsBudgetPage() {
findElement(Datafeeds_option).click();
findElement(Datafeeds_option_submit).click();
//findElement(Datafeeds_select_nycha).click();
}
public void navigateToDatafeedscitywideBudgetPage()
{
findElement(Datafeeds_select_citywide).click();
}
public void navigateToDatafeedsCitywideBudgetSubmit1(){
findElement(Datafeeds_add_all).click();
findElement(Datafeeds_default_submit).click();
}
public String getTotalCountForDatfeeds() {
return findElement(By.xpath("//div[@class='records-result']")).getText().substring(9, 17);
}
public void clickOnBudgetFyDropdown(String value) {
// TODO Auto-generated method stub
Select dropdown = new Select(findElement(By.id("edit-fiscal-year")));
dropdown.selectByVisibleText(value);
}
public void clickOnAgencysDropdown(String value) {
// TODO Auto-generated method stub
Select dropdown = new Select(findElement(By.id("edit-agency")));
dropdown.selectByVisibleText(value);
}
public void clickOnDepartmentDropdown(String value) {
// TODO Auto-generated method stub
Select dropdown = new Select(findElement(By.id("edit-dept")));
dropdown.selectByVisibleText(value);
}
public void clickOnExpenseCategoryDropdown(String value) {
// TODO Auto-generated method stub
Select dropdown = new Select(findElement(By.id("edit-expense-category")));
dropdown.selectByVisibleText(value);
}
public void sendValueToBudgetCode(String value) {
// TODO Auto-generated method stub
findElement(By.id("edit-budget-code")).sendKeys(value);
}
public void enterRangeValueForAdoptedField(String from, String to) {
// TODO Auto-generated method stub
findElement(By.id("edit-adoptedfrom")).sendKeys(from);
findElement(By.id("edit-adoptedto")).sendKeys(to);
}
public void enterRangeValueForModifiedField(String from, String to) {
// TODO Auto-generated method stub
findElement(By.id("edit-currentfrom")).sendKeys(from);
findElement(By.id("edit-currentto")).sendKeys(to);
}
public void enterRangeValueForPreEncumberedField(String from, String to) {
// TODO Auto-generated method stub
findElement(By.id("edit-preencumberedfrom")).sendKeys(from);
findElement(By.id("edit-preencumberedto")).sendKeys(to);
}
public void enterRangeValueForEncumberedField(String from, String to) {
// TODO Auto-generated method stub
findElement(By.id("edit-encumberedfrom")).sendKeys(from);
findElement(By.id("edit-encumberedto")).sendKeys(to);
}
public void enterRangeValueForAccruedExpenseField(String from, String to) {
// TODO Auto-generated method stub
findElement(By.id("edit-accruedexpensefrom")).sendKeys(from);
findElement(By.id("edit-accruedexpenseto")).sendKeys(to);
}
public void enterRangeValueForCashPaymentsField(String from, String to) {
// TODO Auto-generated method stub
findElement(By.id("edit-cashfrom")).sendKeys(from);
findElement(By.id("edit-cashto")).sendKeys(to);
}
public void enterRangeValueForPostAdjustmentsField(String from, String to) {
// TODO Auto-generated method stub
findElement(By.id("edit-postadjustmentsfrom")).sendKeys(from);
findElement(By.id("edit-postadjustmentsto")).sendKeys(to);
}
public String getLabelName(String Xpath) {
return findElement(By.xpath("//label[@for=\""+Xpath+"\"]")).getText();
}
public String getDropDownDefaultValue(String value) {
// TODO Auto-generated method stub
Select select = new Select(findElement(By.id(value)));
String defaultItem = select.getFirstSelectedOption().getText();
return defaultItem;
}
}
| true |
bc5ab68f9360ca81268a69d9ebb19fb51ff5a9f7 | Java | gosin1994/zx | /src/main/java/com/zx/dao/ApplyDao2.java | UTF-8 | 567 | 1.765625 | 2 | [] | no_license | package com.zx.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.zx.common.page.Page;
import com.zx.entity.Apply2;
public interface ApplyDao2 {
int deleteByPrimaryKey(Integer id);
int insert(Apply2 record);
int insertSelective(Apply2 record);
Apply2 selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Apply2 record);
int updateByPrimaryKey(Apply2 record);
List<Apply2> selectAll(@Param("query")Apply2 query, Page<Apply2> page);
int updateMemberStateByCustomerId(Integer customerId);
} | true |
605956f48dc35c2057ca514698a94cf2765dec67 | Java | chinni73/Test1 | /src/main/resources/Employee.java | UTF-8 | 492 | 3.125 | 3 | [] | no_license |
public class Employee implements Comparable<Employee>
{
int id,salary;
String name;
Emplyoee(String name,int id,int salary)
{
this.name=name;
this.id=id;
this.salary=salary;
}
public int CompareTo(Employee el)
{
if(id==el.id)
{
return 0;
}
else if(id>el.id)
{
return 1;
}else
{
return -1;
}
}
}
| true |
7c438086905c8d0195df45f2d2ae290c7fe31be1 | Java | peluka613/weather-demo | /src/main/java/edu/weather/model/dto/LocationDto.java | UTF-8 | 222 | 1.78125 | 2 | [] | no_license | package edu.weather.model.dto;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class LocationDto {
private String lat;
private String lon;
private String city;
private String state;
}
| true |
48fa8047233a6fc0a8294e8a9454756103e6fb1c | Java | gverissi/Todo-list-mono | /src/test/java/com/example/todomono/controller/HomeControllerUnitTest.java | UTF-8 | 2,394 | 2.15625 | 2 | [] | no_license | package com.example.todomono.controller;
import com.example.todomono.entity.Role;
import com.example.todomono.exception.EntityAlreadyExistException;
import com.example.todomono.form.CustomerCreateForm;
import com.example.todomono.service.RoleService;
import com.example.todomono.service.customer.HomeService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
@WebMvcTest(controllers = HomeController.class, useDefaultFilters = false)
@DirtiesContext
class HomeControllerUnitTest {
@MockBean
private HomeService homeService;
@MockBean
private RoleService roleService;
@MockBean
private BindingResult result;
@MockBean
private Model model;
private HomeController homeController;
@BeforeEach
void init() {
homeController = new HomeController(homeService, roleService);
}
@Test
void showHomePage() {
// When
String viewName = homeController.showHomePage(model);
// Then
assertEquals("home/home", viewName);
}
@Test
void showLogInPage() {
// When
String viewName = homeController.showLogInPage(model);
// Then
assertEquals("home/log-in", viewName);
}
@Test
void showRegistrationForm() {
// When
String viewName = homeController.showRegistrationForm(model);
// Then
assertEquals("home/sign-up", viewName);
}
@Test
void registerNewCustomer() throws EntityAlreadyExistException {
// Given
CustomerCreateForm customerCreateForm = new CustomerCreateForm("toto", "1234", "1234");
Role roleMock = mock(Role.class);
when(roleService.findByRoleName("USER")).thenReturn(roleMock);
// When
String viewName = homeController.registerNewCustomer(customerCreateForm, result, model);
// Then
verify(homeService).createCustomer(customerCreateForm, roleMock);
assertEquals("redirect:/home/log-in?registered", viewName);
}
} | true |
f2ec1ff655628efc089283ae96445cc28f0896ba | Java | mpeychev/Villie | /src/interpreter/loader/RecursiveLoader.java | UTF-8 | 968 | 2.4375 | 2 | [
"MIT"
] | permissive | // Author: Momchil Peychev
package interpreter.loader;
import java.util.HashMap;
import interpreter.evaluator.EvaluationTree;
import interpreter.evaluator.RunTimeErrorException;
import interpreter.lexer.LexerErrorException;
import interpreter.parser.AbstractSyntaxTree;
import interpreter.parser.Expression;
import interpreter.parser.NodeType;
import interpreter.parser.ParserErrorException;
public class RecursiveLoader extends Loader {
public RecursiveLoader(String file) throws LexerErrorException, ParserErrorException {
super(file);
}
@Override
public void run() throws ParserErrorException, LexerErrorException, RunTimeErrorException {
for (Expression expression : expressions) {
AbstractSyntaxTree ast = new AbstractSyntaxTree(NodeType.E, expression,
functionNameToDefinition);
EvaluationTree et = new EvaluationTree(ast);
System.out.println(et.toRecursiveEvaluation().evaluate(this, new HashMap<>()));
}
}
}
| true |
018c3322a78f376f2033fad101bf419e48abaa85 | Java | ZoranLi/wechat_reversing | /com/tencent/mm/plugin/game/model/r.java | UTF-8 | 3,661 | 1.570313 | 2 | [] | no_license | package com.tencent.mm.plugin.game.model;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.plugin.game.d.c;
import com.tencent.mm.plugin.game.model.q.d;
import com.tencent.mm.plugin.game.ui.GameMessageUI;
import com.tencent.mm.pluginsdk.model.app.g;
import com.tencent.mm.sdk.platformtools.bg;
import com.tencent.mm.sdk.platformtools.w;
public final class r implements OnClickListener {
private Context mContext;
public int mqT;
public static class a {
public int fTL = 1301;
public q mpa;
public String mqQ;
public int position;
public a(q qVar, String str, int i) {
this.mpa = qVar;
this.mqQ = str;
this.position = i;
}
}
public r(Context context) {
this.mContext = context;
}
public r(Context context, int i) {
this.mContext = context;
this.mqT = i;
}
public final void onClick(View view) {
if (view.getTag() == null || !(view.getTag() instanceof a)) {
w.e("MicroMsg.GameMessageClickListener", "v.getTag is null");
return;
}
a aVar = (a) view.getTag();
if (aVar.mpa == null) {
w.e("MicroMsg.GameMessageClickListener", "message is null");
} else if (aVar.mqQ == null) {
w.e("MicroMsg.GameMessageClickListener", "jumpId is null");
} else {
d dVar = (d) aVar.mpa.mpU.get(aVar.mqQ);
if (dVar == null) {
w.e("MicroMsg.GameMessageClickListener", "jumpInfo is null");
return;
}
int a = a(this.mContext, aVar.mpa, dVar, aVar.mpa.field_appId, aVar.fTL);
if (a != 0) {
ai.a(this.mContext, 13, aVar.fTL, aVar.position, a, 0, aVar.mpa.field_appId, this.mqT, aVar.mpa.mqy, aVar.mpa.field_gameMsgId, aVar.mpa.mqz, null);
}
}
}
public static int a(Context context, q qVar, d dVar, String str, int i) {
int i2 = 0;
switch (dVar.mqH) {
case 1:
if (!g.n(context, str)) {
return d(context, str, i);
}
e.V(context, str);
return 3;
case 2:
if (!g.n(context, str)) {
return 0;
}
e.V(context, str);
return 3;
case 3:
return d(context, str, i);
case 4:
if (qVar != null) {
qVar.field_isRead = true;
SubCoreGameCenter.aBB().c(qVar, new String[0]);
}
Intent intent = new Intent(context, GameMessageUI.class);
intent.putExtra("game_report_from_scene", i);
context.startActivity(intent);
return 6;
case 5:
String str2 = dVar.lkK;
if (!bg.mA(str2)) {
c.aa(context, str2);
i2 = 7;
}
return i2;
default:
w.i("MicroMsg.GameMessageClickListener", "unknown msg jump type = " + dVar.mqH);
return 0;
}
}
private static int d(Context context, String str, int i) {
if (bg.mA(str)) {
return 0;
}
Bundle bundle = new Bundle();
bundle.putCharSequence("game_app_id", str);
bundle.putInt("game_report_from_scene", i);
return c.a(context, str, null, bundle);
}
}
| true |
8a6907d547d62ef41d67351d440616f51e03e7e2 | Java | TomSpencerLondon/Design-Patterns-in-Java | /src/main/java/StructruralDesignPatterns/Flyweight/FormattedText.java | UTF-8 | 963 | 3.515625 | 4 | [] | no_license | package StructruralDesignPatterns.Flyweight;
import java.util.ArrayList;
import java.util.List;
public class FormattedText {
private String plainText;
private List<TextRange> formatting = new ArrayList<>();
FormattedText(String plainText) {
this.plainText = plainText;
}
TextRange getRange(int start, int end) {
TextRange range = new TextRange(start, end);
formatting.add(range);
return range;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < plainText.length(); ++i) {
char letter = plainText.charAt(i);
for (TextRange range : formatting) {
if (range.covers(i) && range.capitalize) {
letter = Character.toUpperCase(letter);
}
}
stringBuilder.append(letter);
}
return stringBuilder.toString();
}
} | true |
5455eb6c7a1ebce296aae8c0c3d40cf24db5a182 | Java | immortalcatz/HelperTools | /src/main/java/helpertools/tools/ItemEuclideanTransposer.java | UTF-8 | 16,372 | 1.679688 | 2 | [
"MIT"
] | permissive | package helpertools.tools;
import java.util.List;
import java.util.Random;
import helpertools.Mod_Registry;
import helpertools.HelpTab;
import helpertools.Main;
import helpertools.blocks.tile_entities.TileEntityTranscriber;
import helpertools.util.InventoryUtil;
import helpertools.util.Whitelist_Util;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.effect.EntityLightningBolt;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemSpade;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Item.ToolMaterial;
import net.minecraft.item.ItemSword;
import net.minecraft.item.ItemTool;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.StatCollector;
import net.minecraft.util.Vec3;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import net.minecraftforge.event.world.ChunkEvent;
public class ItemEuclideanTransposer extends ItemTool
{
public ItemEuclideanTransposer(ToolMaterial material)
{
super (2,material, Mod_Registry.properharvest);
this.maxStackSize = 1;
setUnlocalizedName("euclideantransposer");
setCreativeTab(HelpTab.HelperTools);
setTextureName("helpertools:EuWand1");
}
//////////////////
protected static Random growrand = new Random();
////////////////////////////////////////////////
//flavor text
@Override
public void addInformation(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, List par3List, boolean par4)
{
par3List.add(EnumChatFormatting.WHITE + "Sets blocks in a 5^cube pattern");
par3List.add(EnumChatFormatting.ITALIC + "Use while sneaking for a pattern");
par3List.add(" ");
par3List.add(EnumChatFormatting.ITALIC + "Can also be used with");
par3List.add(EnumChatFormatting.ITALIC + "- Transcriber Block");
}
/////////////////////////////////////////////////////////////
public int getMode(ItemStack itemStack)
{
if(itemStack.stackTagCompound == null)
{
return 0;
}
return itemStack.stackTagCompound.getInteger("mode");
}
public boolean isMetadataSpecific(ItemStack itemStack)
{
return false;
}
///////////////////////////////////////////
public void setMode(ItemStack itemStack, int Value)
{
if(itemStack.stackTagCompound == null)
{
itemStack.setTagCompound(new NBTTagCompound());
}
itemStack.stackTagCompound.setInteger("mode", Value );
//this.tagMap.put(p_74768_1_, new NBTTagInt(p_74768_2_));
}
///////////////////
public int getTBlock(ItemStack itemStack, int Nbtcount)
{
if(itemStack.stackTagCompound == null)
{
return 0;
}
return itemStack.stackTagCompound.getInteger("TBlock" + Nbtcount);
}
public void setTBlock(ItemStack itemStack, int Value, int Nbtcount)
{
if(itemStack.stackTagCompound == null)
{
itemStack.setTagCompound(new NBTTagCompound());
}
itemStack.stackTagCompound.setInteger("TBlock" + Nbtcount, Value );
//this.tagMap.put(p_74768_1_, new NBTTagInt(p_74768_2_));
}
////////
public int getTMeta(ItemStack itemStack, int Nbtcount)
{
if(itemStack.stackTagCompound == null)
{
return 0;
}
return itemStack.stackTagCompound.getInteger("TMeta" + Nbtcount);
}
public void setTMeta(ItemStack itemStack, int Value, int Nbtcount)
{
if(itemStack.stackTagCompound == null)
{
itemStack.setTagCompound(new NBTTagCompound());
}
itemStack.stackTagCompound.setInteger("TMeta"+ Nbtcount, Value );
//this.tagMap.put(p_74768_1_, new NBTTagInt(p_74768_2_));
}
//////
public int returnTMeta(ItemStack thestaff, int Nbtcount)
{
return getTMeta(thestaff, Nbtcount);
}
public Block returnTBlock(ItemStack thestaff, int Nbtcount)
{
return Block.getBlockById(getTBlock(thestaff, Nbtcount));
}
/** Offmode here prevents getblock from double dipping into switch mode code**/
// ///////////////////////////////////////////////////////////
public int getOffMode(ItemStack itemStack) {
if (itemStack.stackTagCompound == null) {
return 0;
}
return itemStack.stackTagCompound.getInteger("OffMode");
}
public void setOffMode(ItemStack itemStack, int Value) {
if (itemStack.stackTagCompound == null) {
itemStack.setTagCompound(new NBTTagCompound());
}
itemStack.stackTagCompound.setInteger("OffMode", Value);
}
////////////////////////
/** Rotation Counter**/
public int getCorner(ItemStack itemStack) {
if (itemStack.stackTagCompound == null) {
return 0;
}
return itemStack.stackTagCompound.getInteger("Corner");
}
public void setCorner(ItemStack itemStack, int Value) {
if (itemStack.stackTagCompound == null) {
itemStack.setTagCompound(new NBTTagCompound());
}
itemStack.stackTagCompound.setInteger("Corner", Value);
}
//////////////////////////////////////////////////////////////
/** should make an complex interface like this to cut down on space, using string tree to call... Zzzzz
public int getTMeta(ItemStack itemStack, int Nbtcount, String get)
{
if(itemStack.stackTagCompound == null)
{
return 0;
}
return itemStack.stackTagCompound.getInteger("TMeta" + Nbtcount);
}
**/
//Generic tool stuff
public boolean onBlockDestroyed(ItemStack p_150894_1_, World p_150894_2_, Block p_150894_3_, int p_150894_4_, int p_150894_5_, int p_150894_6_, EntityLivingBase p_150894_7_)
{
if ((double)p_150894_3_.getBlockHardness(p_150894_2_, p_150894_4_, p_150894_5_, p_150894_6_) != 0.0D)
{
p_150894_1_.damageItem(2, p_150894_7_);
}
return true;
}
public boolean hitEntity(ItemStack p_77644_1_, EntityLivingBase p_77644_2_, EntityLivingBase p_77644_3_)
{
p_77644_1_.damageItem(2, p_77644_3_);
return true;
}
//Custom mode changing code
@Override
public boolean onEntitySwing(EntityLivingBase entityLiving, ItemStack stack)
{
if (getMode(stack)== 0)
{
setMode(stack, 2);
}
if (getOffMode(stack)== 0)
{
setOffMode(stack, 2);
}
if (!entityLiving.worldObj.isRemote) {
if (entityLiving.isSneaking()&& getOffMode(stack)== 2)
{
if (getMode(stack) == 4)
{
//entityLiving.playSound("mob.chicken.plop", 3.0F, .3F);
entityLiving.worldObj.playSoundAtEntity(entityLiving, "mob.chicken.plop", 3F, .3F);
ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation(EnumChatFormatting.GRAY + "Flush Mode", new Object[0]);
((EntityPlayer) entityLiving).addChatComponentMessage(chatcomponenttranslation);
setMode(stack,2);
return true;
}
else if (getMode(stack) == 2)
{
ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation(EnumChatFormatting.GRAY + "Submerged -1", new Object[0]);
((EntityPlayer) entityLiving).addChatComponentMessage(chatcomponenttranslation);
//entityLiving.playSound("mob.chicken.plop", .3F, 3.0F);}
entityLiving.worldObj.playSoundAtEntity(entityLiving, "mob.chicken.plop", .3F, 3.0F);
setMode(stack,4);
}
return true;
}
}
if (getOffMode(stack)== 4)
{
setOffMode(stack, 2);
}
return false;
}
//The guts of the placement code
/** This is a huge mess **/
//Basically It will go through checks and determine what action it should perform next
/**During this, it looks for Which mode -> Which face of the block
* -> Which blocks are legal -> If they are legal, place or swap
* -> And finally depending on which gamemode to remove durability and items**/
public boolean onItemUse(ItemStack thestaff, EntityPlayer player, World world, int i1, int j1, int k1, int theface, float p_77648_8_, float p_77648_9_, float p_77648_10_)
{
float py = (this.growrand .nextFloat()) ;
int mOffset = ((((getMode(thestaff)/2)*-1) +1));
if (getOffMode(thestaff)== 0)
{
setOffMode(thestaff, 2);
}
/////////////////////////////
/** placement and get code**/
////////////////////////////
int successful = 0;
int P = 5;
int proxyskip = 0;
if (!player.isSneaking()){
//placement via transcriber proxy
if(world.getBlock(i1, j1, k1) == Mod_Registry.TranscriberBlock){
TileEntityTranscriber tile = (TileEntityTranscriber)world.getTileEntity(i1, j1, k1);
if (tile != null)
{
//ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation(
// "Tile Detected" + (tile).offX, new Object[0]);
//((EntityPlayer) player)
// .addChatComponentMessage(chatcomponenttranslation);
i1 = i1 -2 + (tile.offX);
j1 = j1 -1 + (tile.offY);
k1 = k1 -2 + (tile.offZ);
proxyskip = 1;
}
}
//placement via staff
if(world.getBlock(i1, j1, k1) != Mod_Registry.TranscriberBlock
&& proxyskip == 0){
//dynamic placement offsets
//W/E_T/B_N/S
if (theface == 0){
j1 = j1 - mOffset -6;
i1 = i1 - 2;
k1 = k1 - 2;
}
if (theface == 1){
j1 = mOffset + j1;
i1 = i1 - 2;
k1 = k1 - 2;
}
//North south
if (theface == 2){
j1 = j1-3;
i1 = i1 - 2;
k1 = k1 - 5 -mOffset;
}
if (theface == 3){
j1 = j1-3;
i1 = i1 - 2;
k1 = k1 +1 +mOffset;
}
//West East
if (theface == 4){
j1 = j1-3;
i1 = i1 - 5 -mOffset;
k1 = k1 -2 ;
}
if (theface == 5){
j1 = j1-3;
i1 = i1 +1 +mOffset;
k1 = k1 -2 ;
}
}
for (int G2 = 0; G2 < P; ++G2)
{
int G2counter = G2*P*P;
for (int U = 0; U < P; ++U)
{
int Ucounter = U*P;
for (int l = 0; l < P; ++l)
{
int Nbtcounter = G2counter+Ucounter+l+1;
int X_1 = i1+U;
int Y_1 = j1+1+l;
int Z_1 = k1+G2;
if (returnTBlock(thestaff, Nbtcounter) != Blocks.air){
/** displacement whitelist **/
if (world.isAirBlock(X_1 , Y_1 , Z_1 )
|| world.getBlock(X_1 , Y_1 , Z_1 ).getMaterial() == Material.lava
|| world.getBlock(X_1 , Y_1 , Z_1 ).getMaterial() == Material.water
|| world.getBlock(X_1 , Y_1 , Z_1 ).getMaterial() == Material.plants
|| world.getBlock(X_1 , Y_1 , Z_1 ).getMaterial() == Material.vine )
{
ItemStack stacky = new ItemStack (Item.getItemFromBlock(returnTBlock(thestaff, Nbtcounter)),0, returnTMeta(thestaff, Nbtcounter));
Boolean whitelist_flag;
whitelist_flag = Whitelist_Util.Block_Whitelist(returnTBlock(thestaff, Nbtcounter), player, returnTMeta(thestaff, Nbtcounter));
if (player.capabilities.isCreativeMode|| player.inventory.hasItemStack(stacky)
||whitelist_flag
){
//world.playSoundEffect((double)((float)X_1 + 0.5F), (double)((float)Y_1 + 0.5F), (double)((float)Z_1 + 0.5F), returnTBlock(thestaff, Nbtcounter).stepSound.getStepResourcePath(), (returnTBlock(thestaff, Nbtcounter).stepSound.getVolume() + 1.0F) / 2.0F, returnTBlock(thestaff, Nbtcounter).stepSound.getPitch() * 0.8F);
/** plants reinbursement **/ /**Having to work around blocks like this isn't fun **/
if (world.getBlock(X_1 , Y_1 , Z_1 ).getMaterial() == Material.vine
|| world.getBlock(X_1 , Y_1 , Z_1 ).getMaterial() == Material.plants)
{
(world.getBlock(X_1 , Y_1 , Z_1 )).dropBlockAsItem(world,X_1 , Y_1 , Z_1 , (world.getBlockMetadata(X_1 , Y_1 , Z_1 )), 0);
}
world.setBlock(X_1 , Y_1 , Z_1 , Blocks.dirt);
world.setBlock(X_1 , Y_1 , Z_1 , returnTBlock(thestaff, Nbtcounter), (returnTMeta(thestaff, Nbtcounter)), 0);
successful = 1;
short short1 = 32;
for (int lp = 0; lp < short1; ++lp)
{
double d6 = (double)lp / ((double)short1 - 1.0D);
float f = (this.growrand.nextFloat() - .5F) * 1.4F;
float f1 = (this.growrand .nextFloat() - .5F) * 1.4F;
float f2 = (this.growrand .nextFloat() - .5F) * 1.4F;
float p = (this.growrand.nextFloat()) ;
float p1 = (this.growrand .nextFloat() ) ;
float p2 = (this.growrand .nextFloat() ) ;
world.spawnParticle("portal", X_1 +p+.1, j1+.6+l+p1, Z_1 +p2+.1, f, f1, f2);
}
if (!player.capabilities.isCreativeMode){
if(!whitelist_flag)InventoryUtil.consumeInventoryItemStack(stacky, player.inventory);
if(whitelist_flag){
Whitelist_Util.Consume_Whitelist(stacky, player, returnTBlock(thestaff, Nbtcounter), returnTMeta(thestaff, Nbtcounter));
//player.inventory.consumeInventoryItem(item);
}
thestaff.damageItem(1, player);
}
}
}
}
}
}
}
if (successful == 1){
player.worldObj.playSoundAtEntity(player, "mob.endermen.portal", 1.2F, .5F+py);
player.worldObj.playSoundAtEntity(player, "mob.endermen.portal", 1.7F, .5F+py);
successful = 0;
return true;
}
if (successful ==0){
player.worldObj.playSoundAtEntity(player, "random.click",.4F, itemRand.nextFloat() * 0.4F + 0.5F);
successful = 0;
return true;
}
}
/////////////////////////////
/** Pattern Collection **/
if (player.isSneaking()){
if(world.getBlock(i1, j1, k1) == Mod_Registry.TranscriberBlock){
TileEntityTranscriber tile = (TileEntityTranscriber)world.getTileEntity(i1, j1, k1);
if (tile != null)
{
//player.worldObj.playSoundAtEntity(player, "mob.ghast.fireball", 1.2F, .2F+py/5);
i1 = i1 + (tile.offX);
j1 = j1 + (tile.offY);
k1 = k1 + (tile.offZ);
}
}
i1 = i1 - 2;
k1 = k1 - 2;
/** Z **/
for (int G2 = 0; G2 < P; ++G2)
{
int G2counter = G2*P*P;
/** X **/
for (int U = 0; U < P; ++U)
{
int Ucounter = U*P;
/** Y **/
for (int l = 0; l < P; ++l)
{
int Nbtcounter = G2counter+Ucounter+l+1;
setTBlock(thestaff, world.getBlock(i1+U, j1+l, k1+G2).getIdFromBlock(world.getBlock(i1+U, j1+l, k1+G2)), Nbtcounter);
setTMeta(thestaff,world.getBlockMetadata(i1+U, j1+l, k1+G2), Nbtcounter);
}
}
}
if(!player.worldObj.isRemote){
ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation(
EnumChatFormatting.GRAY + "Pattern Saved", new Object[0]);
((EntityPlayer) player)
.addChatComponentMessage(chatcomponenttranslation);
player.worldObj.playSoundAtEntity(player, "mob.ghast.fireball", 1.5F, .2F+py/4);
}
setOffMode(thestaff, 4);
return true;
}
return false;
}
@SideOnly(Side.CLIENT)
public boolean isFull3D()
{
return true;
}
} | true |
9520ed6cecda8f5b7312a2c5bb5caad04ebb2b58 | Java | tasomaniac/SeriesGuide | /SeriesGuide/src/main/java/com/battlelancer/seriesguide/util/MovieTools.java | UTF-8 | 42,295 | 1.570313 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2014 Uwe Trottmann
*
* 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.battlelancer.seriesguide.util;
import android.content.ContentProviderOperation;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import com.battlelancer.seriesguide.backend.HexagonTools;
import com.battlelancer.seriesguide.backend.settings.HexagonSettings;
import com.battlelancer.seriesguide.items.MovieDetails;
import com.battlelancer.seriesguide.provider.SeriesGuideContract;
import com.battlelancer.seriesguide.settings.DisplaySettings;
import com.battlelancer.seriesguide.settings.TraktCredentials;
import com.battlelancer.seriesguide.settings.TraktSettings;
import com.battlelancer.seriesguide.util.tasks.AddMovieToCollectionTask;
import com.battlelancer.seriesguide.util.tasks.AddMovieToWatchlistTask;
import com.battlelancer.seriesguide.util.tasks.RateMovieTask;
import com.battlelancer.seriesguide.util.tasks.RemoveMovieFromCollectionTask;
import com.battlelancer.seriesguide.util.tasks.RemoveMovieFromWatchlistTask;
import com.battlelancer.seriesguide.util.tasks.SetMovieUnwatchedTask;
import com.battlelancer.seriesguide.util.tasks.SetMovieWatchedTask;
import com.google.api.client.util.DateTime;
import com.uwetrottmann.androidutils.AndroidUtils;
import com.uwetrottmann.seriesguide.backend.movies.model.MovieList;
import com.uwetrottmann.tmdb.services.MoviesService;
import com.uwetrottmann.trakt.v2.TraktV2;
import com.uwetrottmann.trakt.v2.entities.BaseMovie;
import com.uwetrottmann.trakt.v2.entities.LastActivityMore;
import com.uwetrottmann.trakt.v2.entities.MovieIds;
import com.uwetrottmann.trakt.v2.entities.Ratings;
import com.uwetrottmann.trakt.v2.entities.SearchResult;
import com.uwetrottmann.trakt.v2.entities.SyncItems;
import com.uwetrottmann.trakt.v2.entities.SyncMovie;
import com.uwetrottmann.trakt.v2.enums.Extended;
import com.uwetrottmann.trakt.v2.enums.IdType;
import com.uwetrottmann.trakt.v2.enums.Rating;
import com.uwetrottmann.trakt.v2.exceptions.OAuthUnauthorizedException;
import com.uwetrottmann.trakt.v2.services.Movies;
import com.uwetrottmann.trakt.v2.services.Search;
import com.uwetrottmann.trakt.v2.services.Sync;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import android.support.annotation.NonNull;
import retrofit.RetrofitError;
import timber.log.Timber;
import static com.battlelancer.seriesguide.sync.SgSyncAdapter.UpdateResult;
public class MovieTools {
private static final int MOVIES_MAX_BATCH_SIZE = 100;
public static class MovieChangedEvent {
public int movieTmdbId;
public MovieChangedEvent(int movieTmdbId) {
this.movieTmdbId = movieTmdbId;
}
}
public enum Lists {
COLLECTION(SeriesGuideContract.Movies.IN_COLLECTION),
WATCHLIST(SeriesGuideContract.Movies.IN_WATCHLIST);
public final String databaseColumn;
private Lists(String databaseColumn) {
this.databaseColumn = databaseColumn;
}
}
/**
* Deletes all movies which are not watched and not in any list.
*/
public static void deleteUnusedMovies(Context context) {
int rowsDeleted = context.getContentResolver()
.delete(SeriesGuideContract.Movies.CONTENT_URI,
SeriesGuideContract.Movies.SELECTION_UNWATCHED
+ " AND " + SeriesGuideContract.Movies.SELECTION_NOT_COLLECTION
+ " AND " + SeriesGuideContract.Movies.SELECTION_NOT_WATCHLIST,
null);
Timber.d("deleteUnusedMovies: removed " + rowsDeleted + " movies");
}
public static void addToCollection(Context context, int movieTmdbId) {
AndroidUtils.executeOnPool(new AddMovieToCollectionTask(context, movieTmdbId));
}
public static void addToWatchlist(Context context, int movieTmdbId) {
AndroidUtils.executeOnPool(new AddMovieToWatchlistTask(context, movieTmdbId));
}
/**
* Adds the movie to the given list. If it was not in any list before, adds the movie to the
* local database first.
*
* @return If the database operation was successful.
*/
public static boolean addToList(Context context, int movieTmdbId, Lists list) {
// do we have this movie in the database already?
Boolean movieExists = isMovieInDatabase(context, movieTmdbId);
if (movieExists == null) {
return false;
}
if (movieExists) {
return updateMovie(context, movieTmdbId, list.databaseColumn, true);
} else {
return addMovie(context, movieTmdbId, list);
}
}
public static void removeFromCollection(Context context, int movieTmdbId) {
AndroidUtils.executeOnPool(new RemoveMovieFromCollectionTask(context, movieTmdbId));
}
public static void removeFromWatchlist(Context context, int movieTmdbId) {
AndroidUtils.executeOnPool(new RemoveMovieFromWatchlistTask(context, movieTmdbId));
}
/**
* Removes the movie from the given list.
*
* <p>If it would not be on any list afterwards and is not watched, deletes the movie from the
* local database.
*
* @return If the database operation was successful.
*/
public static boolean removeFromList(Context context, int movieTmdbId, Lists listToRemoveFrom) {
Lists otherListToCheck = listToRemoveFrom == Lists.COLLECTION
? Lists.WATCHLIST : Lists.COLLECTION;
Boolean isInOtherList = isMovieInList(context, movieTmdbId, otherListToCheck);
if (isInOtherList == null) {
// query failed, or movie not in local database
return false;
}
// if movie will not be in any list and is not watched, remove it completely
if (!isInOtherList && deleteMovieIfUnwatched(context, movieTmdbId)) {
return true;
} else {
// otherwise, just update
return updateMovie(context, movieTmdbId, listToRemoveFrom.databaseColumn, false);
}
}
public static void watchedMovie(Context context, int movieTmdbId) {
AndroidUtils.executeOnPool(new SetMovieWatchedTask(context, movieTmdbId));
}
public static void unwatchedMovie(Context context, int movieTmdbId) {
AndroidUtils.executeOnPool(new SetMovieUnwatchedTask(context, movieTmdbId));
}
/**
* Set watched flag of movie in local database. If setting watched, but not in database, creates
* a new movie watched shell.
*
* @return If the database operation was successful.
*/
public static boolean setWatchedFlag(Context context, int movieTmdbId, boolean flag) {
Boolean movieInDatabase = isMovieInDatabase(context, movieTmdbId);
if (movieInDatabase == null) {
return false;
}
if (!movieInDatabase && flag) {
// Only add, never remove shells. Next trakt watched movie sync will take care of that.
return addMovieWatchedShell(context, movieTmdbId);
} else {
return updateMovie(context, movieTmdbId, SeriesGuideContract.Movies.WATCHED, flag);
}
}
/**
* Store the rating for the given movie in the database (if it is in the database) and send it
* to trakt.
*/
public static void rate(Context context, int movieTmdbId, Rating rating) {
AndroidUtils.executeOnPool(new RateMovieTask(context, rating, movieTmdbId));
}
private static ContentValues[] buildMoviesContentValues(List<MovieDetails> movies) {
ContentValues[] valuesArray = new ContentValues[movies.size()];
int index = 0;
for (MovieDetails movie : movies) {
valuesArray[index] = buildMovieContentValues(movie);
index++;
}
return valuesArray;
}
private static ContentValues buildMovieContentValues(MovieDetails details) {
ContentValues values = buildBasicMovieContentValuesWithId(details);
values.put(SeriesGuideContract.Movies.IN_COLLECTION,
DBUtils.convertBooleanToInt(details.inCollection));
values.put(SeriesGuideContract.Movies.IN_WATCHLIST,
DBUtils.convertBooleanToInt(details.inWatchlist));
return values;
}
/**
* Extracts basic properties, except in_watchlist and in_collection from trakt. Also includes
* the TMDb id and watched state as value.
*/
private static ContentValues buildBasicMovieContentValuesWithId(MovieDetails details) {
ContentValues values = buildBasicMovieContentValues(details);
values.put(SeriesGuideContract.Movies.TMDB_ID, details.tmdbMovie().id);
return values;
}
/**
* Extracts ratings from trakt, all other properties from TMDb data.
*
* <p> If either movie data is null, will still extract the properties of others.
*/
public static ContentValues buildBasicMovieContentValues(MovieDetails details) {
ContentValues values = new ContentValues();
// data from trakt
if (details.traktRatings() != null) {
values.put(SeriesGuideContract.Movies.RATING_TRAKT,
details.traktRatings().rating);
values.put(SeriesGuideContract.Movies.RATING_VOTES_TRAKT,
details.traktRatings().votes);
}
// data from TMDb
if (details.tmdbMovie() != null) {
values.put(SeriesGuideContract.Movies.IMDB_ID, details.tmdbMovie().imdb_id);
values.put(SeriesGuideContract.Movies.TITLE, details.tmdbMovie().title);
values.put(SeriesGuideContract.Movies.TITLE_NOARTICLE,
DBUtils.trimLeadingArticle(details.tmdbMovie().title));
values.put(SeriesGuideContract.Movies.OVERVIEW, details.tmdbMovie().overview);
values.put(SeriesGuideContract.Movies.POSTER, details.tmdbMovie().poster_path);
values.put(SeriesGuideContract.Movies.RUNTIME_MIN, details.tmdbMovie().runtime);
values.put(SeriesGuideContract.Movies.RATING_TMDB, details.tmdbMovie().vote_average);
values.put(SeriesGuideContract.Movies.RATING_VOTES_TMDB, details.tmdbMovie().vote_count);
// if there is no release date, store Long.MAX as it is likely in the future
// also helps correctly sorting movies by release date
Date releaseDate = details.tmdbMovie().release_date;
values.put(SeriesGuideContract.Movies.RELEASED_UTC_MS,
releaseDate == null ? Long.MAX_VALUE : releaseDate.getTime());
}
return values;
}
/**
* Returns a set of the TMDb ids of all movies in the local database.
*
* @return null if there was an error, empty list if there are no movies.
*/
public static HashSet<Integer> getMovieTmdbIdsAsSet(Context context) {
HashSet<Integer> localMoviesIds = new HashSet<>();
Cursor movies = context.getContentResolver().query(SeriesGuideContract.Movies.CONTENT_URI,
new String[] { SeriesGuideContract.Movies.TMDB_ID },
null, null, null);
if (movies == null) {
return null;
}
while (movies.moveToNext()) {
localMoviesIds.add(movies.getInt(0));
}
movies.close();
return localMoviesIds;
}
/**
* Determines if the movie is in the given list.
*
* @return true if the movie is in the given list, false otherwise. Can return {@code null} if
* the database could not be queried or the movie does not exist.
*/
private static Boolean isMovieInList(Context context, int movieTmdbId, Lists list) {
Cursor movie = context.getContentResolver()
.query(SeriesGuideContract.Movies.buildMovieUri(movieTmdbId),
new String[] { list.databaseColumn }, null, null, null);
if (movie == null) {
return null;
}
Boolean isInList = null;
if (movie.moveToFirst()) {
isInList = movie.getInt(0) == 1;
}
movie.close();
return isInList;
}
private static Boolean isMovieInDatabase(Context context, int movieTmdbId) {
Cursor movie = context.getContentResolver()
.query(SeriesGuideContract.Movies.CONTENT_URI, new String[] {
SeriesGuideContract.Movies._ID },
SeriesGuideContract.Movies.TMDB_ID + "=" + movieTmdbId, null, null);
if (movie == null) {
return null;
}
boolean movieExists = movie.getCount() > 0;
movie.close();
return movieExists;
}
private static boolean addMovie(Context context, int movieTmdbId, Lists listToAddTo) {
// get movie info
MovieDetails details = Download.getMovieDetails(context, movieTmdbId);
if (details.tmdbMovie() == null) {
// abort if minimal data failed to load
return false;
}
// build values
ContentValues values = buildBasicMovieContentValuesWithId(details);
// set flags
values.put(SeriesGuideContract.Movies.IN_COLLECTION,
DBUtils.convertBooleanToInt(listToAddTo == Lists.COLLECTION));
values.put(SeriesGuideContract.Movies.IN_WATCHLIST,
DBUtils.convertBooleanToInt(listToAddTo == Lists.WATCHLIST));
// add to database
context.getContentResolver().insert(SeriesGuideContract.Movies.CONTENT_URI, values);
// ensure ratings and watched flags are downloaded on next sync
TraktSettings.resetMoviesLastActivity(context);
return true;
}
/**
* Inserts a movie shell into the database only holding TMDB id, list and watched states.
*/
private static boolean addMovieWatchedShell(Context context, int movieTmdbId) {
ContentValues values = new ContentValues();
values.put(SeriesGuideContract.Movies.TMDB_ID, movieTmdbId);
values.put(SeriesGuideContract.Movies.IN_COLLECTION, false);
values.put(SeriesGuideContract.Movies.IN_WATCHLIST, false);
values.put(SeriesGuideContract.Movies.WATCHED, true);
Uri insert = context.getContentResolver().insert(SeriesGuideContract.Movies.CONTENT_URI,
values);
return insert != null;
}
private static boolean updateMovie(Context context, int movieTmdbId, String column,
boolean value) {
ContentValues values = new ContentValues();
values.put(column, value);
int rowsUpdated = context.getContentResolver().update(
SeriesGuideContract.Movies.buildMovieUri(movieTmdbId), values, null, null);
return rowsUpdated > 0;
}
/**
* @return {@code true} if the movie was deleted (because it was not watched).
*/
private static boolean deleteMovieIfUnwatched(Context context, int movieTmdbId) {
int rowsDeleted = context.getContentResolver()
.delete(SeriesGuideContract.Movies.buildMovieUri(movieTmdbId),
SeriesGuideContract.Movies.SELECTION_UNWATCHED, null);
Timber.d("deleteMovieIfUnwatched: deleted " + rowsDeleted + " movie");
return rowsDeleted > 0;
}
public static Integer lookupTraktId(Search traktSearch, int movieTmdbId) {
try {
List<SearchResult> lookup = traktSearch.idLookup(IdType.TMDB,
String.valueOf(movieTmdbId), 1, 10);
if (lookup == null || lookup.size() == 0) {
Timber.e("Finding trakt movie failed (no results)");
return null;
}
for (SearchResult result : lookup) {
// find movie (tmdb ids are not unique for tv and movies)
if (result.movie != null && result.movie.ids != null) {
return result.movie.ids.trakt;
}
}
Timber.e("Finding trakt movie failed (not in results)");
} catch (RetrofitError e) {
Timber.e(e, "Finding trakt movie failed");
}
return null;
}
public static class Download {
/**
* Downloads movies from hexagon, updates existing movies with new properties, removes
* movies that are neither in collection or watchlist.
*
* <p> Adds movie tmdb ids to the respective collection or watchlist set.
*/
public static boolean fromHexagon(Context context,
@NonNull Set<Integer> newCollectionMovies, @NonNull Set<Integer> newWatchlistMovies,
boolean hasMergedMovies) {
List<com.uwetrottmann.seriesguide.backend.movies.model.Movie> movies;
boolean hasMoreMovies = true;
String cursor = null;
long currentTime = System.currentTimeMillis();
DateTime lastSyncTime = new DateTime(HexagonSettings.getLastMoviesSyncTime(context));
HashSet<Integer> localMovies = getMovieTmdbIdsAsSet(context);
if (hasMergedMovies) {
Timber.d("fromHexagon: downloading movies changed since " + lastSyncTime);
} else {
Timber.d("fromHexagon: downloading all movies");
}
while (hasMoreMovies) {
// abort if connection is lost
if (!AndroidUtils.isNetworkConnected(context)) {
Timber.e("fromHexagon: no network connection");
return false;
}
try {
com.uwetrottmann.seriesguide.backend.movies.Movies moviesService
= HexagonTools.getMoviesService(context);
if (moviesService == null) {
return false;
}
com.uwetrottmann.seriesguide.backend.movies.Movies.Get request
= moviesService.get().setLimit(MOVIES_MAX_BATCH_SIZE);
if (hasMergedMovies) {
request.setUpdatedSince(lastSyncTime);
}
if (!TextUtils.isEmpty(cursor)) {
request.setCursor(cursor);
}
MovieList response = request.execute();
if (response == null) {
// nothing more to do
Timber.d("fromHexagon: response was null, done here");
break;
}
movies = response.getMovies();
if (response.getCursor() != null) {
cursor = response.getCursor();
} else {
hasMoreMovies = false;
}
} catch (IOException e) {
Timber.e(e, "fromHexagon: failed to download movies");
return false;
}
if (movies == null || movies.size() == 0) {
// nothing more to do
break;
}
ArrayList<ContentProviderOperation> batch = new ArrayList<>();
for (com.uwetrottmann.seriesguide.backend.movies.model.Movie movie : movies) {
if (localMovies.contains(movie.getTmdbId())) {
// movie is in database
if (movie.getIsInCollection() != null && movie.getIsInWatchlist() != null
&& !movie.getIsInCollection() && !movie.getIsInWatchlist()) {
// if neither in watchlist or collection: remove movie
batch.add(ContentProviderOperation.newDelete(
SeriesGuideContract.Movies.buildMovieUri(movie.getTmdbId()))
.build());
} else {
// update movie properties
ContentValues values = new ContentValues();
if (movie.getIsInCollection() != null) {
values.put(SeriesGuideContract.Movies.IN_COLLECTION,
movie.getIsInCollection());
}
if (movie.getIsInWatchlist() != null) {
values.put(SeriesGuideContract.Movies.IN_WATCHLIST,
movie.getIsInWatchlist());
}
batch.add(ContentProviderOperation.newUpdate(
SeriesGuideContract.Movies.buildMovieUri(movie.getTmdbId()))
.withValues(values).build());
}
} else {
// schedule movie to be added
if (movie.getIsInCollection() != null && movie.getIsInCollection()) {
newCollectionMovies.add(movie.getTmdbId());
}
if (movie.getIsInWatchlist() != null && movie.getIsInWatchlist()) {
newWatchlistMovies.add(movie.getTmdbId());
}
}
}
try {
DBUtils.applyInSmallBatches(context, batch);
} catch (OperationApplicationException e) {
Timber.e(e, "fromHexagon: applying movie updates failed");
return false;
}
}
// set new last sync time
if (hasMergedMovies) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putLong(HexagonSettings.KEY_LAST_SYNC_MOVIES, currentTime)
.commit();
}
return true;
}
/**
* Updates the local movie database against trakt movie watchlist and collection. Adds,
* updates and removes movies in the database.
*
* <p> When syncing the first time, will upload any local movies missing from trakt
* collection or watchlist instead of removing them locally.
*
* <p> Performs <b>synchronous network access</b>, make sure to run this on a background
* thread.
*/
public static UpdateResult syncMovieListsWithTrakt(Context context,
LastActivityMore activity) {
if (activity.collected_at == null) {
Timber.e("syncMoviesWithTrakt: null collected_at");
return UpdateResult.INCOMPLETE;
}
if (activity.watchlisted_at == null) {
Timber.e("syncMoviesWithTrakt: null watchlisted_at");
return UpdateResult.INCOMPLETE;
}
TraktV2 trakt = ServiceUtils.getTraktV2WithAuth(context);
if (trakt == null) {
return UpdateResult.INCOMPLETE;
}
final boolean merging = !TraktSettings.hasMergedMovies(context);
if (!merging && !TraktSettings.isMovieListsChanged(context, activity.collected_at,
activity.watchlisted_at)) {
Timber.d("syncMoviesWithTrakt: no changes");
return UpdateResult.SUCCESS;
}
Sync sync = trakt.sync();
// download collection and watchlist
Set<Integer> collection;
Set<Integer> watchlist;
try {
collection = buildTmdbIdSet(sync.collectionMovies(Extended.DEFAULT_MIN));
if (collection == null) {
Timber.e("syncMoviesWithTrakt: null collection response");
return UpdateResult.INCOMPLETE;
}
watchlist = buildTmdbIdSet(sync.watchlistMovies(Extended.DEFAULT_MIN));
if (watchlist == null) {
Timber.e("syncMoviesWithTrakt: null watchlist response");
return UpdateResult.INCOMPLETE;
}
} catch (RetrofitError e) {
Timber.e(e, "syncMoviesWithTrakt: download failed");
return UpdateResult.INCOMPLETE;
} catch (OAuthUnauthorizedException e) {
TraktCredentials.get(context).setCredentialsInvalid();
return UpdateResult.INCOMPLETE;
}
// build updates
// loop through all local movies
Set<Integer> moviesNotOnTraktCollection = new HashSet<>();
Set<Integer> moviesNotOnTraktWatchlist = new HashSet<>();
ArrayList<ContentProviderOperation> batch = new ArrayList<>();
for (Integer tmdbId : getMovieTmdbIdsAsSet(context)) {
// is local movie in trakt collection or watchlist?
boolean inCollection = collection.remove(tmdbId);
boolean inWatchlist = watchlist.remove(tmdbId);
if (merging) {
// upload movie if missing from trakt collection or watchlist
if (!inCollection) {
moviesNotOnTraktCollection.add(tmdbId);
}
if (!inWatchlist) {
moviesNotOnTraktWatchlist.add(tmdbId);
}
// add to local collection or watchlist, but do NOT remove
if (inCollection || inWatchlist) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newUpdate(SeriesGuideContract.Movies.buildMovieUri(tmdbId));
if (inCollection) {
builder.withValue(SeriesGuideContract.Movies.IN_COLLECTION, true);
}
if (inWatchlist) {
builder.withValue(SeriesGuideContract.Movies.IN_WATCHLIST, true);
}
batch.add(builder.build());
}
} else {
// mirror trakt collection and watchlist flag
// will take care of removing unneeded (not watched or in any list) movies
// in later sync step
ContentProviderOperation op = ContentProviderOperation
.newUpdate(SeriesGuideContract.Movies.buildMovieUri(tmdbId))
.withValue(SeriesGuideContract.Movies.IN_COLLECTION, inCollection)
.withValue(SeriesGuideContract.Movies.IN_WATCHLIST, inWatchlist)
.build();
batch.add(op);
}
}
// apply collection and watchlist updates to existing movies
try {
DBUtils.applyInSmallBatches(context, batch);
Timber.d("syncMoviesWithTrakt: updated " + batch.size());
} catch (OperationApplicationException e) {
Timber.e(e, "syncMoviesWithTrakt: database updates failed");
return UpdateResult.INCOMPLETE;
}
batch.clear();
// merge on first run
if (merging) {
// upload movies not in trakt collection or watchlist
if (Upload.toTrakt(context, sync, moviesNotOnTraktCollection,
moviesNotOnTraktWatchlist) != UpdateResult.SUCCESS) {
return UpdateResult.INCOMPLETE;
} else {
// set merge successful
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putBoolean(TraktSettings.KEY_HAS_MERGED_MOVIES, true)
.commit();
}
}
// add movies from trakt missing locally
// all local movies were removed from trakt collection and watchlist,
// so they only contain movies missing locally
UpdateResult result = addMovies(context, collection, watchlist);
if (result == UpdateResult.SUCCESS) {
// store last activity timestamps
TraktSettings.storeLastMoviesChangedAt(context, activity.collected_at,
activity.watchlisted_at);
// if movies were added,
// ensure all movie ratings and watched flags are downloaded next
if (collection.size() > 0 || watchlist.size() > 0) {
TraktSettings.resetMoviesLastActivity(context);
}
}
return result;
}
private static Set<Integer> buildTmdbIdSet(List<BaseMovie> movies) {
if (movies == null) {
return null;
}
Set<Integer> tmdbIdSet = new HashSet<>();
for (BaseMovie movie : movies) {
if (movie.movie == null || movie.movie.ids == null
|| movie.movie.ids.tmdb == null) {
continue; // skip invalid values
}
tmdbIdSet.add(movie.movie.ids.tmdb);
}
return tmdbIdSet;
}
/**
* Adds new movies to the database.
*
* @param newCollectionMovies Movie TMDB ids to add to the collection.
* @param newWatchlistMovies Movie TMDB ids to add to the watchlist.
*/
public static UpdateResult addMovies(@NonNull Context context,
@NonNull Set<Integer> newCollectionMovies,
@NonNull Set<Integer> newWatchlistMovies) {
Timber.d("addMovies: " + newCollectionMovies.size() + " to collection, "
+ newWatchlistMovies.size() + " to watchlist");
// build a single list of tmdb ids
Set<Integer> newMovies = new HashSet<>();
for (Integer tmdbId : newCollectionMovies) {
newMovies.add(tmdbId);
}
for (Integer tmdbId : newWatchlistMovies) {
newMovies.add(tmdbId);
}
TraktV2 trakt = ServiceUtils.getTraktV2(context);
Search traktSearch = trakt.search();
Movies traktMovies = trakt.movies();
MoviesService tmdbMovies = ServiceUtils.getTmdb(context).moviesService();
String languageCode = DisplaySettings.getContentLanguage(context);
List<MovieDetails> movies = new LinkedList<>();
// loop through ids
for (Iterator<Integer> iterator = newMovies.iterator(); iterator.hasNext(); ) {
int tmdbId = iterator.next();
if (!AndroidUtils.isNetworkConnected(context)) {
Timber.e("addMovies: no network connection");
return UpdateResult.INCOMPLETE;
}
// download movie data
MovieDetails movieDetails = getMovieDetails(traktSearch, traktMovies, tmdbMovies,
languageCode, tmdbId);
if (movieDetails.tmdbMovie() == null) {
// skip if minimal values failed to load
Timber.d("addMovies: downloaded movie " + tmdbId + " incomplete, skipping");
continue;
}
// set flags
movieDetails.inCollection = newCollectionMovies.contains(tmdbId);
movieDetails.inWatchlist = newWatchlistMovies.contains(tmdbId);
movies.add(movieDetails);
// add to database in batches of at most 10
if (movies.size() == 10 || !iterator.hasNext()) {
// insert into database
context.getContentResolver().bulkInsert(SeriesGuideContract.Movies.CONTENT_URI,
buildMoviesContentValues(movies));
// start new batch
movies.clear();
}
}
return UpdateResult.SUCCESS;
}
/**
* Download movie data from trakt and TMDb. If you plan on calling this multiple times, use
* {@link #getMovieDetails(com.uwetrottmann.trakt.v2.services.Search,
* com.uwetrottmann.trakt.v2.services.Movies, com.uwetrottmann.tmdb.services.MoviesService,
* String, int)} instead.
*/
public static MovieDetails getMovieDetails(Context context, int movieTmdbId) {
// trakt
TraktV2 trakt = ServiceUtils.getTraktV2(context);
Movies traktMovies = trakt.movies();
Search traktSearch = trakt.search();
// TMDb
MoviesService tmdbMovies = ServiceUtils.getTmdb(context).moviesService();
String languageCode = DisplaySettings.getContentLanguage(context);
return getMovieDetails(traktSearch, traktMovies, tmdbMovies, languageCode, movieTmdbId);
}
/**
* Download movie data from trakt and TMDb.
*
* <p> <b>Always</b> supply trakt services <b>without</b> auth, as retrofit will crash on
* auth errors.
*/
public static MovieDetails getMovieDetails(Search traktSearch, Movies traktMovies,
MoviesService tmdbMovies, String languageCode, int movieTmdbId) {
MovieDetails details = new MovieDetails();
// load ratings and release time from trakt
Integer movieTraktId = lookupTraktId(traktSearch, movieTmdbId);
if (movieTraktId != null) {
details.traktRatings(loadRatingsFromTrakt(traktMovies, movieTraktId));
}
// load summary from tmdb
details.tmdbMovie(loadSummaryFromTmdb(tmdbMovies, languageCode, movieTmdbId));
return details;
}
private static Ratings loadRatingsFromTrakt(Movies traktMovies, int movieTraktId) {
try {
return traktMovies.ratings(String.valueOf(movieTraktId));
} catch (RetrofitError e) {
Timber.e(e, "Loading trakt movie ratings failed");
return null;
}
}
private static com.uwetrottmann.tmdb.entities.Movie loadSummaryFromTmdb(
MoviesService moviesService, String languageCode, int movieTmdbId) {
try {
com.uwetrottmann.tmdb.entities.Movie movie = moviesService.summary(movieTmdbId,
languageCode, null);
if (movie != null && TextUtils.isEmpty(movie.overview)) {
// fall back to English if TMDb has no localized text
movie = moviesService.summary(movieTmdbId, null, null);
}
return movie;
} catch (RetrofitError e) {
Timber.e(e, "Loading TMDb movie summary failed");
return null;
}
}
private static void buildMovieDeleteOps(Set<Integer> moviesToRemove,
ArrayList<ContentProviderOperation> batch) {
for (Integer movieTmdbId : moviesToRemove) {
ContentProviderOperation op = ContentProviderOperation
.newDelete(SeriesGuideContract.Movies.buildMovieUri(movieTmdbId)).build();
batch.add(op);
}
}
}
public static class Upload {
private static final String[] PROJECTION_MOVIES_IN_LISTS = {
SeriesGuideContract.Movies.TMDB_ID, // 0
SeriesGuideContract.Movies.IN_COLLECTION, // 1
SeriesGuideContract.Movies.IN_WATCHLIST // 2
};
/**
* Uploads all local movies to Hexagon.
*/
public static boolean toHexagon(Context context) {
Timber.d("toHexagon: uploading all movies");
List<com.uwetrottmann.seriesguide.backend.movies.model.Movie> movies = buildMovieList(
context);
if (movies == null) {
Timber.e("toHexagon: movie query was null");
return false;
}
if (movies.size() == 0) {
// nothing to do
Timber.d("toHexagon: no movies to upload");
return true;
}
MovieList movieList = new MovieList();
movieList.setMovies(movies);
try {
com.uwetrottmann.seriesguide.backend.movies.Movies moviesService
= HexagonTools.getMoviesService(context);
if (moviesService == null) {
return false;
}
moviesService.save(movieList).execute();
} catch (IOException e) {
Timber.e(e, "toHexagon: failed to upload movies");
return false;
}
return true;
}
private static List<com.uwetrottmann.seriesguide.backend.movies.model.Movie> buildMovieList(
Context context) {
List<com.uwetrottmann.seriesguide.backend.movies.model.Movie> movies
= new ArrayList<>();
// query for movies in lists (excluding movies that are only watched)
Cursor moviesInLists = context.getContentResolver().query(
SeriesGuideContract.Movies.CONTENT_URI, PROJECTION_MOVIES_IN_LISTS,
SeriesGuideContract.Movies.SELECTION_IN_LIST, null, null);
if (moviesInLists == null) {
return null;
}
while (moviesInLists.moveToNext()) {
com.uwetrottmann.seriesguide.backend.movies.model.Movie movie
= new com.uwetrottmann.seriesguide.backend.movies.model.Movie();
movie.setTmdbId(moviesInLists.getInt(0));
movie.setIsInCollection(moviesInLists.getInt(1) == 1);
movie.setIsInWatchlist(moviesInLists.getInt(2) == 1);
movies.add(movie);
}
moviesInLists.close();
return movies;
}
/**
* Checks if the given movies are in the local collection or watchlist, then uploads them to
* the appropriate list(s) on trakt.
*/
public static UpdateResult toTrakt(Context context, Sync sync,
Set<Integer> moviesNotOnTraktCollection, Set<Integer> moviesNotOnTraktWatchlist) {
if (moviesNotOnTraktCollection.size() == 0 && moviesNotOnTraktWatchlist.size() == 0) {
// nothing to upload
Timber.d("toTrakt: nothing to upload");
return UpdateResult.SUCCESS;
}
// return if connectivity is lost
if (!AndroidUtils.isNetworkConnected(context)) {
return UpdateResult.INCOMPLETE;
}
// query for movies in lists (excluding movies that are only watched)
Cursor moviesInLists = context.getContentResolver()
.query(SeriesGuideContract.Movies.CONTENT_URI, PROJECTION_MOVIES_IN_LISTS,
SeriesGuideContract.Movies.SELECTION_IN_LIST, null, null);
if (moviesInLists == null) {
Timber.e("toTrakt: query failed");
return UpdateResult.INCOMPLETE;
}
// build list of collected, watchlisted movies to upload
List<SyncMovie> moviesToCollect = new LinkedList<>();
List<SyncMovie> moviesToWatchlist = new LinkedList<>();
while (moviesInLists.moveToNext()) {
int tmdbId = moviesInLists.getInt(0);
// in local collection, but not on trakt?
if (moviesInLists.getInt(1) == 1 && moviesNotOnTraktCollection.contains(tmdbId)) {
moviesToCollect.add(new SyncMovie().id(MovieIds.tmdb(tmdbId)));
}
// in local watchlist, but not on trakt?
if (moviesInLists.getInt(2) == 1 && moviesNotOnTraktWatchlist.contains(tmdbId)) {
moviesToWatchlist.add(new SyncMovie().id(MovieIds.tmdb(tmdbId)));
}
}
// clean up
moviesInLists.close();
// upload
try {
SyncItems items = new SyncItems();
if (moviesToCollect.size() > 0) {
items.movies(moviesToCollect);
sync.addItemsToCollection(items);
}
if (moviesToWatchlist.size() > 0) {
items.movies(moviesToWatchlist);
sync.addItemsToWatchlist(items);
}
} catch (RetrofitError e) {
Timber.e(e, "toTrakt: upload failed");
return UpdateResult.INCOMPLETE;
} catch (OAuthUnauthorizedException e) {
TraktCredentials.get(context).setCredentialsInvalid();
return UpdateResult.INCOMPLETE;
}
Timber.d("toTrakt: success, uploaded "
+ moviesToCollect.size() + " to collection, "
+ moviesToWatchlist.size() + " to watchlist");
return UpdateResult.SUCCESS;
}
}
}
| true |
a6b4568ef1e4dc03ba4dfd5aaf0807c1f119c022 | Java | MZ-Liang/MySolr | /src/main/java/com/lmz/bean/PageResult.java | UTF-8 | 1,885 | 2.546875 | 3 | [] | no_license | package com.lmz.bean;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* 分页结果类
* @param <T>
*
*/
public class PageResult<T> implements Serializable{
/** serialVersionUID */
private static final long serialVersionUID = 1L;
/** 当前页 */
private Integer pageNo;
/** 每页大小 */
private Integer pageSize;
/** 总数 */
private Long count;
/**总页数*/
private Integer totalPage;
/** list集合数据 */
private List<T> list;
/** map集合数据 */
private Map<Object, Object> map;
public Integer getPageNo() {
return pageNo;
}
public void setPageNo(Integer pageNo) {
this.pageNo = pageNo;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Long getCount() {
return count;
}
public void setCount(Long l) {
this.count = l;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public Map<Object, Object> getMap() {
return map;
}
public void setMap(Map<Object, Object> map) {
this.map = map;
}
public PageResult() {
super();
}
public PageResult(Integer pageNo, Integer pageSize, Long count, Integer totalPage, List<T> list,
Map<Object, Object> map) {
super();
this.pageNo = pageNo;
this.pageSize = pageSize;
this.count = count;
this.totalPage = totalPage;
this.list = list;
this.map = map;
}
@Override
public String toString() {
return "PageResult [pageNo=" + pageNo + ", pageSize=" + pageSize + ", count=" + count + ", totalPage="
+ totalPage + ", list=" + list + ", map=" + map + "]";
}
}
| true |
df0dfb204e066b80e4d17b9c478be10a543a7eda | Java | linkedin/avro-util | /helper/helper-common/src/main/java/com/linkedin/avroutil1/compatibility/AvroAdapter.java | UTF-8 | 9,809 | 1.648438 | 2 | [
"BSD-2-Clause",
"Apache-2.0"
] | permissive | /*
* Copyright 2020 LinkedIn Corp.
* Licensed under the BSD 2-Clause License (the "License").
* See License in the project root for license information.
*/
package com.linkedin.avroutil1.compatibility;
import com.linkedin.avroutil1.normalization.AvscWriterPlugin;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.avro.AvroTypeException;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.io.BinaryDecoder;
import org.apache.avro.io.BinaryEncoder;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.Encoder;
import org.apache.avro.io.JsonDecoder;
import org.apache.avro.io.JsonEncoder;
import org.apache.avro.specific.SpecificData;
import org.apache.avro.specific.SpecificDatumReader;
/**
* an interface for performing various avro operations that are avro-version-dependant.
* each implementation is expected to support a given major version of avro (more specifically, the latest
* minor version of a particular major version - so the adapter for 1.7 actually supports 1.7.7).
*/
public interface AvroAdapter {
//metadata
AvroVersion supportedMajorVersion();
//codecs
BinaryEncoder newBinaryEncoder(OutputStream out, boolean buffered, BinaryEncoder reuse);
BinaryEncoder newBinaryEncoder(ObjectOutput out);
BinaryDecoder newBinaryDecoder(InputStream in, boolean buffered, BinaryDecoder reuse);
BinaryDecoder newBinaryDecoder(ObjectInput in);
BinaryDecoder newBinaryDecoder(byte[] bytes, int offset, int length, BinaryDecoder reuse);
JsonEncoder newJsonEncoder(Schema schema, OutputStream out, boolean pretty) throws IOException;
Encoder newJsonEncoder(Schema schema, OutputStream out, boolean pretty, AvroVersion jsonFormat) throws IOException;
JsonDecoder newJsonDecoder(Schema schema, InputStream in) throws IOException;
JsonDecoder newJsonDecoder(Schema schema, String in) throws IOException;
Decoder newCompatibleJsonDecoder(Schema schema, InputStream in) throws IOException;
Decoder newCompatibleJsonDecoder(Schema schema, String in) throws IOException;
SkipDecoder newCachedResolvingDecoder(Schema writer, Schema reader, Decoder in) throws IOException;
Decoder newBoundedMemoryDecoder(InputStream in) throws IOException;
Decoder newBoundedMemoryDecoder(byte[] data) throws IOException;
<T> SpecificDatumReader<T> newAliasAwareSpecificDatumReader(Schema writer, Class<T> readerClass);
DatumWriter<?> newSpecificDatumWriter(Schema writer, SpecificData specificData);
DatumReader<?> newSpecificDatumReader(Schema writer, Schema reader, SpecificData specificData);
//parsing and Schema-related
SchemaParseResult parse(String schemaJson, SchemaParseConfiguration desiredConf, Collection<Schema> known);
String toParsingForm(Schema s);
String getDefaultValueAsJsonString(Schema.Field field);
//specific record utils
Object newInstance(Class<?> clazz, Schema schema);
Object getSpecificDefaultValue(Schema.Field field);
//generic record utils
GenericData.EnumSymbol newEnumSymbol(Schema enumSchema, String enumValue);
GenericData.Fixed newFixedField(Schema fixedSchema);
GenericData.Fixed newFixedField(Schema fixedSchema, byte[] contents);
Object getGenericDefaultValue(Schema.Field field);
//schema query and manipulation utils
boolean fieldHasDefault(Schema.Field field);
boolean defaultValuesEqual(Schema.Field a, Schema.Field b, boolean allowLooseNumerics);
Set<String> getFieldAliases(Schema.Field field);
@Deprecated
default FieldBuilder cloneSchemaField(Schema.Field field) {
return newFieldBuilder(field);
}
/**
* constructs a new {@link FieldBuilder}, optionally using a given {@link org.apache.avro.Schema.Field}
* for initial values
* @param other a starting point. or null.
* @return a new builder
*/
FieldBuilder newFieldBuilder(Schema.Field other);
@Deprecated
default FieldBuilder newFieldBuilder(String name) {
return newFieldBuilder((Schema.Field) null).setName(name);
}
/**
* constructs a new {@link SchemaBuilder}, optionally using a given {@link Schema} for initial values
* @param other a starting point. or null.
* @return a new builder
*/
SchemaBuilder newSchemaBuilder(Schema other);
String getFieldPropAsJsonString(Schema.Field field, String propName);
void setFieldPropFromJsonString(Schema.Field field, String propName, String valueAsJsonLiteral, boolean strict);
/**
* compare json properties on 2 schema fields for equality.
* @param a a field
* @param b another field
* @param compareStringProps true to compare string properties (otherwise ignored)
* @param compareNonStringProps true to compare all other properties (otherwise ignored). this exists because avro 1.4
* doesnt handle non-string props at all and we want to be able to match that behaviour under any avro
* @param jsonPropNamesToIgnore a set of json property names to ignore. if null, no properties will be ignored
* @return if field properties are equal, under the configuration parameters above
*/
boolean sameJsonProperties(Schema.Field a, Schema.Field b, boolean compareStringProps, boolean compareNonStringProps,
Set<String> jsonPropNamesToIgnore);
String getSchemaPropAsJsonString(Schema schema, String propName);
void setSchemaPropFromJsonString(Schema field, String propName, String valueAsJsonLiteral, boolean strict);
/**
* compare json properties on 2 schemas for equality.
* @param a a schema
* @param b another schema
* @param compareStringProps true to compare string properties (otherwise ignored)
* @param compareNonStringProps true to compare all other properties (otherwise ignored). this exists because avro 1.4
* doesnt handle non-string props at all and we want to be able to match that behaviour under any avro
* @param jsonPropNamesToIgnore a set of json property names to ignore. if null, all properties are considered
* @return if schema properties are equal, under the configuration parameters above
*/
boolean sameJsonProperties(Schema a, Schema b, boolean compareStringProps, boolean compareNonStringProps,
Set<String> jsonPropNamesToIgnore);
List<String> getAllPropNames(Schema schema);
List<String> getAllPropNames(Schema.Field field);
String getEnumDefault(Schema s);
default Schema newEnumSchema(String name, String doc, String namespace, List<String> values, String enumDefault) {
if (enumDefault != null) {
//TODO - implement via properties
throw new AvroTypeException("enum default is not supported in " + supportedMajorVersion().toString());
}
return Schema.createEnum(name, doc, namespace, values);
}
/**
* "serialize" a {@link Schema} to avsc format
* @param schema a schema to print out as (exploded/fully-defined) avsc
* @return the given schema as avsc
*/
String toAvsc(Schema schema, AvscGenerationConfig config);
/***
* Instantiates and returns com.linkedin.avroutil1.compatibility.AvroWriter for the provided configs, plugin list
* and runtime avro version.
* @param config
* @param schemaPlugins can be an empty list or null
* @return
*/
AvscWriter getAvscWriter(AvscGenerationConfig config, List<AvscWriterPlugin> schemaPlugins);
default boolean isSusceptibleToAvro702(Schema schema) {
//this implementation is slow, as it completely serializes the schema and parses it back again
//and potentially catches an exception. its possible to write a stripped down version of the
//AvscWriter recursion that will simply return a boolean if pre- and post-702 states ever "diverge"
String naiveAvsc = toAvsc(schema, AvscGenerationConfig.LEGACY_ONELINE);
boolean parseFailed = false;
Schema evilTwin = null;
try {
evilTwin = Schema.parse(naiveAvsc); //avro-702 can result in "exploded" schemas that dont parse
} catch (Exception ignored) {
parseFailed = true;
}
return parseFailed || !evilTwin.equals(schema);
}
/**
* given schemas about to be code-gen'd and a code-gen config, returns a map of
* alternative AVSC to use by schema full name.
* @param toCompile schemas about to be "compiled"
* @param config configuration
* @return alternative AVSCs, keyed by schema full name
*/
default Map<String, String> createAlternativeAvscs(Collection<Schema> toCompile, CodeGenerationConfig config) {
if (!config.isAvro702HandlingEnabled()) {
return Collections.emptyMap();
}
AvscGenerationConfig avscGenConfig = config.getAvro702AvscReplacement();
Map<String, String> fullNameToAlternativeAvsc = new HashMap<>(1); //expected to be small
//look for schemas that are susceptible to avro-702, and re-generate their AVSC if required
for (Schema schema : toCompile) {
if (!HelperConsts.NAMED_TYPES.contains(schema.getType())) {
continue; //only named types impacted by avro-702 to begin with
}
String fullName = schema.getFullName();
if (isSusceptibleToAvro702(schema)) {
String altAvsc = toAvsc(schema, avscGenConfig);
fullNameToAlternativeAvsc.put(fullName, altAvsc);
}
}
return fullNameToAlternativeAvsc;
}
//code generation
Collection<AvroGeneratedSourceCode> compile(Collection<Schema> toCompile, AvroVersion minSupportedVersion,
AvroVersion maxSupportedVersion, CodeGenerationConfig config);
}
| true |
a4467a3a8e809df36ad28e85c06a856d32c7c763 | Java | nicomartinezdev/ryd | /src/main/java/com/ryd/validator/ClienteFormValidator.java | UTF-8 | 923 | 2.40625 | 2 | [] | no_license | package com.ryd.validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.ryd.model.ClienteForm;
import com.ryd.service.ClienteService;
public class ClienteFormValidator implements Validator{
private ClienteService clienteService;
public boolean supports(@SuppressWarnings("rawtypes") Class arg0) {
return ClienteForm.class.equals(arg0);
}
public void validate(Object object, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "razonSocial", "error.vacio");
ClienteForm form = (ClienteForm) object;
if (clienteService.validarRazonSocial(form.getClienteId(), form.getRazonSocial())) {
errors.rejectValue("razonSocial", "error.razonSocial.duplicado");
}
}
public void setClienteService(ClienteService clienteService) {
this.clienteService = clienteService;
}
}
| true |
4c69130e3c41ed4ae9c8330e49bd4a944ca10a2f | Java | chenluyuan/jaksona | /src/main/java/com/jaksona/app/entity/admin/Permission.java | UTF-8 | 1,751 | 2.03125 | 2 | [
"Apache-2.0"
] | permissive | package com.jaksona.app.entity.admin;
import com.jaksona.app.bean.tree.TreeBean;
import java.util.Date;
/**
* 权限
* @author jaksona
*/
public class Permission extends TreeBean {
// members
private String name;
private String code;
private String url;
private String descn;
private Integer type;
private Integer sort;
private Boolean hidden;
private Boolean active;
private Date createTime;
private Date updateTime;
private Long userId;
// setter and getter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescn() {
return descn;
}
public void setDescn(String descn) {
this.descn = descn;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Boolean getHidden() {
return hidden;
}
public void setHidden(Boolean hidden) {
this.hidden = hidden;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
}
| true |
60cc91b1ddc5060e07f96af994aa47fc25203074 | Java | atinkohli/DemoProjects | /JEE/ReviewSystem/ReviewSystemJpa/src/com/arpn/review/jpa/domain/Reviews.java | UTF-8 | 1,410 | 2.34375 | 2 | [] | no_license | package com.arpn.review.jpa.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="Reviews",schema="APP")
public class Reviews {
private long reviewId;
private String userName;
private String productName;
private String comment;
private int rating;
public Reviews() {
// TODO Auto-generated constructor stub
}
public Reviews(final String userName, final String productName, final String comment, final int rating){
this.userName = userName;
this.productName = productName;
this.comment = comment;
this.rating = rating;
}
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public long getReviewId() {
return reviewId;
}
private void setReviewId(long reviewId) {
this.reviewId = reviewId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
}
| true |
ff85f106763bd53ec38477112430daed978e2300 | Java | seanshaojie/graduation_project | /src/main/java/com/example/service/impl/PermissionServiceImpl.java | UTF-8 | 943 | 2.046875 | 2 | [] | no_license | package com.example.service.impl;
import com.example.dao.PermissionDao;
import com.example.model.Permission;
import com.example.service.PermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class PermissionServiceImpl implements PermissionService {
@Autowired
private PermissionDao permissionDao;
@Override
public void save(Permission permission) {
permissionDao.save(permission);
}
@Override
public void update(Permission permission) {
permissionDao.update(permission);
}
@Override
@Transactional
public void delete(Long id) {
permissionDao.deleteRolePermission(id);
permissionDao.delete(id);
permissionDao.deleteByParentId(id);
}
}
| true |
7240617225f0b4ee62c9636d14f02dcc31ff3e8a | Java | Dranoss/firstCourtagePatBack | /src/main/java/com/patrimoine/website/webServices/service/UserAddressService.java | UTF-8 | 1,748 | 2.28125 | 2 | [] | no_license | package com.patrimoine.website.webServices.service;
import com.patrimoine.website.webServices.entity.UserAddress;
import com.patrimoine.website.webServices.repository.UserAddressRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import java.util.Optional;
@Service
public class UserAddressService {
@Autowired
private UserAddressRepository userAddressRepository;
public List<UserAddress> getAllUserAddresses(){
return userAddressRepository.findAll();
}
public UserAddress getUserAddressById(Long id){
Optional<UserAddress> userAddress = userAddressRepository.findById(id);
if(userAddress.isPresent()){
return userAddress.get();
}
return null;
}
public UserAddress saveUserAddress(UserAddress userAddress){
return userAddressRepository.save(userAddress);
}
public UserAddress updateUserAddress(UserAddress userAddress, Long id){
if(id == userAddress.getId()) {
UserAddress userAddressUpdated = userAddressRepository.findById(id).get();
userAddressUpdated.setStreetName(userAddress.getStreetName());
userAddressUpdated.setZipCode(userAddress.getZipCode());
userAddressUpdated.setCityName(userAddress.getCityName());
return userAddressRepository.save(userAddressUpdated);
}
throw new ResponseStatusException(
HttpStatus.PRECONDITION_FAILED);
}
public void deleteUserAddress(Long id){
userAddressRepository.deleteById(id);
}
}
| true |
b7298e70f3c78ecf6a1cbfd56ed9bbe3e23a6cc3 | Java | Peipeilvcm/Junior-semester | /JAVA/homework_7/BookSpecification.java | GB18030 | 1,500 | 3.21875 | 3 | [] | no_license |
public class BookSpecification {
public static final int NOT_EXIST = 0; //ʱ鱾
public static final int NOT_COMPUTER_TEACHING = 1; //ǽ̲ļ
public static final int TEACHING = 2; //̲
public static final int COMIC = 3; //
public static final int HEALTH = 4; //
public static final int OTHER = 5; //
private String isbn;
private String title;
private double price;
private int type;
//캯
public BookSpecification() {
this.type = NOT_EXIST;
}
public BookSpecification(String isbn,
String title,double price, int type) {
this.isbn = isbn;
this.title = title;
this.price = price;
this.type = type;
}
public String getTypeName(){
switch(type){
case NOT_EXIST:
return null;
case NOT_COMPUTER_TEACHING:
return "ǽ̲ͼ";
case TEACHING:
return "̲ͼ";
case COMIC:
return "ͼ";
case HEALTH:
return "ͼ";
default:
return "";
}
}
//get,set
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getType() {
return type;
}
public void setType(int category) {
this.type = category;
}
}
| true |
a99f01357e060561f74de269f90fc4515af6303a | Java | bianapis/sd-direct-debit-v3 | /src/main/java/org/bian/dto/CRDirectDebitArrangementExchangeOutputModel.java | UTF-8 | 4,894 | 1.882813 | 2 | [
"Apache-2.0"
] | permissive | package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.Valid;
/**
* CRDirectDebitArrangementExchangeOutputModel
*/
public class CRDirectDebitArrangementExchangeOutputModel {
private String directDebitArrangementParameterType = null;
private String directDebitArrangementSelectedOption = null;
private String directDebitArrangementSchedule = null;
private String directDebitArrangementStatus = null;
private String directDebitArrangementExchangeActionTaskReference = null;
private Object directDebitArrangementExchangeActionTaskRecord = null;
private String directDebitArrangementExchangeActionResponse = null;
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: A Classification value that distinguishes between arrangements according to the type of business services within Direct Debit Arrangement
* @return directDebitArrangementParameterType
**/
public String getDirectDebitArrangementParameterType() {
return directDebitArrangementParameterType;
}
public void setDirectDebitArrangementParameterType(String directDebitArrangementParameterType) {
this.directDebitArrangementParameterType = directDebitArrangementParameterType;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: A selected optional business service as subject matter of Direct Debit Arrangement
* @return directDebitArrangementSelectedOption
**/
public String getDirectDebitArrangementSelectedOption() {
return directDebitArrangementSelectedOption;
}
public void setDirectDebitArrangementSelectedOption(String directDebitArrangementSelectedOption) {
this.directDebitArrangementSelectedOption = directDebitArrangementSelectedOption;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Timetable to fulfill Direct Debit Arrangement
* @return directDebitArrangementSchedule
**/
public String getDirectDebitArrangementSchedule() {
return directDebitArrangementSchedule;
}
public void setDirectDebitArrangementSchedule(String directDebitArrangementSchedule) {
this.directDebitArrangementSchedule = directDebitArrangementSchedule;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The status of Direct Debit Arrangement
* @return directDebitArrangementStatus
**/
public String getDirectDebitArrangementStatus() {
return directDebitArrangementStatus;
}
public void setDirectDebitArrangementStatus(String directDebitArrangementStatus) {
this.directDebitArrangementStatus = directDebitArrangementStatus;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to a Direct Debit Arrangement instance exchange service call
* @return directDebitArrangementExchangeActionTaskReference
**/
public String getDirectDebitArrangementExchangeActionTaskReference() {
return directDebitArrangementExchangeActionTaskReference;
}
public void setDirectDebitArrangementExchangeActionTaskReference(String directDebitArrangementExchangeActionTaskReference) {
this.directDebitArrangementExchangeActionTaskReference = directDebitArrangementExchangeActionTaskReference;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The exchange service call consolidated processing record
* @return directDebitArrangementExchangeActionTaskRecord
**/
public Object getDirectDebitArrangementExchangeActionTaskRecord() {
return directDebitArrangementExchangeActionTaskRecord;
}
public void setDirectDebitArrangementExchangeActionTaskRecord(Object directDebitArrangementExchangeActionTaskRecord) {
this.directDebitArrangementExchangeActionTaskRecord = directDebitArrangementExchangeActionTaskRecord;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Details of the exchange action service response
* @return directDebitArrangementExchangeActionResponse
**/
public String getDirectDebitArrangementExchangeActionResponse() {
return directDebitArrangementExchangeActionResponse;
}
public void setDirectDebitArrangementExchangeActionResponse(String directDebitArrangementExchangeActionResponse) {
this.directDebitArrangementExchangeActionResponse = directDebitArrangementExchangeActionResponse;
}
}
| true |
4135773e161a89e1bdbe784cf624acde65ca6412 | Java | tectronics/macchiato-ecommerce | /Macchiato/src/fr/labri/macchiato/client/cart/OfferSearch.java | UTF-8 | 3,070 | 2.28125 | 2 | [] | no_license | package fr.labri.macchiato.client.cart;
import java.util.ArrayList;
import java.util.List;
import com.google.gwt.i18n.client.NumberFormat;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.form.fields.RadioGroupItem;
import fr.labri.macchiato.client.cart.events.ValidateSearchHandler;
import fr.labri.macchiato.framework.business.model.businessEntity.BusinessEntity;
import fr.labri.macchiato.framework.business.model.preferences.UserPreferences;
import fr.labri.macchiato.framework.business.finder.Callback;
import fr.labri.macchiato.framework.business.model.product.Offer;
import fr.labri.macchiato.framework.business.service.Services;
/**
* A widget searching for available offers for a specified model
*
* @author Paul SARRAUTE
*
*/
public class OfferSearch extends ProductSearch {
private RadioGroupItem offerItems;
private List<Offer> resultOffers;
/**
* Create the widget searching available offers
*
* @param modelEan The EAN barcode of the model to search offer for
*/
OfferSearch(String modelEan) {
super(modelEan);
resultOffers = null;
}
private void addOffers(List<Offer> offers) {
resultOffers = offers;
resultNumber.setContents(resultOffers.size() + " élément(s) trouvé(s)");
offerItems = new RadioGroupItem();
offerItems.setRequired(true);
offerItems.setTitle("Choisissez un fournisseur: ");
List<String> offersDescription = new ArrayList<String>();
for (Offer offer : offers) {
offersDescription.add(offer.getProvider().getLegalName() + ": "
+ NumberFormat.getCurrencyFormat().format(offer.getPrice()));
}
offerItems.setValueMap(offersDescription.toArray(new String[0]));
contents.setFields(offerItems);
displayContents();
}
@Override
void addValidateHandler(final ValidateSearchHandler handler) {
validButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Offer selectedOffer = getSelectedOffer();
handler.setSelectedOffer(selectedOffer);
handler.fireEvent();
}
});
}
private Offer getSelectedOffer() {
Offer offer = null;
String selected = offerItems.getValueAsString();
for (Offer o : resultOffers) {
if (selected.contains(o.getProvider().getLegalName())) {
offer = o;
break;
}
}
return offer;
}
@Override
void startSearch() {
if (resultOffers == null) {
progressbar = new ProgressLabel("Recherche en cours...");
addMember(progressbar);
List<BusinessEntity> favoriteBusinessEntity = getUserPreferences().getFavoriteBusinessEntities();
getProductFinder().getOffersByEan(searchKeyword, favoriteBusinessEntity,
new Callback<List<Offer>>() {
@Override
public void onCallback(List<Offer> result) {
addOffers(result);
}
});
} else {
show();
}
}
/**
*
* @return The user's preferences
*/
UserPreferences getUserPreferences() {
return Services.getInstance().getPreferencesService().getUserPreferences();
}
}
| true |
a445e1e13316985dbed5b5f27d043362230a2d24 | Java | zhouhui0802/Greedy_Snake_Zh | /src/com/zh/ui/MyGameStartPanel.java | GB18030 | 3,394 | 2.84375 | 3 | [] | no_license | package com.zh.ui;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.*;
import com.zh.entity.Direction;
import com.zh.entity.Egg;
import com.zh.entity.Node;
import com.zh.entity.Snake;
public class MyGameStartPanel extends JPanel implements ActionListener, KeyListener,Runnable{
boolean isPause=false;
public static int COLS = 30;
public static int ROWS = 30;
public static int CELLSIZE = 20;
public Egg egg = new Egg(10,8);
public static Snake snake=new Snake();
public MyGameStartPanel()
{
}
@Override
public void paint(Graphics g)
{
super.paint(g);
g.fillRect(0, 0, 600, 600);
if (snake.isLive() == false) {
//Ϸ֮
g.setColor(Color.MAGENTA);
Font tmp = g.getFont();
g.setFont(new Font("",Font.BOLD,30));
g.drawString("Game Over",200, 280);
g.drawString("F2¿ʼ",200,340);
g.setFont(tmp);
return;
}
//ʾϢ
showInfo(g);
//Ϸ
g.setColor(Color.green);
for (int i = 0; i < COLS; i++) {
g.drawLine(i*CELLSIZE,0,i*CELLSIZE,ROWS*CELLSIZE);
}
for (int i = 0; i < ROWS; i++) {
g.drawLine(0,i*CELLSIZE,COLS*CELLSIZE,i*CELLSIZE);
}
//
egg.draw(g);
//߳Լ
snake.eatEgg(egg);
//̰
snake.draw(g);
if(snake.isLive()==false)
{
}
}
public void showInfo(Graphics g)
{
Font f=new Font("",Font.BOLD,20);
g.setFont(f);
g.drawString("ܵ÷: "+snake.getScore(),630,40);
g.drawString("߽: "+snake.getSize(),630,100);
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true)
{
try{
Thread.sleep(500);
if(isPause==true)
{
continue;
}
}catch(Exception e)
{
e.printStackTrace();
}
//»
this.repaint();
}
}
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
switch(arg0.getKeyCode())
{
case KeyEvent.VK_LEFT:
if(snake.head.direction!=Direction.RIGHT)
{
snake.head.direction=Direction.LEFT;
}
break;
case KeyEvent.VK_UP:
if(snake.head.direction!=Direction.DOWN)
{
snake.head.direction=Direction.UP;
}
break;
case KeyEvent.VK_RIGHT:
if(snake.head.direction!=Direction.LEFT)
{
snake.head.direction=Direction.RIGHT;
}
break;
case KeyEvent.VK_DOWN:
if(snake.head.direction!=Direction.UP)
{
snake.head.direction=Direction.DOWN;
}
break;
case KeyEvent.VK_B:
isPause=!isPause;
break;
case KeyEvent.VK_F2: //Ϸ
if (snake.isLive() == false) {
snake.head = new Node(15,20,Direction.LEFT);
snake.live = true;
snake.score = 0;
snake.size = 1;
}
}
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
| true |
b9ebe8324447107d29aafeea3cb1b0c0f65ffe66 | Java | jid1311644/TinyLove | /src/com/example/tinylove/Interface/ItemClickListener.java | UTF-8 | 128 | 1.820313 | 2 | [] | no_license | package com.example.tinylove.Interface;
public interface ItemClickListener {
public void onItemClickListener(int position);
}
| true |
658c22da8f2bb53a518a9241a84f544b0ef2aac0 | Java | Shivarathri/lmsjdbc | /project/librarymanagementjdbc/src/main/java/com/capgemini/librarymanagementjdbc/dao/AdminDAOImplementation.java | UTF-8 | 6,719 | 2.671875 | 3 | [] | no_license | package com.capgemini.librarymanagementjdbc.dao;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import com.capgemini.librarymanagementjdbc.dto.AdminBean;
import com.capgemini.librarymanagementjdbc.dto.BookBean;
import com.capgemini.librarymanagementjdbc.dto.RequestBean;
import com.capgemini.librarymanagementjdbc.dto.UsersBean;
public class AdminDAOImplementation implements AdminDAO {
@Override
public boolean addBook(BookBean book) {
try(FileInputStream fin = new FileInputStream("dburl.properties")){
Properties pro = new Properties();
pro.load(fin);
Class.forName(pro.getProperty("path")).newInstance();
try(Connection conn = DriverManager.getConnection(pro.getProperty("dburl"), pro)){
String query = pro.getProperty("add_book");
try(PreparedStatement pstmt = conn.prepareStatement(query)){
pstmt.setString(1, book.getBname());
pstmt.setInt(2, book.getBid());
pstmt.setString(3, book.getBauthor());
pstmt.setString(4, book.getCategory());
pstmt.setString(5, book.getPublishername());
int count = pstmt.executeUpdate();
}
}
}catch(Exception e) {
e.printStackTrace();
}
return false;
}
@Override
public BookBean searchBookTitle(String bname) {
BookBean bean = new BookBean();
try(FileInputStream fin = new FileInputStream("dburl.properties")){
Properties pro = new Properties();
pro.load(fin);
Class.forName(pro.getProperty("path")).newInstance();
try(Connection conn = DriverManager.getConnection(pro.getProperty("dburl"), pro)){
String query = pro.getProperty("search_book_name");
try(PreparedStatement pstmt = conn.prepareStatement(query)){
pstmt.setString(1, bname);
ResultSet rs = pstmt.executeQuery();
if(rs.next()) {
bean.setBid(rs.getInt("bid"));
bean.setBname(rs.getString("bname"));
bean.setBauthor(rs.getString("author"));
bean.setCategory(rs.getString("category"));
bean.setPublishername(rs.getString("publishername"));
return bean;
} else {
System.out.println("book not found");
}
}
}
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public BookBean searchBookAuthor(String bAuthor) {
BookBean bean = new BookBean();
try(FileInputStream fin = new FileInputStream("dburl.properties")){
Properties pro = new Properties();
pro.load(fin);
Class.forName(pro.getProperty("path")).newInstance();
try(Connection conn = DriverManager.getConnection(pro.getProperty("dburl"), pro)){
String query = pro.getProperty("search_book_author");
try(PreparedStatement pstmt = conn.prepareStatement(query)){
pstmt.setString(1, bAuthor);
ResultSet rs = pstmt.executeQuery();
if(rs.next()) {
bean.setBid(rs.getInt("bid"));
bean.setBname(rs.getString("bname"));
bean.setBauthor(rs.getString("author"));
bean.setCategory(rs.getString("category"));
bean.setPublishername(rs.getString("publishername"));
return bean;
} else {
System.out.println("book not found");
}
}
}
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public BookBean searchBookType(String bookType) {
BookBean bean = new BookBean();
try(FileInputStream fin = new FileInputStream("dburl.properties")){
Properties pro = new Properties();
pro.load(fin);
Class.forName(pro.getProperty("path")).newInstance();
try(Connection conn = DriverManager.getConnection(pro.getProperty("dburl"), pro)){
String query = pro.getProperty("search_book_id");
try(PreparedStatement pstmt = conn.prepareStatement(query)){
pstmt.setString(1, bookType);
ResultSet rs = pstmt.executeQuery();
if(rs.next()) {
bean.setBid(rs.getInt("bid"));
bean.setBname(rs.getString("bname"));
bean.setBauthor(rs.getString("author"));
bean.setCategory(rs.getString("category"));
bean.setPublishername(rs.getString("publishername"));
return bean;
} else {
System.out.println("book not found");
}
}
}
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public int updateBook(int bid) {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean removeBook(int bid) {
// TODO Auto-generated method stub
return false;
}
@Override
public LinkedList<Integer> getBookIds() {
try(FileInputStream fin = new FileInputStream("dburl.properties")){
Properties pro = new Properties();
pro.load(fin);
List<Integer> list = new LinkedList<Integer>();
Class.forName(pro.getProperty("path")).newInstance();
try(Connection conn = DriverManager.getConnection(pro.getProperty("dburl"), pro)){
String query = pro.getProperty("get_bookId");
try(Statement stmt = conn.createStatement()){
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
BookBean bean = new BookBean();
bean.setBid(rs.getInt("bid"));
}
}
}
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public LinkedList<BookBean> getBooksInfo() {
try(FileInputStream fin = new FileInputStream("dburl.properties")){
Properties pro = new Properties();
pro.load(fin);
LinkedList<BookBean> li = new LinkedList<BookBean>();
Class.forName(pro.getProperty("path")).newInstance();
try(Connection conn = DriverManager.getConnection(pro.getProperty("dburl"), pro)){
String query = pro.getProperty("get_allBook");
try(Statement stmt = conn.createStatement()){
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
BookBean bean = new BookBean();
bean.setBid(rs.getInt("bid"));
bean.setBname(rs.getString("bname"));
bean.setBauthor(rs.getString("author"));
bean.setCategory(rs.getString("category"));
bean.setPublishername(rs.getString("publishername"));
li.add(bean);
}
return li;
}
}
}catch(Exception e) {
e.printStackTrace();
return null;
}
}
@Override
public List<UsersBean> showUsers() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<RequestBean> showRequests() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean bookIssue(UsersBean user, BookBean book) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isBookReceived(UsersBean user, BookBean book) {
// TODO Auto-generated method stub
return false;
}
}
| true |
b05a20c2e95025705441d3f41fef687b97887a0e | Java | EngulfMiss/LearnJava2 | /LearnReflect/annotation/Reflect/Demo1.java | UTF-8 | 144 | 1.78125 | 2 | [] | no_license | package LearnReflect.annotation.Reflect;
public class Demo1 {
public void show(){
System.out.println("showyishow");
}
}
| true |
fce4be0fc5a7081faf8c5c4723e389670278c41b | Java | piefel/testing-spring-contexts | /src/test/java/mockmvc/example/WebAppContextJMockitTest.java | UTF-8 | 3,869 | 2.15625 | 2 | [] | no_license | package mockmvc.example;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.validation.Errors;
import org.springframework.web.context.WebApplicationContext;
import global.Log;
import mockit.Capturing;
import mockit.Delegate;
import mockit.Expectations;
/**
* The same tests as in {@link StandaloneJMockitTest}, but creating the {@link MockMvc} object with a call to
* {@link MockMvcBuilders#webAppContextSetup(WebApplicationContext)} instead of
* {@link MockMvcBuilders#standaloneSetup(Object...)}.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = WebAppContextJMockitTest.WebAppConfig.class)
public final class WebAppContextJMockitTest {
@Configuration
@ComponentScan(excludeFilters = @ComponentScan.Filter(value = Configuration.class, type = FilterType.ANNOTATION))
static class WebAppConfig {
@Bean
RequestService requestService() {
Log.append("@rs ");
return new RequestService() {
@Override
public RequestComment getRequestCommentByUUID(String uuid) {
Log.append("grc");
return null;
}
};
}
@Bean
CommentValidator validator() {
Log.append("@cv ");
return new CommentValidator();
}
}
// These two fields provide access to the beans created in the configuration, as mocked instances.
@Capturing
RequestService requestService;
@Capturing
CommentValidator validator;
@Autowired
WebApplicationContext context;
MockMvc mockMvc;
@BeforeClass
public static void setupLog() {
Log.init("WebAppContextJMockitTest");
}
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
new Expectations() {{
validator.supports((Class<?>) any);
result = true;
}};
}
@Test
public void saveCommentWhenRequestCommentIsNotFound() throws Exception {
new Expectations() {{
requestService.getRequestCommentByUUID("123");
result = null;
}};
mockMvc.perform(post("/comment/{uuid}", "123"))
.andExpect(status().isFound())
.andExpect(view().name("redirect:/dashboard"));
Log.log();
}
// @Test
public void saveCommentWhenThereIsAFormError() throws Exception {
new Expectations() {{
requestService.getRequestCommentByUUID("123");
result = new RequestComment();
validator.validate(any, (Errors) any);
result = new Delegate() {
@SuppressWarnings("unused")
void validate(Object target, Errors errors) {
errors.reject("forcing some error");
}
};
}};
mockMvc.perform(post("/comment/{uuid}", "123"))
.andExpect(status().isOk())
.andExpect(view().name("comment"));
Log.log();
}
// @Test
public void saveComment() throws Exception {
new Expectations() {{
requestService.getRequestCommentByUUID("123");
result = new RequestComment();
}};
mockMvc.perform(post("/comment/{uuid}", "123"))
.andExpect(status().isOk())
.andExpect(view().name("ok"));
Log.log();
}
}
| true |
045a3b0ac95a7070634fe1bfe73b9982986fda1e | Java | AlbertoMGV/SoftDesign_E3 | /SD3_DeustoAir_Server/src/es/deusto/deustoair/server/gateway/PaypalPaymentProcessor.java | UTF-8 | 421 | 2.203125 | 2 | [] | no_license | package es.deusto.deustoair.server.gateway;
import es.deusto.deustoair.server.data.Payment;
public class PaypalPaymentProcessor implements IPaymentGateway{
private String email, password;
public PaypalPaymentProcessor(String email, String password) {
this.email = email;
this.password = password;
}
@Override
public Payment pay(float price) {
// TODO Auto-generated method stub
return null;
}
}
| true |
79026348645d10c617814fd38146374b560f5f08 | Java | dhanashreejava/BankApplication | /src/Saving.java | UTF-8 | 496 | 2.203125 | 2 | [] | no_license |
public class Saving extends Account{
int saving_Id;
int saving_limit;
int saving_in;
public int getSaving_id() {
return saving_Id;
}
public void setSaving_id(int saving_id) {
this.saving_Id = saving_id;
}
public int getSaving_limit() {
return saving_limit;
}
public void setSaving_limit(int saving_limit) {
this.saving_limit = saving_limit;
}
public int getSaving_in() {
return saving_in;
}
public void setSaving_in(int saving_in) {
this.saving_in = saving_in;
}
}
| true |
397ab1baf705a28ff74dd43f25a2483b3aad5ab2 | Java | Zeegit/fin | /src/main/java/ru/zeet/fin/service/SecurityService.java | UTF-8 | 2,148 | 2.296875 | 2 | [] | no_license | package ru.zeet.fin.service;
import org.springframework.stereotype.Service;
import ru.zeet.fin.converter.ServiceUserToUserDtoConverter;
import ru.zeet.fin.dao.ServiceUserDao;
import ru.zeet.fin.domain.ServiceUser;
import ru.zeet.fin.dto.UserDto;
import ru.zeet.fin.exception.CommonServiceException;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;
@Service
public class SecurityService {
private final ServiceUserDao serviceUserDao;
private final DigestService digestService;
private final ServiceUserToUserDtoConverter serviceUserToUserDtoConverter;
public SecurityService(ServiceUserDao serviceUserDao, DigestService digestService, ServiceUserToUserDtoConverter serviceUserToUserDtoConverter) {
this.serviceUserDao = serviceUserDao;
this.digestService = digestService;
this.serviceUserToUserDtoConverter = serviceUserToUserDtoConverter;
}
public UserDto auth(String email, String passwoed) {
ServiceUser serviceUser = serviceUserDao.findByEmail(email);
if (serviceUser != null) {
String passwordHash = digestService.hash(passwoed);
if (passwordHash.equals(serviceUser.getPassword())) {
return serviceUserToUserDtoConverter.convert(serviceUser);
}
}
return null;
}
public UserDto register(String email, String password) {
ServiceUser serviceUser = serviceUserDao.findByEmail(email);
if (serviceUser == null) {
serviceUser = new ServiceUser();
serviceUser.setEmail(email);
serviceUser.setPassword(digestService.hash(password));
serviceUserDao.insert(serviceUser);
/*try {
authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(email, password));
} catch (AuthenticationException e) {
throw new CustomException(e);
}
return (CustomUserDetails) authentication.getPrincipal();*/
}
return serviceUserToUserDtoConverter.convert(serviceUser);
}
}
| true |
cf58d841c5aeb140baabbc16eed3445697e0359d | Java | apratapani/advanced-java-spring | /src/main/java/platform/codingnomads/co/corespring/examples/autowiredannotation/GeForce.java | UTF-8 | 193 | 1.601563 | 2 | [] | no_license | package platform.codingnomads.co.corespring.examples.autowiredannotation;
import org.springframework.stereotype.Component;
@Component("geforce")
public class GeForce implements VideoCard {
}
| true |
4ddebc9bf8466a2a098c28bbcfba982611c4697d | Java | MrSkip/cinema | /src/main/java/com/countrycinema/ua/persistence/entity/Company.java | UTF-8 | 1,129 | 2.109375 | 2 | [] | no_license | package com.countrycinema.ua.persistence.entity;
import com.countrycinema.ua.persistence.entity._core.time.TimeComponentString;
import com.countrycinema.ua.persistence.entity.equipment.Equipment;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "companies")
@Data
@ToString(callSuper = true, exclude = {"users"})
@EqualsAndHashCode(callSuper = true, exclude = {"users"})
public class Company extends TimeComponentString<Company> {
@Column(name = "name", nullable = false, unique = true)
private String name;
@Column(name = "email", nullable = false, unique = true)
private String email;
@Column(name = "timeZone")
private String timeZone;
@OneToMany(mappedBy = "company", orphanRemoval = true, cascade = CascadeType.ALL)
private List<User> users;
@OneToMany(mappedBy = "company", orphanRemoval = true, cascade = CascadeType.ALL)
private List<Hall> halls;
@OneToMany(mappedBy = "company", orphanRemoval = true, cascade = CascadeType.ALL)
private List<Equipment> equipment;
}
| true |
0805b37f1caec5f0b8a8db6bbd1195817e1de5a9 | Java | wallxu/wallxuCloud | /wallxu-seckill/wallxu-seckill-web/src/main/java/com/wallxu/seckill/interceptor/UserHandlerMethodArgumentResolver.java | UTF-8 | 2,064 | 2.34375 | 2 | [] | no_license | package com.wallxu.seckill.interceptor;
import com.wallxu.common.utils.FastJsonUtil;
import com.wallxu.common.utils.RedisUtil;
import com.wallxu.seckill.annotation.UserInfo;
import com.wallxu.seckill.dao.domain.TbMiaoshaUser;
import org.springframework.core.MethodParameter;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
* Created by Administrator on 2018/7/31.
*/
/**
* @Description: 用户token处理,判断用户登录状态
* @author Administrator
* @date 2018/8/1 9:46
*/
public class UserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
if(methodParameter.hasParameterAnnotation(UserInfo.class)){
return true; //需要继续验证
}
//不包含这个参数,不需要验证
return false;
}
@Override
public Object resolveArgument(MethodParameter methodParameter, @Nullable ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, @Nullable WebDataBinderFactory webDataBinderFactory) throws Exception {
UserInfo userInfo = methodParameter.getParameterAnnotation(UserInfo.class);
// HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest();
//从session的scope里取UserInfo注解里的value属性值的key的value
String token = (String)nativeWebRequest.getAttribute(userInfo.value(), NativeWebRequest.SCOPE_SESSION);
//判断redis里数据是否过期
String tokenVal = RedisUtil.get(token);
//成功后,只能返回对象,返回string不行。失败返回null即可
return tokenVal == null? null: FastJsonUtil.parseToClass(tokenVal, TbMiaoshaUser.class);
}
}
| true |
f2a6ea769a6d77151f868099ca17923a479f9d1a | Java | sheldorTheConqueror73/AgileBandits | /src/renderer/BasicRayTracer.java | UTF-8 | 11,475 | 2.65625 | 3 | [] | no_license | package renderer;
import algo.SuperSampling;
import elements.LightSource;
import primitives.*;
import scene.Scene;
import geometries.Intersectable.GeoPoint;
import java.util.ArrayList;
import java.util.List;
import static primitives.Util.alignZero;
public class BasicRayTracer extends RayTracerBase {
private static final int MAX_CALC_COLOR_LEVEL = 10;
private static final double MIN_CALC_COLOR_K = 0.001;
private static final double INITIAL_K = 1.0;
private static int COUNT_RAYS=100;
private static double RADIUS_SAMPLE=10.0;
public static boolean flagSoftShadows=false;
private static String samplingAlgo="RANDOM";
/**
* ctor
* @param _scene
*/
public BasicRayTracer(Scene _scene) {
super(_scene);
}
/**
* set super sampling's algorithm kind
* @param samplingAlgo string of the kind
* @return
*/
public BasicRayTracer setSamplingAlgo(String samplingAlgo) {
if(samplingAlgo!="RANDOM" && samplingAlgo!="DISTRIBUTED")
throw new IllegalArgumentException("you must select one of the two allowed algorithems");
BasicRayTracer.samplingAlgo = samplingAlgo;
return this;
}
/**
* setter
* @param countRays count of rays for super Sampling
* @return
*/
public BasicRayTracer setCountRays(int countRays) {
COUNT_RAYS = countRays;
return this;
}
/**
* setter
* @param flagSoftShadows true if do the soft shadows algo
* @return
*/
public BasicRayTracer setFlagSoftShadows(boolean flagSoftShadows) {
BasicRayTracer.flagSoftShadows = flagSoftShadows;
return this;
}
/**
* setter
* @param radiusSample radius of the super sampling
* @return
*/
public BasicRayTracer setRadiusSample(double radiusSample) {
RADIUS_SAMPLE = radiusSample;
return this;
}
/**
* traces ray and calcs color
* @param ray ray to trace
* @return
*/
@Override
public Color traceRay(Ray ray) {
GeoPoint closestPoint = findClosestIntersection(ray);
return closestPoint == null ? scene.background : calcColor(closestPoint, ray);
}
/**
* return the color of pixel
* @param c0 top left corner
* @param c1 top right corner
* @param c2 bottom left corner
* @param c3 bottom right corner
* @param camPos camera position
* @param level recursion level
* @return
*/
@Override
public Color adaptiveTrace(Point3D c0,Point3D c1,Point3D c2,Point3D c3,Point3D camPos,int level ){
return adaptiveCalc(c0,c1,c2,c3,camPos,level);
}
/**
* retrun pixel's color
* @param geoPoint geometry and point
* @param ray ray
* @return
*/
private Color calcColor(GeoPoint geoPoint, Ray ray) {
return calcColor(geoPoint, ray, MAX_CALC_COLOR_LEVEL, INITIAL_K)
.add(scene.ambientLight.getIntensity());
}
/**
* calcs color at goepoint
* @param point point
* @param ray ray
* @return
*/
Color calcColor(GeoPoint point, Ray ray,int level,double k) {
Color color=point.geometry.getEmission();
color= color.add(calcLocalEffects(point,ray,k));
return 1==level?color:color.add(calcGlobalEffects(point,ray.getDir(),level,k));
}
/**
* return the global effect color
* @param gp geomtery and point
* @param v vector of the ray
* @param level recursion level
* @param k initial k (kt,ktr...)
* @return
*/
private Color calcGlobalEffects(GeoPoint gp, Vector v, int level, double k) {
Color color = Color.BLACK; Vector n = gp.geometry.getNormal(gp.point);
Material material = gp.geometry.getMaterial();
double kkr = k * material.kR;
if (kkr > MIN_CALC_COLOR_K)
color = calcGlobalEffect(constructReflectedRay(n,gp.point,v), level, material.kR, kkr);
double kkt = k * material.kT;
if (kkt > MIN_CALC_COLOR_K)
color = color.add(
calcGlobalEffect(constructRefractedRay(n,gp.point, v), level, material.kT, kkt));
return color;
}
/**
*
* @param ray ray
* @param level recrusion level
* @param kx the lest level
* @param kkx this level
* @return
*/
private Color calcGlobalEffect(Ray ray, int level, double kx, double kkx) {
GeoPoint gp = findClosestIntersection(ray);
if(gp==null){
return scene.background.scale(kx);
}
Color temp=calcColor(gp, ray, level-1, kkx);
return temp.scale(kx);
}
/**
* return ray of reflected
* @param n normal
* @param point point on the geometry
* @param v direction of the ray
* @return
*/
private Ray constructReflectedRay(Vector n, Point3D point, Vector v){
double temp = v.dotProduct(n)*2;
Vector r = v.subtract(n.scale(temp));
return new Ray(point,r,n);
}
/**
* return ray of reflaction
* @param n normal
* @param point point on the geometry
* @param v the ray's direction
* @return
*/
private Ray constructRefractedRay(Vector n,Point3D point,Vector v){
return new Ray(point,v,n);
}
private GeoPoint findClosestIntersection(Ray ray){
var points=scene.geometries.findGeoIntersections(ray);
return ray.getClosestGeoPoint(points);
}
/**
* clacs local effect
* @param intersection intersection point
* @param ray ray
* @return
*/
private Color calcLocalEffects(GeoPoint intersection, Ray ray,double k) {
Vector v = ray.getDir();
Vector n = intersection.geometry.getNormal(intersection.point);
double nv = alignZero(n.dotProduct(v));
if (nv == 0)
return Color.BLACK;
int nShininess = intersection.geometry.getMaterial().getnShininess();
double kd = intersection.geometry.getMaterial().getkD(),
ks = intersection.geometry.getMaterial().getkS();
Color color = Color.BLACK;
for (LightSource lightSource : scene.lights) {
Vector l = lightSource.getL(intersection.point);
double nl = alignZero(n.dotProduct(l));
if (nl * nv > 0) {// sign(nl) == sing(nv)
double ktr=transparency(lightSource,l,n, intersection);
if (ktr * k > MIN_CALC_COLOR_K) {
Color lightIntensity = lightSource.getIntensity(intersection.point).scale(ktr);
color = color.add(lightIntensity.scale(calcDiffusive(kd, l, n) + calcSpecular(ks, l, n, v, nShininess)));
}
}
}
return color;
}
/**
* calcs diffusive effect
* @param kd kd coefficient
* @param l l vector
* @param n n vector
* @return
*/
private double calcDiffusive(double kd,Vector l ,Vector n) {
return kd*(Math.abs(l.dotProduct(n)));//add argument l*n
}
/**
* calcs specular effecr
* @param ks ks coefficient
* @param l l vector
* @param n n vector
* @param v vector
* @param nShininess shininess coefficient
* @return
*/
private double calcSpecular(double ks,Vector l ,Vector n,Vector v,int nShininess ) {
Vector temp= n.scale(2*l.dotProduct(n));
Vector r = l.subtract(temp);
Vector temp2= v.scale(-1);
double num= Math.max(0,temp2.dotProduct(r));
return ks*(Math.pow(num,nShininess));
}
/**
* return precent of the shadow at specific point
* @param ls light source
* @param l vector from point to light
* @param n normal
* @param geopoint geometry and point
* @return
*/
private double transparency(LightSource ls, Vector l, Vector n, GeoPoint geopoint) {
Vector lightDirection = l.scale(-1); // from point to light source
double sumKtr = 0.0, baseKtr;
Ray lightRay = new Ray(geopoint.point, lightDirection, n);
baseKtr = calKtr( geopoint, lightRay,ls);
if ( flagSoftShadows) {
List<Ray> beam;
if(samplingAlgo=="DISTRIBUTED")
beam = SuperSampling.distributedSample(lightRay,
geopoint.point.add(lightDirection.scale(ls.getDistance(geopoint.point))), COUNT_RAYS,RADIUS_SAMPLE);
else
beam = SuperSampling.randomSample(lightRay,
geopoint.point.add(lightDirection.scale(ls.getDistance(geopoint.point))), COUNT_RAYS,RADIUS_SAMPLE);
for (int i = 1; i < beam.size(); i++) {
sumKtr += calKtr(geopoint, beam.get(i),ls);
}
baseKtr = (sumKtr + baseKtr) / beam.size();
}
return baseKtr;
}
/**
* return the ktr
* @param geoPoint point and geometry
* @param ray vector from light to point
* @param ls light source
* @return
*/
private double calKtr(GeoPoint geoPoint,Ray ray,LightSource ls){
List<GeoPoint> intersections=scene.geometries.findGeoIntersections(ray);
double lightDistance=ls.getDistance(geoPoint.point);
double ktr=1.0;
if(intersections==null){
return ktr;
}
for (GeoPoint gp : intersections) {
if (alignZero(gp.point.distance(geoPoint.point)-lightDistance) <= 0) {
ktr *= gp.geometry.getMaterial().getKt();
if (ktr < MIN_CALC_COLOR_K){
return 0.0;
}
}
}
return ktr;
}
/**
* return pixel's color
* @param p0 top left
* @param p1 top right
* @param p2 bottom left
* @param p3 bottom right
* @param camPos camera position
* @param level recursion level
* @return
*/
public Color adaptiveCalc(Point3D p0,Point3D p1,Point3D p2,Point3D p3,Point3D camPos,int level){
List<Point3D> edges= List.of(p0,p1,p2,p3);
List<Color> colors= new ArrayList<Color>();
for (int i=0;i<4;i++){
Ray ray= new Ray(camPos,edges.get(i).subtract(camPos).normalized());
GeoPoint point= findClosestIntersection(ray);
if(point!=null){
colors.add(calcColor(point,ray));//calc the corner's color.
}
else{
colors.add(scene.background);
}
}
if((colors.get(0).equals(colors.get(1))&&colors.get(0).equals(colors.get(2))&&colors.get(0).equals(colors.get(3))) || level==0){
return colors.get(0);//if all the corners have the same color.
}
//calc the middle between two corners:
Point3D up=edges.get(0).middleOf(edges.get(1));
Point3D down=edges.get(2).middleOf(edges.get(3));
Point3D r=edges.get(1).middleOf(edges.get(3));
Point3D l=edges.get(0).middleOf(edges.get(2));
Point3D center=r.middleOf(l);
//recursive color calc
return adaptiveCalc(edges.get(0),up,l,center,camPos,level-1).scale(0.25d)
.add(adaptiveCalc(up,edges.get(1),center,r,camPos,level-1).scale(0.25d))
.add(adaptiveCalc(l,center,edges.get(2),down,camPos,level-1).scale(0.25d))
.add(adaptiveCalc(center,r,down,edges.get(3),camPos,level-1).scale(0.25d));
}
}
| true |
0732f9abc6690216578a5081bdb2992727419d93 | Java | fllafquen/Patrones-de-Dise-o | /FactoryMethod/PedidoCredito.java | UTF-8 | 516 | 3.203125 | 3 | [] | no_license | package FactoryMethod;
public class PedidoCredito extends Pedido{
public PedidoCredito(double importe) {
super(importe);
}
@Override
public boolean valida() {
if((importe>=1000.0)&& (importe<=5000.0))
return true;
else
return false;
}
@Override
public void paga() {
System.out.println("El pago del pedido a crédito de: "+importe+" se ha realizado.");
}
@Override
public void falla() {
System.out.println("El pago del pedido por un monto de "+importe+" no pudo ser realizado.");
}
}
| true |
bda65d51c5bfd2c0ad6fc43dce46e5c39a1df839 | Java | CheungBH/HKUEEE | /app/src/main/java/msc/eee/hku/hkueee/facilities/Communication.java | UTF-8 | 1,157 | 2.21875 | 2 | [] | no_license | package msc.eee.hku.hkueee.facilities;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import msc.eee.hku.hkueee.R;
public class Communication extends AppCompatActivity {
private String[] data={"Audio Engineering Lab.","Broadband Networking Lab.","Computer Lab.","Computer Architecture and System Research Lab.","Electromagnetics Lab.","Industrial System Development Unit","Micro wave / RF Engineering Lab.","Multimedia Networking Lab.","Radio Frequency Lab."};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_communication);
// ActionBar actionbar = getSupportActionBar();
// if (actionbar != null){
// actionbar.hide();
// }
ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(
Communication.this, android.R.layout.simple_list_item_1, data);
ListView listViewc = (ListView) findViewById(R.id.list_viewcom);
listViewc.setAdapter(adapter3);
}
}
| true |
e77e0ea4dbb1fc5074ef3a23da8880e6f08a0847 | Java | nusratsultana95/JavaBasic | /src/mentoring/MentoringAssertion.java | UTF-8 | 490 | 2.609375 | 3 | [] | no_license | package mentoring;
import org.testng.Assert;
import org.testng.asserts.SoftAssert;
public class MentoringAssertion {
public static void main(String[] args) {
int a= 10;
int b=12;
int i= 30;
int j= 20;
//hard assert
//Assert.assertEquals(a,b,"assertion failed");
//soft assert
SoftAssert softAssert = new SoftAssert();
softAssert.assertEquals(i,j,"soft assert failed");
softAssert.assertAll();
}
}
| true |
e7a6e4cb8a621bb3bcf2af320b6ba4ce154f9547 | Java | WhaAppsTraining/LoadImageFromNetwork | /app/src/main/java/sembarang/mainanimage/LoadImageWithGlideActivity.java | UTF-8 | 444 | 2.03125 | 2 | [] | no_license | package sembarang.mainanimage;
import android.os.Bundle;
import com.bumptech.glide.Glide;
/**
* Kelas yang mempraktekkan cara untuk download image dan set ke ImageView menggunakan Glide
*/
public class LoadImageWithGlideActivity extends ImageViewActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Glide.with(this).load(imageUrl).into(imageView);
}
}
| true |
a8ea1b44819c104f3f94b241db5a408f2ad2064a | Java | uttejadiraju/JavaLearning | /src/multiThreadingDuragSoft/SynchronizedWithIrregularOutput.java | UTF-8 | 846 | 3.390625 | 3 | [] | no_license | package multiThreadingDuragSoft;
class Display1 {
public synchronized void wish(String name){
for (int i = 0; i < 10; i++) {
System.out.println("Good Morining --" +name);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class myRunnable2 extends Thread {
Display1 d;
String name;
myRunnable2(Display1 d, String name) {
this.d = d;
this.name = name;
}
public void run() {
d.wish(name);
}
}
public class SynchronizedWithIrregularOutput {
public static void main(String[] args) throws InterruptedException {
Display1 d = new Display1();
myRunnable2 t1 = new myRunnable2(d, "dhoni");
myRunnable2 t2 = new myRunnable2(new Display1(), "raina"); // Different objects of display. Irregular output
t1.start();
t2.start();
}
}
| true |
71f4e9ad63cffe1f8a531c32fd2cf24741d61b7a | Java | t4kaha00/software_production_project | /src/botrecvm/Constants.java | UTF-8 | 591 | 1.5625 | 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 botrecvm;
/**
*
* @author vvaisan
*/
public class Constants {
public static final int STOPPED=1;
public static final int RUNNING = 2;
public static final int INVALID = -1;
public static final int EVENT_MOTOR_START = 1;
public static final int EVENT_MOTOR_STOP = 2;
public static final int EVENT_SHOW_SUM = 3;
public static final int EVENT_PRINT_TICKET = 4;
}
| true |
6ffa31d98ae92c57fc073d5430f4de8e23995389 | Java | mygithubwork/midi-relay | /src/main/java/de/paluch/midi/relay/http/RsApplication.java | UTF-8 | 506 | 2.140625 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package de.paluch.midi.relay.http;
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
/**
* @author <a href="mailto:mark.paluch@1und1.de">Mark Paluch</a>
* @since 09.11.12 20:44
*/
public class RsApplication extends Application {
private java.util.Set<java.lang.Object> objects = new HashSet<Object>();
public void setObjects(Set<Object> objects) {
this.objects = objects;
}
@Override
public Set<Object> getSingletons() {
return objects;
}
}
| true |
7c1d53b21ef31b34d05c1b948389b0cac939b634 | Java | velovan/myBooks | /Books/src/Book/Information.java | UTF-8 | 550 | 2.65625 | 3 | [] | no_license | package Book;
public class Information{
public String getWelcomeInformation(){
return " *** Welcome ***";
}
public String getInvalidOptionInformation(){
return "Select a valid option!!\n";
}
public String getValidBookInformation(){
return "Thank You! Enjoy the book.\n";
}
public String getInvalidBookInformation(){
return "Sorry we don't have that book yet.\n";
}
public String getCheckLibNumInformation(){
return "Please talk to Librarian. Thank you.\n";
}
}
| true |
00e3c837ab36b1dac7c0de0381cca402e2a42242 | Java | ChooseSongsSystem/ChooseSongsSystem | /niejinlian/GeQuChose.java | GB18030 | 3,749 | 2.671875 | 3 | [] | no_license | import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Iterator;
import java.util.regex.Pattern;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
@SuppressWarnings("serial")
public class GeQuChose extends JFrame implements ActionListener{
@SuppressWarnings("rawtypes")
JList jlist;
JButton btn1;
JButton btn2;
JTextField txt1;
JLabel jlabel;
String xuanzhong;
int i;
DataInputStream in=null;
DataOutputStream out=null;
Socket socket;
InputStream in_data;
OutputStream out_data;
FileInputStream filein;
FileOutputStream fileout;
String str;
@SuppressWarnings("rawtypes")
DefaultListModel listmode;
JScrollPane sclist;
@SuppressWarnings({ "rawtypes", "unchecked" })
GeQuChose(){
super("ѡ");
this.setSize(300, 500);
this.setVisible(true);
//this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.setLayout(null);
jlabel=new JLabel("Ҫѡ:");
add(jlabel);
jlabel.setBounds(30,10,240,30);
txt1=new JTextField();
add(txt1);
txt1.setBounds(30,60,200,30);
btn1=new JButton("ѯ");
add(btn1);
btn1.setBounds(30, 110, 100, 30 );
btn1.addActionListener(this);
btn2=new JButton("ѡȡ");
add(btn2);
btn2.setBounds(140, 110, 100, 30);
btn2.addActionListener(this);
jlist=new JList();
sclist=new JScrollPane(jlist);
add(sclist);
sclist.setBounds(30,160,200,280);
/*DefaultListModel listModel= (DefaultListModel) jlist.getModel();
listModel.add(listModel.getSize(),"I am Fly");*/
DataModel dm=new DataModel();
jlist.setModel(dm);
this.validate();
go_go1();
}
private void go_go1() {
// TODO Զɵķ
try{
socket=new Socket("localhost",4321);
}
catch(IOException e1){
System.out.println("Ҳ");
}
try{
in_data=socket.getInputStream();
out_data=socket.getOutputStream();
in=new DataInputStream(in_data);
out=new DataOutputStream(out_data);
}
catch(IOException e2){
System.out.println("");
}
}
@SuppressWarnings("rawtypes")
class DataModel extends DefaultListModel {
@SuppressWarnings("unchecked")
DataModel() {
String name=txt1.getText();
SelectClass shuchu=new SelectClass();
String str1=shuchu.SelectGqName(name);
if(str1!=null){
Pattern pattern1=Pattern.compile(",");
String[] str2=pattern1.split(str1);
for(int i=1;i<str2.length;i=i+2){
addElement(str2[i]);
/*System.out.println(str2[i]+",");*/
}
}else{
addElement("Բûҵĸ");
}
}
}
@SuppressWarnings("unchecked")
@Override
public void actionPerformed(ActionEvent e) {
// TODO Զɵķ
if(e.getSource().equals(btn1)){
DataModel dm=new DataModel();
jlist.setModel(dm);
}
if(e.getSource().equals(btn2)){
xuanzhong=(String) jlist.getSelectedValue();
/*System.out.println(xuanzhong+",,,");*/
try{
/* str1=in.readUTF();*/
out.writeUTF(xuanzhong);
/*in.close();
out.close();
socket.close();*/
}
catch(IOException e3){
System.out.println("·ȡ");
}
}
}
public static void main(String args[]){
GeQuChose a=new GeQuChose();
}
}
| true |
ed4aefeb00bd14177bfd6317f6cf9e225dcc403c | Java | nileshkadam222/Core-Java | /Core java - Programmes/for loop/disha12.java | UTF-8 | 379 | 2.921875 | 3 | [] | no_license | import java.io.*;
class disha12
{
public static void main(String ar[])throws IOException
{
int i, n, ans=0;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the value of n");
n=Integer.parseInt(in.readLine());
for(i=1;i<=10;i++)
{
ans=n*i;
System.out.println(+n+"*"+i+"="+ans);
}
}
} | true |
401121d446be266da2a8fcf1af45897564791995 | Java | ysun02/gitlet-version-control-system | /gitlet/Staging.java | UTF-8 | 14,283 | 2.5625 | 3 | [] | no_license | package gitlet;
import java.io.File;
import java.io.Serializable;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Set;
import java.util.ArrayList;
import java.util.List;
import java.util.HashSet;
/** staging class.
* @author Yuan Sun
* */
public class Staging implements Serializable {
/** HashMap<String, String>. */
private HashMap<String, String> _trackedBlobs;
/** HashMap<String, String>. */
private HashMap<String, String> _untracked;
/** HashMap<String, String>. */
private HashMap<String, String> _modifyTracked;
/** HashMap<String, String>. */
private HashMap<String, String> _removeTracked;
/** HashMap<String, String>. */
private HashMap<String, String> _addStage;
/** HashMap<String, String>. */
private HashMap<String, String> _removeStage;
/** constructor for staging. */
public Staging() {
_trackedBlobs = new HashMap<>();
_untracked = new HashMap<>();
_modifyTracked = new HashMap<>();
_removeTracked = new HashMap<>();
_addStage = new HashMap<>();
_removeStage = new HashMap<>();
}
/** Usage: java gitlet.Main add [file name] .
* Description: Adds a copy of the file based on the FILENAME
* as it currently exists to the staging area
* (see the description of the COMMIT command).
* For this reason, adding a file is also called staging the file.
* The staging area should be somewhere in .gitlet.
* If the current working version of the file
* is identical to the version in the current commit,
* do not stage it to be added, and remove it
* from the staging area if it is already there
* (as can happen when a file is changed, added,
* and then changed back).
* If the file had been marked to be removed
* (see gitlet rm), delete that mark.
* Runtime:
* In the worst case, should run in linear time
* relative to the size of the file being added.
* Failure cases: If the file does not exist,
* print the error message File does not exist.
* and exit without changing anything.
*/
public void add(String fileName, Commit commit) {
HashMap<String, String> allBlobs = getTrackedBlobs();
File file = Paths.get(Main.getWorkingDir(), fileName).toFile();
boolean modified;
String uid;
String contents = Utils.readContentsAsString(file);
if (!_removeStage.containsKey(fileName)) {
boolean tracked = allBlobs.containsKey(fileName);
if (tracked) {
modified = modified(fileName, contents, true);
if (!modified) {
return;
}
_modifyTracked.put(fileName, "");
}
Blob blob = new Blob(fileName, contents);
Main.write(Main.getTempBlobPath(), blob.getUID(), blob);
uid = blob.getUID();
} else {
Utils.writeContents(file, contents);
uid = allBlobs.get(fileName);
}
updateStage(fileName, uid);
}
/** rm, given FILENAME and COMMIT. */
public void rm(String fileName, Commit commit) {
HashMap<String, String> allTrackedBlobs = getTrackedBlobs();
boolean tracked = allTrackedBlobs.containsKey(fileName);
boolean staged = _addStage.containsKey(fileName)
|| _removeStage.containsKey(fileName);
File file = Paths.get(Main.getWorkingDir(), fileName).toFile();
if (tracked) {
String uid = allTrackedBlobs.get(fileName);
_addStage.remove(fileName);
_removeStage.put(fileName, allTrackedBlobs.get(fileName));
_modifyTracked.remove(fileName);
_removeTracked.remove(fileName);
Utils.restrictedDelete(file);
File f = Paths.get(Main.getTempBlobPath(), uid).toFile();
f.delete();
} else if (staged) {
_addStage.remove(fileName);
if (!file.exists()) {
_removeStage.put(fileName, _addStage.get(fileName));
} else {
_untracked.put(fileName, _addStage.get(fileName));
}
} else {
System.out.println("No reason to remove the file.");
}
}
/** handle status. */
public void status() {
String stagedInfo = printStaged();
String removedInfo = printRemoved();
String modifiedInfo = printModified();
String untrackedInfo = printUntracked();
untrackedInfo = untrackedInfo.trim();
String all = stagedInfo + removedInfo
+ modifiedInfo + untrackedInfo;
System.out.println(all);
}
/** Return sorted string, given LIST. */
public String sort(ArrayList<String> list) {
for (int i = 0; i < list.size() - 1; i++) {
for (int j = i + 1; j < list.size(); j++) {
String file1 = list.get(i);
String file2 = list.get(j);
if (file1.compareTo(file2) > 0) {
String temp = file2;
list.set(j, file1);
list.set(i, temp);
}
}
}
String files = "";
for (String fileName: list) {
files += (fileName + "\n");
}
files += "\n";
return files;
}
/** Return updated untracked FILENAMES.
* in case the untracked files are not in the
* working dir.
*/
public Set<String> update(Set<String> fileNames) {
Set<String> intersection = new HashSet<>(fileNames);
Set<String> workingFiles = new HashSet<>(
Utils.plainFilenamesIn(Main.getWorkingDir()));
workingFiles.remove("commitsConfig.bin");
workingFiles.remove("stagingConfig.bin");
intersection.retainAll(workingFiles);
return intersection;
}
/** return String. */
public String printUntracked() {
Set<String> fileNames =
getUntracked().keySet();
fileNames = update(fileNames);
fileNames.addAll(Main.getNewFiles());
String header = "=== Untracked Files ===" + "\n";
ArrayList<String> unsorted = new ArrayList<>(fileNames);
header += sort(unsorted);
return header;
}
/** Return sorted strings, given LIST. */
public ArrayList<String> sortModified(ArrayList<String> list) {
for (int i = 0; i < list.size() - 1; i++) {
for (int j = i + 1; j < list.size(); j++) {
String file1 = list.get(i);
String file2 = list.get(j);
if (file1.compareTo(file2) > 0) {
String temp = file2;
list.set(j, file1);
list.set(i, temp);
}
}
}
return list;
}
/** Return print modified string. */
public String printModified() {
Set<String> modified =
getModified().keySet();
Set<String> deleted =
getDeleted().keySet();
String header = "=== Modifications Not Staged For Commit ===" + "\n";
ArrayList<String> unsorted = new ArrayList<>(deleted);
HashSet<String> justDeleted = Main.getJustDeleted();
if (!justDeleted.isEmpty()) {
unsorted.addAll(justDeleted);
}
ArrayList<String> files = sortModified(unsorted);
for (String fileName: files) {
header += (fileName + " (deleted)" + "\n");
}
unsorted = new ArrayList<>(modified);
HashSet<String> toCheck = Main.getJustModified();
if (!toCheck.isEmpty()) {
unsorted.addAll(toCheck);
}
files = sortModified(unsorted);
for (String fileName: files) {
header += (fileName + " (modified)" + "\n");
}
header += "\n";
return header;
}
/** return removed string. */
public String printRemoved() {
Set<String> fileNames =
getRemoveStage().keySet();
String header = "=== Removed Files ===" + "\n";
ArrayList<String> unsorted = new ArrayList<>(fileNames);
header += sort(unsorted);
return header;
}
/** return staged string. */
public String printStaged() {
Set<String> fileNames =
getAddStage().keySet();
String header = "=== Staged Files ===" + "\n";
ArrayList<String> unsorted = new ArrayList<>(fileNames);
header += sort(unsorted);
return header;
}
/** a FILENAME with UID could have 4 stages.
* we need to update them accordingly after a staging occurs
* 1. staged as removal, then remove this record from _removeStage
* 2. tracked but was removed, then remove this record from _removeTracked
* and put it into removeStage for further operations.
* 3. tracked but was modified, removed this record from _modifyTracked
* then put it into _addStage for further operations.
* 4. not tracked at all, remove this from _untracked
* and put it into _addStage for further operations.
*/
public void updateStage(String fileName, String uid) {
boolean stagedAsRemoved = _removeStage.containsKey(fileName);
boolean trackedDel = _removeTracked.containsKey(fileName);
boolean trackedModified = _modifyTracked.containsKey(fileName);
if (trackedDel) {
_removeTracked.remove(fileName);
_removeStage.put(fileName, uid);
} else if (trackedModified) {
_modifyTracked.remove(fileName);
_addStage.put(fileName, uid);
} else if (stagedAsRemoved) {
_removeStage.remove(fileName);
} else {
_untracked.remove(fileName);
_addStage.put(fileName, uid);
}
}
/** post merge update.
* given UPDATEBLOBS, RMBLOBS, CONFLICTS
* @param updateBlobs updated blobs
* @param rmBlobs removed blobs
* @param conflicts conflicts
*/
public void mergeUpdate(HashMap<String, String> updateBlobs,
HashMap<String, String> rmBlobs,
HashMap<String, String> conflicts) {
for (String fileName: updateBlobs.keySet()) {
add(fileName, Main.getAllCommits().getCurrentCommit());
}
for (String fileName: rmBlobs.keySet()) {
_removeStage.put(fileName, rmBlobs.get(fileName));
}
for (String fileName: conflicts.keySet()) {
_modifyTracked.put(fileName, null);
}
}
/** Check whether the files in the staging area have been tracked or not.
*/
public void stagedAllTracked() {
List<String> fileNames = Utils.plainFilenamesIn
(Main.getWorkingDir());
for (String fileName: fileNames) {
File f = Paths.get(Main.getWorkingDir(), fileName).toFile();
String contents = Utils.readContentsAsString(f);
if (getTrackedBlobs().containsKey(fileName)
&& modified(fileName, contents, true)) {
_modifyTracked.put(fileName, "");
} else if (((!getTrackedBlobs().containsKey(fileName))
&& getAddStage().containsKey(fileName)
&& modified(fileName, contents, false))
|| (!getTrackedBlobs().containsKey(fileName)
&& !getAddStage().containsKey(fileName))) {
_untracked.put(fileName, "");
}
}
for (String fileName: _untracked.keySet()) {
File f = Paths.get(Main.getWorkingDir(), fileName).toFile();
if (!f.exists()) {
_untracked.remove(fileName);
}
}
for (String fileName: getTrackedBlobs().keySet()) {
File f = Paths.get(Main.getWorkingDir(), fileName).toFile();
if (!f.exists()) {
_removeStage.put(fileName, getTrackedBlobs().get(fileName));
}
}
}
/** Return _ADDSTAGE. */
public HashMap<String, String> getAddStage() {
return _addStage;
}
/** Return _REMOVESTAGE. */
public HashMap<String, String> getRemoveStage() {
return _removeStage;
}
/** Update my blobs to be the blobs of newest COMMIT. */
public void setBlobs(Commit commit) {
_trackedBlobs = commit.getAllBlobs();
}
/** Clear the staging area. */
public void clearAll() {
_modifyTracked.clear();
_removeTracked.clear();
_addStage.clear();
_removeStage.clear();
}
/** return Tracked files. */
public HashMap<String, String> getTrackedBlobs() {
return _trackedBlobs;
}
/** return untracked files. */
public HashMap<String, String> getUntracked() {
return _untracked;
}
/** return removed blobs. */
public HashMap<String, String> getModified() {
return _modifyTracked;
}
/** return removed tracked blobs. */
public HashMap<String, String> getDeleted() {
return _removeTracked;
}
/** Return true if the FILENAME's CONTENT has been modified.
* otherwise False.
* given TRACKED */
private boolean modified(String fileName, String content, Boolean tracked) {
String currContent = getContents(fileName, tracked);
return !(currContent.equals(content));
}
/** if the FILENAME is not TRACKED by the commit.
* return contents in .tempBlob.
* else, return contents in .blob
* @param fileName a file name,
* @param tracked boolean value.
*/
private String getContents(String fileName, Boolean tracked) {
Blob blob;
String contents;
if (tracked) {
blob = (Blob) Main.read(Main.getBlobPath(),
getTrackedBlobs().get(fileName));
contents = blob.getContents();
} else {
blob = (Blob) Main.read(Main.getTempBlobPath(),
getAddStage().get(fileName));
contents = blob.getContents();
}
return contents;
}
}
| true |
2a8bd7d48a3d0d73f50d997cd4156855a7306f2c | Java | China-YunSu/ActionProcessor | /src/man/kuke/action/core/BeanDefination.java | UTF-8 | 740 | 2.3125 | 2 | [] | no_license | package man.kuke.action.core;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
public abstract class BeanDefination {
protected Method method;
protected Object object;
protected Class<?> klass;
protected Class<?> getKlass() {
return klass;
}
public void setKlass(Class<?> klass) {
this.klass = klass;
}
public Method getMethod() {
return method;
}
public void setMethod(Method method) {
this.method = method;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
public abstract Object[] getValues(Parameter[] parameters,String strValues);
}
| true |
f70b6a36167c17f8218fd711348b91d5d764cdcb | Java | TiagoAlmeidaPoa/designPatterns | /src/main/java/br/fundatec/lp3/lojacelulares/materialfactory/MaterialFactoryCentro.java | UTF-8 | 714 | 2.296875 | 2 | [] | no_license | package br.fundatec.lp3.lojacelulares.materialfactory;
import br.fundatec.lp3.lojacelulares.acessorio.Acessorio;
import br.fundatec.lp3.lojacelulares.acessorio.AcessorioCarregadorPortatil;
import br.fundatec.lp3.lojacelulares.embalagem.Embalagem;
import br.fundatec.lp3.lojacelulares.embalagem.EmbalagemPlastica;
import br.fundatec.lp3.lojacelulares.tinta.Tinta;
import br.fundatec.lp3.lojacelulares.tinta.TintaJato;
public class MaterialFactoryCentro implements MaterialFactory {
public Acessorio prepararAcessorio() {
return new AcessorioCarregadorPortatil();
}
public Tinta prepararTinta() {
return new TintaJato();
}
public Embalagem prepararEmbalagem() {
return new EmbalagemPlastica();
}
}
| true |
b1f0f9849d75de09872224a7fda0d37849ab75a2 | Java | Deadpool110/Leetcode | /training/src/leetcode/_173_BSTIterator.java | UTF-8 | 1,834 | 3.296875 | 3 | [] | no_license | package leetcode;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
public class _173_BSTIterator {
List<Integer> bst;
int tmp;
public _173_BSTIterator(TreeNode root) {
bst = new ArrayList<>();
tmp = 0;
bst.add(-1);
setBst(root, bst);
}
public void setBst(TreeNode root, List<Integer> bst) {
if (root.left != null) {
setBst(root.left, bst);
}
bst.add(root.val);
if (root.right != null) {
setBst(root.right, bst);
}
}
public int next() {
return bst.get(++tmp);
}
public boolean hasNext() {
return tmp + 1 < bst.size();
}
// 扁平化
private int idx;
private List<Integer> arr;
// public BSTIterator(TreeNode root) {
// idx = 0;
// arr = new ArrayList<Integer>();
// inorderTraversal(root, arr);
// }
public int next1() {
return arr.get(idx++);
}
public boolean hasNext1() {
return idx < arr.size();
}
private void inorderTraversal(TreeNode root, List<Integer> arr) {
if (root == null) {
return;
}
inorderTraversal(root.left, arr);
arr.add(root.val);
inorderTraversal(root.right, arr);
}
// 迭代
private TreeNode cur;
private Deque<TreeNode> stack;
// public BSTIterator(TreeNode root) {
// cur = root;
// stack = new LinkedList<TreeNode>();
// }
public int next2() {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
int ret = cur.val;
cur = cur.right;
return ret;
}
public boolean hasNext2() {
return cur != null || !stack.isEmpty();
}
}
| true |
ba6e3d5c4f829048a22335c13026d16d465ddc2c | Java | 18164481730/spring-boot | /src/main/java/com/tangzhihe/dao/UserDao.java | UTF-8 | 229 | 1.859375 | 2 | [] | no_license | package com.tangzhihe.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.tangzhihe.domain.User;
public interface UserDao {
public List<User> queryUserList(@Param("entity")User user);
}
| true |
eb238fd02316084849221de7e1acb91e3602f6ed | Java | maoyujiao/bible1 | /cetbible_lib/src/main/java/com/iyuba/activity/sign/SignActivity.java | UTF-8 | 16,440 | 1.679688 | 2 | [] | no_license | package com.iyuba.activity.sign;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.iyuba.biblelib.R;
import com.iyuba.configation.Constant;
import com.iyuba.configation.ConstantManager;
import com.iyuba.core.manager.AccountManager;
import com.iyuba.core.util.ToastUtil;
import com.umeng.analytics.MobclickAgent;
import org.apache.commons.codec.binary.Base64;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.wechat.moments.WechatMoments;
import okhttp3.Call;
@SuppressLint({"SimpleDateFormat", "SetTextI18n"})
public class SignActivity extends Activity {
private ImageView imageView;
private ImageView qrImage;
private TextView tv1, tv2, tv3;
private Context mContext;
private TextView sign;
private ImageView userIcon;
private TextView tvShareMsg;
private int signStudyTime = 2 * 60;
private String loadFiledHint = "打卡加载失败";
private int totalDays = 0;
String shareTxt;
String getTimeUrl;
LinearLayout ll;
ProgressDialog dialog;
String addCredit = "";//Integer.parseInt(bean.getAddcredit());
String days = "";//Integer.parseInt(bean.getDays());
String totalCredit = "";//bean.getTotalcredit();
String money = "";
private TextView tvUserName;
private TextView tvAppName;
@SuppressLint("HandlerLeak")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_sign);
initView();
initData();
initBackGround();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
private void initData() {
String uid = AccountManager.Instace(mContext).userId;
final String url = String.format(Locale.CHINA,
"http://daxue.iyuba.cn/ecollege/getMyTime.jsp?uid=%s&day=%s&flg=1", uid, getDays());
Log.d("dddd", url);
getTimeUrl = url;
dialog.setMessage("正在加载学习时间,请稍等...");
dialog.show();
Http.get(url, new HttpCallback() {
@Override
public void onSucceed(Call call, String response) {
try {
if (null != dialog) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
final StudyTimeBeanNew bean = new Gson().fromJson(response, StudyTimeBeanNew.class);
Log.d("dddd", response);
if ("1".equals(bean.getResult())) {
final int time = Integer.parseInt(bean.getTotalTime());
int totaltime = Integer.parseInt(bean.getTotalDaysTime());
totalDays = Integer.parseInt(bean.getTotalDays());
String url = "http://static.iyuba.cn/images/mobile/" + (totalDays%30) + ".jpg";
Glide.with(mContext).load(url).placeholder(R.drawable.place).dontAnimate().into(imageView);
tv1.setText("学习天数:\n" + bean.getTotalDays() + "");
tv2.setText("单词数:\n" + bean.getTotalWords() + "");
int rankRate = 100 - Integer.parseInt(bean.getRanking()) * 100 / Integer.parseInt(bean.getTotalUser());
tv3.setText("超越了:\n" + rankRate + "%同学");
shareTxt = bean.getSentence() + "我在爱语吧坚持学习了" + bean.getTotalDays() + "天,积累了" + bean.getTotalWords()
+ "单词如下";
if (time < signStudyTime) {
sign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toast(String.format(Locale.CHINA, "打卡失败,当前已学习%d秒,\n满%d分钟可打卡", time, signStudyTime / 60));
}
});
} else {
sign.setOnClickListener(new View.OnClickListener() {
@SuppressLint("NewApi")
@Override
public void onClick(View v) {
qrImage.setVisibility(View.VISIBLE);
sign.setVisibility(View.GONE);
tvShareMsg.setVisibility(View.VISIBLE);
findViewById(R.id.tv_close).setVisibility(View.INVISIBLE);
tvShareMsg.setText("长按图片识别二维码");
tvShareMsg.setGravity(Gravity.CENTER_HORIZONTAL);
findViewById(R.id.tv_desc).setVisibility(View.VISIBLE);
tvShareMsg.setBackground(getResources().getDrawable(R.drawable.sign_bg_yellow));
writeBitmapToFile();
findViewById(R.id.tv_desc).setVisibility(View.INVISIBLE);
showShareOnMoment(mContext, AccountManager.Instace(mContext).userId + "", Constant.APPID + "");
}
});
}
} else {
toast(loadFiledHint + bean.getResult());
}
} catch (Exception e) {
e.printStackTrace();
toast(loadFiledHint + "!!");
}
}
@Override
public void onError(Call call, Exception e) {
dialog.dismiss();
}
});
}
private void toast(String msg) {
Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
}
private long getDays() {
//东八区;
Calendar cal = Calendar.getInstance(Locale.CHINA);
cal.set(1970, 0, 1, 0, 0, 0);
Calendar now = Calendar.getInstance(Locale.CHINA);
long intervalMilli = now.getTimeInMillis() - cal.getTimeInMillis();
long xcts = intervalMilli / (24 * 60 * 60 * 1000);
return xcts;
}
private void initView() {
imageView = findViewById(R.id.iv);
tv1 = findViewById(R.id.tv1);
tv2 = findViewById(R.id.tv2);
tv3 = findViewById(R.id.tv3);
sign = findViewById(R.id.tv_sign);
ll = findViewById(R.id.ll);
qrImage = findViewById(R.id.tv_qrcode);
userIcon = findViewById(R.id.iv_userimg);
tvUserName = findViewById(R.id.tv_username);
tvAppName = findViewById(R.id.tv_appname);
tvShareMsg = findViewById(R.id.tv_sharemsg);
findViewById(R.id.tv_close).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showCloseAlert();
}
});
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);//循环滚动
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(true);//false不能取消显示,true可以取消显示
}
private void showCloseAlert() {
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle("温馨提示");
dialog.setMessage("点击下面的打卡按钮,成功分享至微信朋友圈,可以领取红包哦!您确定要退出吗?");
dialog.setPositiveButton("留下打卡", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.setNegativeButton("去意已决", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
dialog.show();
}
@Override
protected void onResume() {
super.onResume();
}
private void initBackGround() {
String userIconUrl = "http://api.iyuba.com.cn/v2/api.iyuba?protocol=10005&uid="
+ AccountManager.Instace(mContext).userId + "&size=middle";
Glide.with(mContext).load(userIconUrl).placeholder(R.drawable.noavatar_small).dontAnimate().transform(new CircleTransform(mContext)).into(userIcon);
// Log.d("bible", "initBackGround: " + AccountManager.Instance(mContext).userId + ":" + AccountManager.Instance(mContext).userName);
if (TextUtils.isEmpty(AccountManager.Instace(mContext).userName)) {
tvUserName.setText(AccountManager.Instace(mContext).userId);
} else {
tvUserName.setText(AccountManager.Instace(mContext).userName);
}
if (Constant.APP_CONSTANT.TYPE() .equals("4") ){
tvAppName.setText(Constant.APPName + "--四级考试必备的好帮手!");
}else {
tvAppName.setText(Constant.APPName + "--六级考试必备的好帮手!");
}
Glide.with(mContext).load("").placeholder(R.drawable.qrcode).into(qrImage);
}
@SuppressLint("NewApi")
public void writeBitmapToFile() {
View view = findViewById(R.id.rr);
// View view1 = LayoutInflater.from(mContext).inflate(R.layout.activity_sign,null);
((TextView)findViewById(R.id.tv_desc)).setText("在 "+ Constant.APPName+" 上完成了打卡");
// int[] location = new int[2];
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
if (bitmap == null) {
// Log.d("bible", "writeBitmapToFile: ");
return;
}
Log.d("bible", "writeBitmapToFile: ");
bitmap.setHasAlpha(false);
bitmap.prepareToDraw();
File newpngfile = new File(Environment.getExternalStorageDirectory(), "iyuba/aaa.png");
if (newpngfile.exists()) {
newpngfile.delete();
}
try {
FileOutputStream out = new FileOutputStream(newpngfile);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @author
* @time
* @describe 启动获取积分(红包的接口)
*/
private void startInterfaceADDScore(String userID, String appid) {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = formatter.format(currentTime);
// final String time = Base64Coder.encode(dateString);
final String time = new String(Base64.encodeBase64(dateString.getBytes()));
String url = "http://api.iyuba.cn/credits/updateScore.jsp?srid=81&mobile=1&flag="+ time + "&uid=" + userID
+ "&appid=" + appid;
Http.get(url, new HttpCallback() {
@Override
public void onSucceed(Call call, String response) {
final SignBean bean = new Gson().fromJson(response, SignBean.class);
if (bean.getResult().equals("200")) {
money = bean.getMoney();
addCredit = bean.getAddcredit();
days = bean.getDays();
totalCredit = bean.getTotalcredit();
//打卡成功,您已连续打卡xx天,获得xx元红包,关注[爱语课吧]微信公众号即可提现!
runOnUiThread(new Runnable() {
@Override
public void run() {
float moneyThisTime = Float.parseFloat(money);
MobclickAgent.onEvent(mContext, "dailybonus");
if (moneyThisTime > 0) {
float moneyTotal = Float.parseFloat(totalCredit);
DecimalFormat format = new DecimalFormat("##0.00");
String money = format.format(((moneyThisTime) * 0.01));
String moneyTotalS = format.format(((moneyTotal) * 0.01));
Toast.makeText(mContext, "打卡成功," + "您已连续打卡" + days + "天, 获得" + money + "元,总计: " + moneyTotalS + "元," + "满10元可在\"爱语课吧\"公众号提现", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(mContext, "打卡成功,连续打卡" + days + "天,获得" + addCredit + "积分,总积分: " + totalCredit, Toast.LENGTH_LONG).show();
finish();
}
}
});
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(mContext, "您今日已打卡", Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
public void onError(Call call, Exception e) {
}
});
}
public void showShareOnMoment(Context context, final String userID, final String AppId) {
OnekeyShare oks = new OnekeyShare();
//关闭sso授权
oks.disableSSOWhenAuthorize();
oks.setPlatform(WechatMoments.NAME);
// titleUrl是标题的网络链接,仅在人人网和QQ空间使用
oks.setImagePath(Environment.getExternalStorageDirectory() + "/iyuba/aaa.png");
oks.setSilent(true);
oks.setCallback(new PlatformActionListener() {
@Override
public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
startInterfaceADDScore(userID, AppId);
finish();
ToastUtil.showToast(mContext, "分享成功");
}
@Override
public void onError(Platform platform, int i, Throwable throwable) {
Log.e("okCallbackonError", "onError");
Log.e("--分享失败===", throwable.toString());
finish();
}
@Override
public void onCancel(Platform platform, int i) {
Log.e("okCallbackonError", "onCancel");
Log.e("--分享取消===", "....");
finish();
}
});
// 启动分享GUI
oks.show(context);
}
}
| true |
14fe284935d37928ac24581cb472ca09797ffaf3 | Java | jhosep2001/crowdFunding | /src/main/java/com/crowd/repository/PublisherDAO.java | UTF-8 | 266 | 1.71875 | 2 | [] | no_license | package com.crowd.repository;
import com.crowd.entities.Publisher;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PublisherDAO extends JpaRepository<Publisher,Long> {
}
| true |
a1d16a6bd33a21eee4a0252bb6794b6b3d7bcdcb | Java | SBeausoleil/Echelon | /src/main/java/com/sb/echelon/exceptions/NoIdFieldException.java | UTF-8 | 489 | 2.484375 | 2 | [
"MIT"
] | permissive | package com.sb.echelon.exceptions;
public class NoIdFieldException extends EchelonRuntimeException {
private static final long serialVersionUID = -4308582206714518021L;
public NoIdFieldException(Class<?> clazz) {
super("The class " + clazz.getName() + " has no usable ID field. For a field to be used by Echelon, it must be of type long and be either named id or annotated with @Id");
}
public NoIdFieldException(String message, Exception cause) {
super(message, cause);
}
}
| true |
82cf2e031230ad8b267d9fcb2c0a5b60271d49f4 | Java | lavaalone/cgm | /src/com/vng/nettyhttp/ServerPipelineFactory.java | UTF-8 | 1,768 | 1.960938 | 2 | [] | no_license | package com.vng.nettyhttp;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.*;
import static org.jboss.netty.channel.Channels.*;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.handler.codec.http.HttpContentCompressor;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpResponseEncoder;
import org.jboss.netty.handler.stream.ChunkedWriteHandler;
import org.jboss.netty.handler.timeout.IdleStateHandler;
import org.jboss.netty.handler.ssl.SslHandler;
import org.jboss.netty.util.HashedWheelTimer;
import com.vng.skygarden._gen_.*;
public class ServerPipelineFactory implements ChannelPipelineFactory
{
private static final int _MAX_HTTP_SIZE = 32000;
private static final int _SERVER_TIMEOUT_HTTP_READ = 4000;
private static final int _SERVER_TIMEOUT_HTTP_WRITE = 6000;
private final HashedWheelTimer _timer;
ServerPipelineFactory ()
{
_timer = new HashedWheelTimer();
}
public ChannelPipeline getPipeline() throws Exception
{
ChannelPipeline pipeline = pipeline();
/*
if (ProjectConfig.USE_HTTPS)
{
SSLEngine engine = SslContextFactory.getSslContext().createSSLEngine();
engine.setUseClientMode(false);
pipeline.addLast("ssl", new SslHandler(engine));
}
*/
pipeline.addLast("decoder", new HttpRequestDecoder(_MAX_HTTP_SIZE, _MAX_HTTP_SIZE, _MAX_HTTP_SIZE));
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("timeout", new IdleStateHandler(_timer, _SERVER_TIMEOUT_HTTP_READ, _SERVER_TIMEOUT_HTTP_WRITE, 0, TimeUnit.MILLISECONDS));
pipeline.addLast("handler", new ServerHandler());
return pipeline;
}
}
| true |
9f4239a737ea586072a23edc7cec1e3c8b257f75 | Java | VBurachenko/Pagination | /src/main/java/by/epam/tc/parser/sax/impl/SetOrigin.java | UTF-8 | 343 | 2.078125 | 2 | [] | no_license | package by.epam.tc.parser.sax.impl;
import by.epam.tc.parser.sax.Command;
import by.epam.tc.entity.Plane;
public class SetOrigin extends Command{
private Plane plane;
public SetOrigin(Plane plane) {
super(plane);
}
@Override
public void execute(String content) {
getPlane().setOrigin(content);
}
}
| true |
596df37689ce327edcdc9dc4a15bb6e44ac0ee97 | Java | shadowba/LeetCode_JJ | /src/com/LeetCodeJack/Problems/P744_FindSmallestLetterGreaterThanTarget.java | UTF-8 | 947 | 3.296875 | 3 | [] | no_license | package com.LeetCodeJack.Problems;
public class P744_FindSmallestLetterGreaterThanTarget {
public char nextGreatestLetter(char[] letters, char target) {
if (letters.length == 1)
return letters[0];
int x = target;
int left = 0;
int right = letters.length -1;
int mid = 0;
int res;
while (left <= right) {
mid = left + (right - left) / 2;
if (letters[mid] == target) {
left = mid;
break;
} else if (letters[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
while(mid + 1 <= letters.length - 1 && letters[mid] == letters[mid + 1]){
mid++;
}
if (target - letters[mid] >= 0)
res = mid + 1;
else
res = mid;
return (res >= letters.length) ? letters[0] : letters[res];
}
}
| true |
8df071e13a96913bffef59aadc8955a1cbedd7a7 | Java | saikrishnasahu/junit | /src/test/java/com/junit/helper/ArraysCompareTest.java | UTF-8 | 662 | 2.609375 | 3 | [] | no_license | package com.junit.helper;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertArrayEquals;
public class ArraysCompareTest {
@Test
public void testArrays() {
int[] numbers = {12, 13, 4, 1};
int[] expected = {1, 4, 12, 13};
Arrays.sort(numbers);
assertArrayEquals(expected, numbers);
}
@Test(expected = NullPointerException.class)
public void testArrayException() {
int[] numbers = null;
Arrays.sort(numbers);
}
@Test(timeout = 0)
public void testArrayPerformance() {
int[] numbers = {1, 5, 2, 1};
Arrays.sort(numbers);
}
}
| true |
a7116a135f411de34a79b557829221c2b62e2ec9 | Java | moon-util/moon-util | /src/main/java/com/moon/runner/core/ParseParams.java | UTF-8 | 1,989 | 2.609375 | 3 | [
"MIT"
] | permissive | package com.moon.runner.core;
import com.moon.core.lang.ref.IntAccessor;
import com.moon.runner.RunnerSetting;
import java.util.ArrayList;
import java.util.List;
import static com.moon.core.lang.ThrowUtil.noInstanceError;
import static com.moon.runner.core.Constants.*;
/**
* 方法调用参数解析
*
* @author moonsky
*/
final class ParseParams {
private ParseParams() { noInstanceError(); }
/**
* 从左括号的下一个字符开始解析,右括号为止
* 两个连续逗号之间默认有一个 null 值,
* 最后一个逗号后如果是右圆括号,则忽略
*
* @param chars
* @param indexer
* @param len
* @param settings
* @return
*/
final static AsRunner[] parse(char[] chars, IntAccessor indexer, int len, RunnerSetting settings) {
int curr = ParseUtil.nextVal(chars, indexer, len);
List params = new ArrayList();
AsRunner runner;
outer:
for (int next = curr; ; curr = next) {
switch (next) {
case YUAN_R:
AsValuer[] runners = new AsValuer[params.size()];
return (AsValuer[]) params.toArray(runners);
case SINGLE:
case DOUBLE:
runner = ParseConst.parseStr(chars, indexer, next);
break;
default:
runner = ParseCore.parse(chars, indexer.decrement(), len, settings, COMMA, YUAN_R);
if ((next = chars[indexer.get() - 1]) == YUAN_R) {
params.add(runner);
continue outer;
}
break;
}
params.add(runner);
next = ParseUtil.nextVal(chars, indexer, len);
if (next == COMMA && (runner != DataConst.NULL || (curr != COMMA && curr != YUAN_L))) {
next = ParseUtil.nextVal(chars, indexer, len);
}
}
}
}
| true |