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
75fd57dd459919861e4ce95ead51c147d040b29f
Java
zhouzhitong/maven-java-learning_route
/maven-java-01-design_patterns/src/main/java/com/zzt/behavioral/observer/demo02/EventListener.java
UTF-8
248
2.21875
2
[]
no_license
package com.zzt.behavioral.observer.demo02; import java.io.File; /** * 描述:<br> * </> * * @author 周志通 * @version 1.0.0 * @date 2020/10/14 12:59 */ public interface EventListener { void update(String eventType, File file); }
true
95d45f50afd24c2c9654ca02b19df14fff22996c
Java
roosteracham/quandansb
/src/main/java/刷题/剑指offer/数组中的逆序对.java
UTF-8
917
4
4
[]
no_license
package 刷题.剑指offer; /** * 题目描述 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。 输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007 输入描述: 题目保证输入的数组中没有的相同的数字 数据范围: 对于%50的数据,size<=10^4 对于%75的数据,size<=10^5 对于%100的数据,size<=2*10^5 示例1 输入 1,2,3,4,5,6,7,0 输出 7 */ public class 数组中的逆序对 { public int InversePairs(int[] array) { long sum = 0; for (int i = 0; i < array.length - 1; i++) { for (int j = i; j < array.length; j++) { if (array[i] > array[j]) { sum += 1; } } } return (int) (sum % 1000000007); } }
true
294d46921467fbd805e8091bfecfa11a77bc201d
Java
luiz/monads-in-java
/src/com/github/luiz/monads/Function.java
UTF-8
92
2
2
[ "Apache-2.0" ]
permissive
package com.github.luiz.monads; public interface Function<Arg, Ret> { Ret apply(Arg a); }
true
8c5f6c0329e33a2b8073b94cddc9957193577e6e
Java
Leo-Mun/CS
/Java/OOP/FinalStatic.java
UHC
590
3.0625
3
[]
no_license
package Exercise; public class FinalStatic { public static final String KOOKMIN_UNIV_OFFICIAL_NAME = "Kookmin University"; public static final String KMU_ADDRESS = "Jeonnung Ro 77, Seongbuk Gu, Seoul. South Korea"; private final String birthNation = "Korea"; private final String birthYear; // final ʱȭ ϸ Constructor ʱȭ ؾ private String name; public FinalStatic(String birthYear, String name){ this.birthYear = birthYear; this.name = name; } public void setBirthYear(String birthYear){ // this.birthYear = birthYear; } }
true
48da733573a6706fcc2a6b6615d066c0cbeaab82
Java
Avi-kazi/CakeNation
/CakeNation/src/main/java/com/niit/cakenation/ProductController.java
UTF-8
4,125
2.21875
2
[]
no_license
package com.niit.cakenation; import java.util.List; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import com.niit.cakenationbackend.dao.CategoryDAO; import com.niit.cakenationbackend.dao.ProductDAO; import com.niit.cakenationbackend.dao.SupplierDAO; import com.niit.cakenationbackend.model.Category; import com.niit.cakenationbackend.model.Product; import com.niit.cakenationbackend.model.Supplier; import com.niit.utility.FileUtil; @Controller public class ProductController { Logger log = LoggerFactory.getLogger(ProductController.class); @Autowired private ProductDAO productDao; @Autowired private CategoryDAO categoryDao; @Autowired private SupplierDAO supplierDao; @Autowired HttpSession session; @RequestMapping(value = "/manageproducts", method = RequestMethod.GET) public String getProduct(Model model) { log.debug("entering showAllGreetings"); model.addAttribute("isAdminClickedProducts", "true"); List<Category> categories = categoryDao.list(); List<Supplier> suppliers = supplierDao.list(); List<Product> products = productDao.list(); // if (products!=null && !products.isEmpty()) { model.addAttribute("product", new Product()); model.addAttribute("productlist", products); model.addAttribute("categorylist", categories); model.addAttribute("supplierlist", suppliers); log.debug("Ending Greetings"); // } return "admin/Product"; } @RequestMapping(value = "/manageaddProduct", method = RequestMethod.POST) public String addProduct(@ModelAttribute("product") Product product,Model model) { log.debug("starting add product"); if ((productDao.get(product.getProductid())) == null) { MultipartFile image = product.getFile(); FileUtil.upload("D:/Ws/CakeNation/src/main/webapp/resources/images/", image, product.getProductid() + ".jpg"); productDao.save(product); } else { MultipartFile image = product.getFile(); productDao.update(product); FileUtil.upload("D:/Ws/CakeNation/src/main/webapp/resources/images/", image, product.getProductid() + ".jpg"); model.addAttribute("categorylist", this.categoryDao.list()); model.addAttribute("productlist", this.productDao.list()); model.addAttribute("supplierlist", this.supplierDao.list()); } log.debug("ending Add Product"); return "redirect:/manageproducts"; } @RequestMapping(value = "/manageproduct/delete/{productid}", method = RequestMethod.GET) public String deleteProduct(@PathVariable("productid") String id, ModelMap model) { log.debug("Starting delete Product"); Product product = productDao.get(id); if (product != null) { productDao.delete(product); model.addAttribute("msg", "Successfully Deleted"); } else { model.addAttribute("msg", "Product does not exist"); } log.debug("ending Delete Product"); return "redirect:/manageproducts"; } @RequestMapping(value = "/manageedit/{productid}", method = RequestMethod.GET) public String showEditProduct(@ModelAttribute("product") Product product, ModelMap model) { log.debug("Starting Updating product"); MultipartFile image = product.getFile(); productDao.update(product); FileUtil.upload("D:/Ws/CakeNation/src/main/webapp/resources/images/", image, product.getProductid() + ".jpg"); model.addAttribute("categorylist", this.categoryDao.list()); model.addAttribute("productlist", this.productDao.list()); model.addAttribute("supplierlist", this.supplierDao.list()); return "/admin/Product"; } }
true
d847549fa7843d9e800cc934d7f4b71bcf4f4e3e
Java
TheCheshireCat87/HackerRank
/Java/09 - Comparator/src/Solution.java
UTF-8
2,084
3.0625
3
[]
no_license
/********************************************** * .'\ /`. * * .'.-.`-'.-.`. * * ..._: .-. .-. :_... * * .' '-.(o ) (o ).-' `. * * : _ _ _`~(_)~`_ _ _ : * * : /: ' .-=_ _=-. ` ;\ : * * : :|-.._ ' ` _..-|: : * * : `:| |`:-:-.-:-:'| |:' : * * `. `.| | | | | | |.' .' * * `. `-:_| | |_:-' .' * * `-._ ```` _.-' * * ``-------'' * * The Cheshire Cat * **********************************************/ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; class Checker{ public Comparator<Player> desc = null; public Checker(){ desc = new Comparator<Player>(){ public int compare(Player a, Player b){ int i = a.score - b.score; if(i == 0) i = a.name.compareTo(b.name); return -i; } }; } } class Player{ String name; int score; } public class Solution { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine().trim()); String s; StringTokenizer st; Player[] Player = new Player[N]; Checker check = new Checker(); for(int i = 0; i < N; i++){ s = br.readLine().trim(); st = new StringTokenizer(s); Player[i] = new Player(); Player[i].name = st.nextToken(); Player[i].score = Integer.parseInt(st.nextToken()); } Arrays.sort(Player,check.desc); for(int i = 0; i < Player.length; i++){ System.out.printf("%s %s\n",Player[i].name,Player[i].score); } } }
true
ff5595c2867f53736806d40cce72822c1ab86b18
Java
wckhg89/oauth2_sample
/src/main/java/com/guppy/oauth2sample/repository/MemberRepository.java
UTF-8
397
1.703125
2
[]
no_license
package com.guppy.oauth2sample.repository; import com.guppy.oauth2sample.domain.Member; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; /** * Created by kanghonggu on 2017. 7. 5.. */ @RepositoryRestResource public interface MemberRepository extends PagingAndSortingRepository<Member, Long>{ }
true
0c973b874233946a18a446ed7c616abf8c217b18
Java
Garden-Kim/kosaJava
/20211112/src/multi_implement/RemoteControl.java
UTF-8
198
1.9375
2
[]
no_license
package multi_implement; public interface RemoteControl { int MAX_VOLUME = 10; int MIN_VOLUME = 0; void turnOn(); void turnOff(); void setVolume(); void search(String url); }
true
a3a2ebde72671e922a27d7fda6fd41346249427b
Java
shadabmallick/basketball
/app/src/main/java/com/sport/supernathral/activity/PlayerInfo.java
UTF-8
1,988
2
2
[]
no_license
package com.sport.supernathral.activity; import android.app.ProgressDialog; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.LinearLayout; import android.widget.TextView; import com.sport.supernathral.R; import com.sport.supernathral.Utils.GlobalClass; import com.sport.supernathral.Utils.Shared_Preference; public class PlayerInfo extends AppCompatActivity { String TAG=" About"; GlobalClass globalClass; Shared_Preference preference; ProgressDialog pd; TextView tv_about; Toolbar toolbar; LinearLayout ll_txt_about; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.info_frag); globalClass=(GlobalClass)getApplicationContext(); preference = new Shared_Preference(PlayerInfo.this); preference.loadPrefrence(); pd = new ProgressDialog(PlayerInfo.this); pd.setProgressStyle(ProgressDialog.STYLE_SPINNER); pd.setMessage("Loading..."); initView(); } public void initView(){ toolbar = findViewById(R.id.toolbar); ll_txt_about = findViewById(R.id.ll_txt_about); setSupportActionBar(toolbar); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setHomeAsUpIndicator(R.mipmap.back_black); tv_about=findViewById(R.id.about_us); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; } return true; } }
true
608ef6858ec095a194a9183022bc61f43503b27e
Java
x1uyuan/leetcodePractice
/src/leetcode/editor/cn/P993CousinsInBinaryTree.java
UTF-8
3,419
3.53125
4
[]
no_license
//在二叉树中,根节点位于深度 0 处,每个深度为 k 的节点的子节点位于深度 k+1 处。 // // 如果二叉树的两个节点深度相同,但父节点不同,则它们是一对堂兄弟节点。 // // 我们给出了具有唯一值的二叉树的根节点 root,以及树中两个不同节点的值 x 和 y。 // // 只有与值 x 和 y 对应的节点是堂兄弟节点时,才返回 true。否则,返回 false。 // // // // 示例 1: // // // 输入:root = [1,2,3,4], x = 4, y = 3 //输出:false // // // 示例 2: // // // 输入:root = [1,2,3,null,4,null,5], x = 5, y = 4 //输出:true // // // 示例 3: // // // // 输入:root = [1,2,3,null,4], x = 2, y = 3 //输出:false // // // // 提示: // // // 二叉树的节点数介于 2 到 100 之间。 // 每个节点的值都是唯一的、范围为 1 到 100 的整数。 // // // // Related Topics 树 广度优先搜索 // 👍 99 👎 0 package leetcode.editor.cn; /** * Java:二叉树的堂兄弟节点 * date:2020-10-13 14:38:36 **/ public class P993CousinsInBinaryTree { public static void main(String[] args) { Solution solution = new P993CousinsInBinaryTree().new Solution(); // TO TEST } //leetcode submit region begin(Prohibit modification and deletion) /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public boolean isCousins(TreeNode root, int x, int y) { TreeNode xFather = getFather(root, x); TreeNode yFather = getFather(root, y); int xDepth = getDepth(root, x, 0); int yDepth = getDepth(root, y, 0); return xDepth == yDepth && !xFather.equals(yFather); } private TreeNode getFather(TreeNode node, int x) { if (node == null) return null; if (node.left != null && node.right != null) { if (node.left.val == x || node.right.val == x) return node; else if (getFather(node.left, x) != null) return getFather(node.left, x); if (getFather(node.right, x) != null) return getFather(node.right, x); } else if (node.left != null) { if (node.left.val == x) return node; else return getFather(node.left, x); } else if (node.right != null) { if (node.right.val == x) return node; else return getFather(node.right, x); } return null; } private int getDepth(TreeNode node, int val, int cDepth) { if (node == null) return -1; if (node.val == val) return cDepth; else if (node.left == null) { return getDepth(node.right, val, cDepth + 1); } else if (node.right == null) { return getDepth(node.left, val, cDepth + 1); } else { return Math.max(getDepth(node.right, val, cDepth + 1), getDepth(node.left, val, cDepth + 1)); } } } //leetcode submit region end(Prohibit modification and deletion) }
true
83f6af19f9482920a3bc8f15a4c9e40fcd0cf93c
Java
cmFodWx5YWRhdjEyMTA5/smell-and-machine-learning
/ast_results/cgeo_c-geo-opensource/main/src/cgeo/geocaching/models/PersonalNote.java
UTF-8
3,081
2.015625
2
[]
no_license
// isComment package cgeo.geocaching.models; import org.apache.commons.lang3.StringUtils; public class isClassOrIsInterface { private static final String isVariable = "isStringConstant"; private String isVariable; private String isVariable; private boolean isVariable; private isConstructor() { // isComment } public isConstructor(final Geocache isParameter) { this.isFieldAccessExpr = isNameExpr.isMethod(); final String isVariable = isNameExpr.isMethod(); if (isNameExpr.isMethod(isNameExpr)) { return; } final String[] isVariable = isNameExpr.isMethod(isNameExpr, isNameExpr); if (isNameExpr.isFieldAccessExpr > isIntegerConstant) { this.isFieldAccessExpr = isNameExpr.isMethod(isNameExpr[isIntegerConstant]); this.isFieldAccessExpr = isNameExpr.isMethod(isNameExpr[isIntegerConstant]); } else { this.isFieldAccessExpr = isNameExpr.isMethod(isNameExpr[isIntegerConstant]); } } public final PersonalNote isMethod(final PersonalNote isParameter) { if (isNameExpr.isMethod(isNameExpr) && isNameExpr.isMethod(isNameExpr.isFieldAccessExpr)) { return isMethod(isNameExpr); } final PersonalNote isVariable = new PersonalNote(); if (isNameExpr.isFieldAccessExpr != null) { isNameExpr.isFieldAccessExpr = isNameExpr.isFieldAccessExpr; } else { isNameExpr.isFieldAccessExpr = isNameExpr; } if (isNameExpr != null) { isNameExpr.isFieldAccessExpr = isNameExpr; } else { isNameExpr.isFieldAccessExpr = isNameExpr.isFieldAccessExpr; } return isNameExpr; } /** * isComment */ private PersonalNote isMethod(final PersonalNote isParameter) { final PersonalNote isVariable = new PersonalNote(); if (isNameExpr.isMethod(isNameExpr.isFieldAccessExpr) && isNameExpr.isMethod(isNameExpr)) { // isComment if (isNameExpr.isMethod(isNameExpr.isFieldAccessExpr, isNameExpr)) { isNameExpr.isFieldAccessExpr = isNameExpr.isFieldAccessExpr; return isNameExpr; } if (isNameExpr.isFieldAccessExpr) { isNameExpr.isFieldAccessExpr = isNameExpr.isFieldAccessExpr; isNameExpr.isFieldAccessExpr = isNameExpr; } else { isNameExpr.isFieldAccessExpr = isNameExpr; isNameExpr.isFieldAccessExpr = isNameExpr.isFieldAccessExpr; } } return isNameExpr; } @Override public final String isMethod() { final StringBuilder isVariable = new StringBuilder(); if (isNameExpr != null) { isNameExpr.isMethod(isNameExpr).isMethod(isNameExpr); } isNameExpr.isMethod(isNameExpr); return isNameExpr.isMethod(); } final String isMethod() { return isNameExpr; } final String isMethod() { return isNameExpr; } }
true
c46619fb4c58dc1054352a09d5b289c7fb274c8e
Java
richardhendricks/ExtraUtilities
/com/rwtema/extrautils/item/scanner/ScannerRegistry.java
UTF-8
14,999
1.851563
2
[]
no_license
/* 1: */ package com.rwtema.extrautils.item.scanner; /* 2: */ /* 3: */ import cofh.api.energy.IEnergyHandler; /* 4: */ import com.rwtema.extrautils.helper.XUHelper.NBTIds; /* 5: */ import java.io.ByteArrayOutputStream; /* 6: */ import java.io.DataOutputStream; /* 7: */ import java.io.IOException; /* 8: */ import java.util.ArrayList; /* 9: */ import java.util.Collections; /* 10: */ import java.util.Comparator; /* 11: */ import java.util.List; /* 12: */ import java.util.Set; /* 13: */ import net.minecraft.entity.Entity; /* 14: */ import net.minecraft.entity.EntityLivingBase; /* 15: */ import net.minecraft.entity.player.EntityPlayer; /* 16: */ import net.minecraft.entity.player.PlayerCapabilities; /* 17: */ import net.minecraft.inventory.IInventory; /* 18: */ import net.minecraft.inventory.ISidedInventory; /* 19: */ import net.minecraft.nbt.CompressedStreamTools; /* 20: */ import net.minecraft.nbt.NBTBase; /* 21: */ import net.minecraft.nbt.NBTTagCompound; /* 22: */ import net.minecraft.nbt.NBTTagList; /* 23: */ import net.minecraft.tileentity.TileEntity; /* 24: */ import net.minecraftforge.common.IShearable; /* 25: */ import net.minecraftforge.common.util.ForgeDirection; /* 26: */ import net.minecraftforge.fluids.Fluid; /* 27: */ import net.minecraftforge.fluids.FluidStack; /* 28: */ import net.minecraftforge.fluids.FluidTankInfo; /* 29: */ import net.minecraftforge.fluids.IFluidHandler; /* 30: */ /* 31: */ public class ScannerRegistry /* 32: */ { /* 33: 29 */ public static List<IScanner> scanners = new ArrayList(); /* 34: 30 */ private static boolean isSorted = false; /* 35: */ /* 36: */ static /* 37: */ { /* 38: 33 */ addScanner(new scanTE()); /* 39: 34 */ addScanner(new scanEntity()); /* 40: 35 */ addScanner(new scanInv()); /* 41: 36 */ addScanner(new scanSidedInv()); /* 42: 37 */ addScanner(new scanTank()); /* 43: */ /* 44: */ /* 45: 40 */ addScanner(new scanTE3Power()); /* 46: */ } /* 47: */ /* 48: */ public static void addScanner(IScanner scan) /* 49: */ { /* 50: 45 */ scanners.add(scan); /* 51: 46 */ isSorted = false; /* 52: */ } /* 53: */ /* 54: */ public static void sort() /* 55: */ { /* 56: 50 */ Collections.sort(scanners, new SortScanners()); /* 57: 51 */ isSorted = true; /* 58: */ } /* 59: */ /* 60: */ public static List<String> getData(Object obj, ForgeDirection side, EntityPlayer player) /* 61: */ { /* 62: 55 */ List<String> data = new ArrayList(); /* 63: 57 */ if (!isSorted) { /* 64: 58 */ sort(); /* 65: */ } /* 66: 61 */ for (IScanner scan : scanners) { /* 67: 62 */ if (scan.getTargetClass().isAssignableFrom(obj.getClass())) { /* 68: 63 */ scan.addData(obj, data, side, player); /* 69: */ } /* 70: */ } /* 71: 66 */ return data; /* 72: */ } /* 73: */ /* 74: */ public static class SortScanners /* 75: */ implements Comparator<IScanner> /* 76: */ { /* 77: */ public int compare(IScanner arg0, IScanner arg1) /* 78: */ { /* 79: 72 */ int a = arg0.getPriority(); /* 80: 73 */ int b = arg1.getPriority(); /* 81: 75 */ if (a == b) { /* 82: 76 */ return 0; /* 83: */ } /* 84: 77 */ if (a < b) { /* 85: 78 */ return -1; /* 86: */ } /* 87: 80 */ return 1; /* 88: */ } /* 89: */ } /* 90: */ /* 91: */ public static class scanTE /* 92: */ implements IScanner /* 93: */ { /* 94: */ public Class getTargetClass() /* 95: */ { /* 96: 88 */ return TileEntity.class; /* 97: */ } /* 98: */ /* 99: */ public void addData(Object tile, List<String> data, ForgeDirection side, EntityPlayer player) /* 100: */ { /* 101: 93 */ NBTTagCompound tags = new NBTTagCompound(); /* 102: 94 */ ((TileEntity)tile).writeToNBT(tags); /* 103: 95 */ data.add("~~ " + tags.getString("id") + " ~~"); /* 104: */ /* 105: */ /* 106: 98 */ ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream(); /* 107: 99 */ DataOutputStream dataoutputstream = new DataOutputStream(bytearrayoutputstream); /* 108: */ try /* 109: */ { /* 110: */ try /* 111: */ { /* 112:103 */ CompressedStreamTools.write(tags, dataoutputstream); /* 113:104 */ data.add("Tile Data: " + bytearrayoutputstream.size()); /* 114: */ } /* 115: */ finally /* 116: */ { /* 117:106 */ dataoutputstream.close(); /* 118: */ } /* 119: */ } /* 120: */ catch (IOException ignored) {} /* 121:112 */ if (player.capabilities.isCreativeMode) { /* 122:113 */ data.addAll(getString(tags)); /* 123: */ } /* 124: */ } /* 125: */ /* 126: */ public List<String> getString(NBTTagCompound tag) /* 127: */ { /* 128:118 */ List<String> v = new ArrayList(); /* 129:119 */ appendStrings(v, tag, "", "Tags"); /* 130:120 */ return v; /* 131: */ } /* 132: */ /* 133: */ public void appendStrings(List<String> strings, NBTBase nbt, String prefix, String name) /* 134: */ { /* 135:124 */ if (nbt.getId() == XUHelper.NBTIds.NBT.id) /* 136: */ { /* 137:125 */ NBTTagCompound tag = (NBTTagCompound)nbt; /* 138:126 */ if (tag.func_150296_c().isEmpty()) /* 139: */ { /* 140:127 */ strings.add(prefix + name + " = NBT{}"); /* 141: */ } /* 142: */ else /* 143: */ { /* 144:129 */ strings.add(prefix + name + " = NBT{"); /* 145: */ /* 146:131 */ ArrayList<String> l = new ArrayList(); /* 147:132 */ l.addAll(tag.func_150296_c()); /* 148:133 */ Collections.sort(l); /* 149:134 */ for (String key : l) { /* 150:135 */ appendStrings(strings, tag.getTag(key), prefix + " ", key); /* 151: */ } /* 152:140 */ strings.add(prefix + "}"); /* 153: */ } /* 154: */ } /* 155:142 */ else if (nbt.getId() == XUHelper.NBTIds.List.id) /* 156: */ { /* 157:143 */ NBTTagList tag = (NBTTagList)nbt; /* 158:145 */ if (tag.tagCount() == 0) /* 159: */ { /* 160:146 */ strings.add(prefix + name + " = List{}"); /* 161: */ } /* 162: */ else /* 163: */ { /* 164:148 */ strings.add(prefix + name + " = List{"); /* 165:149 */ for (int i = 0; i < tag.tagCount(); i++) { /* 166:150 */ appendStrings(strings, tag.getCompoundTagAt(i), prefix + " ", i + ""); /* 167: */ } /* 168:156 */ strings.add(prefix + "}"); /* 169: */ } /* 170: */ } /* 171: */ else /* 172: */ { /* 173:159 */ strings.add(prefix + name + " = " + nbt.toString()); /* 174: */ } /* 175: */ } /* 176: */ /* 177: */ public int getPriority() /* 178: */ { /* 179:166 */ return -2147483647; /* 180: */ } /* 181: */ } /* 182: */ /* 183: */ public static class scanEntity /* 184: */ implements IScanner /* 185: */ { /* 186: */ public Class getTargetClass() /* 187: */ { /* 188:173 */ return Entity.class; /* 189: */ } /* 190: */ /* 191: */ public void addData(Object tile, List<String> data, ForgeDirection side, EntityPlayer player) /* 192: */ { /* 193:178 */ NBTTagCompound tags = new NBTTagCompound(); /* 194:180 */ if (((Entity)tile).writeToNBTOptional(tags)) /* 195: */ { /* 196:181 */ data.add("~~ " + tags.getString("id") + " ~~"); /* 197:182 */ data.add("Entity Data: " + tags.toString().length()); /* 198: */ } /* 199: */ } /* 200: */ /* 201: */ public int getPriority() /* 202: */ { /* 203:188 */ return -2147483648; /* 204: */ } /* 205: */ } /* 206: */ /* 207: */ public static class scanEntityLiv /* 208: */ implements IScanner /* 209: */ { /* 210: */ public Class getTargetClass() /* 211: */ { /* 212:195 */ return EntityLivingBase.class; /* 213: */ } /* 214: */ /* 215: */ public void addData(Object target, List<String> data, ForgeDirection side, EntityPlayer player) /* 216: */ { /* 217:200 */ EntityLivingBase e = (EntityLivingBase)target; /* 218:201 */ data.add(e.getHealth() + " / " + e.getMaxHealth()); /* 219: */ } /* 220: */ /* 221: */ public int getPriority() /* 222: */ { /* 223:206 */ return -110; /* 224: */ } /* 225: */ } /* 226: */ /* 227: */ public static class scanInv /* 228: */ implements IScanner /* 229: */ { /* 230: */ public Class getTargetClass() /* 231: */ { /* 232:213 */ return IInventory.class; /* 233: */ } /* 234: */ /* 235: */ public void addData(Object tile, List<String> data, ForgeDirection side, EntityPlayer player) /* 236: */ { /* 237:218 */ int n = ((IInventory)tile).getSizeInventory(); /* 238:220 */ if (n > 0) /* 239: */ { /* 240:221 */ int k = 0; /* 241:223 */ for (int i = 0; i < n; i++) { /* 242:224 */ if (((IInventory)tile).getStackInSlot(i) != null) { /* 243:225 */ k++; /* 244: */ } /* 245: */ } /* 246:228 */ data.add("Inventory Slots: " + k + " / " + n); /* 247: */ } /* 248: */ } /* 249: */ /* 250: */ public int getPriority() /* 251: */ { /* 252:234 */ return -100; /* 253: */ } /* 254: */ } /* 255: */ /* 256: */ public static class scanSidedInv /* 257: */ implements IScanner /* 258: */ { /* 259: */ public Class getTargetClass() /* 260: */ { /* 261:241 */ return ISidedInventory.class; /* 262: */ } /* 263: */ /* 264: */ public void addData(Object tile, List<String> data, ForgeDirection side, EntityPlayer player) /* 265: */ { /* 266:246 */ int[] slots = ((ISidedInventory)tile).getAccessibleSlotsFromSide(side.ordinal()); /* 267:247 */ int k = 0; /* 268:249 */ if (slots.length > 0) /* 269: */ { /* 270:250 */ for (int i = 0; i < slots.length; i++) { /* 271:251 */ if (((ISidedInventory)tile).getStackInSlot(i) != null) { /* 272:252 */ k++; /* 273: */ } /* 274: */ } /* 275:255 */ data.add("Inventory Side Slots: " + k + " / " + slots.length); /* 276: */ } /* 277: */ } /* 278: */ /* 279: */ public int getPriority() /* 280: */ { /* 281:261 */ return -99; /* 282: */ } /* 283: */ } /* 284: */ /* 285: */ public static class scanTank /* 286: */ implements IScanner /* 287: */ { /* 288: */ public Class getTargetClass() /* 289: */ { /* 290:268 */ return IFluidHandler.class; /* 291: */ } /* 292: */ /* 293: */ public void addData(Object tile, List<String> data, ForgeDirection side, EntityPlayer player) /* 294: */ { /* 295:273 */ FluidTankInfo[] tanks = ((IFluidHandler)tile).getTankInfo(side); /* 296:275 */ if (tanks != null) { /* 297:276 */ if (tanks.length == 1) /* 298: */ { /* 299:277 */ if ((tanks[0].fluid != null) && (tanks[0].fluid.amount > 0)) { /* 300:278 */ data.add("Fluid Tank: " + tanks[0].fluid.getFluid().getLocalizedName(tanks[0].fluid) + " - " + tanks[0].fluid.amount + " / " + tanks[0].capacity); /* 301: */ } else { /* 302:280 */ data.add("Fluid Tank: Empty - 0 / " + tanks[0].capacity); /* 303: */ } /* 304: */ } /* 305: */ else { /* 306:283 */ for (int i = 0; i < tanks.length; i++) { /* 307:284 */ if ((tanks[i].fluid != null) && (tanks[i].fluid.amount > 0)) { /* 308:285 */ data.add("Fluid Tank " + i + ": " + tanks[i].fluid.getFluid().getLocalizedName(tanks[i].fluid) + " - " + tanks[i].fluid.amount + " / " + tanks[i].capacity); /* 309: */ } else { /* 310:287 */ data.add("Fluid Tank " + i + ": Empty - 0 / " + tanks[i].capacity); /* 311: */ } /* 312: */ } /* 313: */ } /* 314: */ } /* 315: */ } /* 316: */ /* 317: */ public int getPriority() /* 318: */ { /* 319:296 */ return -98; /* 320: */ } /* 321: */ } /* 322: */ /* 323: */ public static class scanTE3Power /* 324: */ implements IScanner /* 325: */ { /* 326: */ public Class getTargetClass() /* 327: */ { /* 328:352 */ return IEnergyHandler.class; /* 329: */ } /* 330: */ /* 331: */ public void addData(Object tile, List<String> data, ForgeDirection side, EntityPlayer player) /* 332: */ { /* 333:357 */ IEnergyHandler a = (IEnergyHandler)tile; /* 334:358 */ data.add(" TE3 Side Energy: " + a.getEnergyStored(side) + " / " + a.getMaxEnergyStored(side)); /* 335: */ } /* 336: */ /* 337: */ public int getPriority() /* 338: */ { /* 339:363 */ return 0; /* 340: */ } /* 341: */ } /* 342: */ /* 343: */ public static class scanShears /* 344: */ implements IScanner /* 345: */ { /* 346: */ public Class getTargetClass() /* 347: */ { /* 348:389 */ return IShearable.class; /* 349: */ } /* 350: */ /* 351: */ public void addData(Object target, List<String> data, ForgeDirection side, EntityPlayer player) /* 352: */ { /* 353:394 */ IShearable a = (IShearable)target; /* 354:395 */ data.add("- Shearable"); /* 355: */ } /* 356: */ /* 357: */ public int getPriority() /* 358: */ { /* 359:400 */ return 0; /* 360: */ } /* 361: */ } /* 362: */ } /* Location: E:\TechnicPlatform\extrautilities\extrautilities-1.2.13.jar * Qualified Name: com.rwtema.extrautils.item.scanner.ScannerRegistry * JD-Core Version: 0.7.0.1 */
true
7211e7f45790db440da8dd62ef4c73e836ae1ec5
Java
reverseengineeringer/com.yelp.android
/src/com/google/android/gms/analytics/internal/aa$1.java
UTF-8
376
1.609375
2
[]
no_license
package com.google.android.gms.analytics.internal; import java.util.concurrent.Callable; class aa$1 implements Callable<String> { aa$1(aa paramaa) {} public String a() throws Exception { return a.d(); } } /* Location: * Qualified Name: com.google.android.gms.analytics.internal.aa.1 * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
bc7fea865fe2b2df7596163962a1a9f4cc10178c
Java
DoctorWhooves23/MLPClassPack
/src/com/ahui/classpack/interaction/PotionEffectModiy.java
UTF-8
1,557
2.46875
2
[]
no_license
package com.ahui.classpack.interaction; import java.util.HashMap; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.potion.PotionEffectType; import com.ahui.classpack.util.RelativeBlocks; public class PotionEffectModiy implements Listener { private HashMap<String, BlockFace> faces = new HashMap<String, BlockFace>(); @EventHandler public void speedMining(BlockBreakEvent e) { Player p = e.getPlayer(); BlockFace face = getBlockFaceByPlayerName(p.getName()); Block block = e.getBlock(); if(p.hasPotionEffect(PotionEffectType.FAST_DIGGING)) { if(p.isSneaking()) {return;} for(Block b: RelativeBlocks.getSurroundingBlocks(face, block)) { if(b.getType()!=Material.AIR) { b.breakNaturally(p.getInventory().getItemInMainHand()); } } } return; } @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void saveBlockFace(PlayerInteractEvent event) { Player player = event.getPlayer(); BlockFace bf = event.getBlockFace(); if (player != null && bf != null) { String name = player.getName(); faces.put(name, bf); } } public BlockFace getBlockFaceByPlayerName(String name) { return faces.get(name); } }
true
8008cdb90668ef621a94dbce9fd07452a731fcf7
Java
rv0-0/Practice_DSA
/Generic Tree/05. Height of tree.java
UTF-8
237
2.84375
3
[ "MIT" ]
permissive
public static int height(Node node) { int ht = -1; for(Node child: node.children) { int temp = height(child); ht = Math.max(temp,ht); } ht +=1; return ht; }
true
60c8e4235e65c20a8b9f5caa84a466eb9a1b028c
Java
Srammy/LocationService
/src/main/java/com/buaa/locationservice/dao/AuthDao.java
UTF-8
897
2.0625
2
[]
no_license
package com.buaa.locationservice.dao; import com.buaa.locationservice.model.Role; import com.buaa.locationservice.model.SecurityUserDetails; import com.buaa.locationservice.model.User; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; @Mapper //@Repository public interface AuthDao { /** * 根据用户名查找用户 * @param name * @return */ User findByUsername(@Param("name") String name); /** * 创建新用户 * @param user */ void insert(User user); /** * 创建用户角色 * @param userId * @param roleId * @return */ void insertRole(@Param("userId") long userId, @Param("roleId") long roleId); /** * 根据用户id查找该用户的角色 * @param userId * @return */ List<Role> findRoleByUserId(@Param("userId") long userId); }
true
1782f63eefaeca043db6ffb9c9afbb9c2334a966
Java
Yossitrx/JaveEE
/src/il/ac/shenkar/javaeeproject/model/ToDoListDAO.java
UTF-8
4,224
2.578125
3
[]
no_license
package il.ac.shenkar.javaeeproject.model; import java.util.Iterator; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.SessionFactory; public class ToDoListDAO implements IToDoListDao{ private static ToDoListDAO instance; private static SessionFactory factory = new AnnotationConfiguration() .configure() .addAnnotatedClass(Task.class) .addAnnotatedClass(User.class) .buildSessionFactory(); private ToDoListDAO() {} public static ToDoListDAO getInstance() { if (instance == null) { instance = new ToDoListDAO(); } return instance; } @Override public int addTask(int userID, String title, String taskBody) throws TasksPlatformException { Session session = factory.openSession(); Transaction tx = null; Integer id = null; try{ tx = session.beginTransaction(); Task task = new Task(); task.setUserId(userID); task.setTitle(title); task.setTaskBody(taskBody); id = (Integer) session.save(task); tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } return id; } @Override public void deleteTask(int userID, int taskID) throws TasksPlatformException { Session session = factory.openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); Task task = (Task)session.get(Task.class, taskID); if ( userID == task.getUserId()) { session.delete(task); tx.commit(); } }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } } @Override public void getTasks(int userId) throws TasksPlatformException { Session session = factory.openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); List<Task> tasks = session.createQuery("FROM " + Task.class.getName()).list(); for (Iterator iterator = tasks.iterator(); iterator.hasNext();){ Task task = (Task) iterator.next(); if( task.getUserId() == userId) { System.out.print("Task ID: " + task.getTaskId()); System.out.print(" Title: " + task.getTitle()); System.out.println(" Body: " + task.getTaskBody()); } } tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } } @Override public void updateTask(int userID, int taskID, String title, String taskBody) throws TasksPlatformException { Session session = factory.openSession(); Transaction tx = null; try{ tx = session.beginTransaction(); Task task = (Task)session.get(Task.class, taskID); if ( task.getUserId() == userID ) { task.setTitle(title); task.setTaskBody(taskBody); session.update(task); tx.commit(); } }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } } public int logIn(int userID, String mail, String password){ Session session = factory.openSession(); Transaction tx = null; Integer id = null; try{ tx = session.beginTransaction(); User user = new User(); user.setUserId(userID); user.setMail(mail); user.setPassword(password); id = (Integer) session.save(user); tx.commit(); }catch (HibernateException e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); } return id; } }
true
9c985bfd69cffb4c819b8d1d4bea793264d1c5a4
Java
xwwx000/repo1
/mud/src/main/java/com/xwwx/sewage/bean/TCommLog.java
UTF-8
1,108
1.875
2
[]
no_license
package com.xwwx.sewage.bean; public class TCommLog { private int id; private String userid; private String username; private String processtime; private String useripaddress; private int logtype; private String logdesc; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getProcesstime() { return processtime; } public void setProcesstime(String processtime) { this.processtime = processtime; } public String getUseripaddress() { return useripaddress; } public void setUseripaddress(String useripaddress) { this.useripaddress = useripaddress; } public int getLogtype() { return logtype; } public void setLogtype(int logtype) { this.logtype = logtype; } public String getLogdesc() { return logdesc; } public void setLogdesc(String logdesc) { this.logdesc = logdesc; } }
true
fc6307a9bdaddbcab44266847b188770fdb7e623
Java
Hirtol/AdventOfCode2019
/advent/day7/CombinationGenerator.java
UTF-8
666
2.828125
3
[]
no_license
package advent.day7; import advent.day7.generator.Itertools; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; public class CombinationGenerator { private List<List<Integer>> codesToUse; public CombinationGenerator(int from, int to){ this.codesToUse = new ArrayList<>(); Itertools.permutations(IntStream.range(from,to).boxed().collect(Collectors.toList()),5).forEach(p -> codesToUse.add(p)); } public int size(){ return codesToUse.size(); } public List<Integer> nextPhaseSettings(){ if(this.codesToUse.size() == 0) return null; return this.codesToUse.remove(0); } }
true
1d88c906d67018e6773295a411f22ad5fe4ff27b
Java
lliyu/collect
/src/main/java/com/site/collect/entity/Role.java
UTF-8
1,321
2.34375
2
[]
no_license
package com.site.collect.entity; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; @Table(name = "sys_role") public class Role implements Serializable { private static final long serialVersionUID = 1L; @Id private Long id; /** * 角色名称 */ private String name; /** * 角色类型 */ private Integer type; /** * 角色描述 */ private String description; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public static final String ID = "id"; public static final String NAME = "name"; public static final String TYPE = "type"; public static final String DESCRIPTION = "description"; @Override public String toString() { return "Role{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", type='" + type + '\'' + ", description='" + description + '\'' + '}'; } }
true
57316e1ae014a568fd659c59bc7ac3a96726139d
Java
liaohuijun/mumu-hbase
/src/main/java/com/lovecws/mumu/hbase/manager/HBaseClusterOperation.java
UTF-8
1,847
2.21875
2
[ "Apache-2.0" ]
permissive
package com.lovecws.mumu.hbase.manager; import com.lovecws.mumu.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.ClusterStatus; import org.apache.hadoop.hbase.RegionLoad; import org.apache.hadoop.hbase.ServerLoad; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.client.Admin; import org.apache.log4j.Logger; import java.io.IOException; import java.util.Collection; import java.util.Map; /** * @author babymm * @version 1.0-SNAPSHOT * @Description: hbase集群管理 * @date 2017-09-28 16:27 */ public class HBaseClusterOperation { private static final Logger log = Logger.getLogger(HBaseClusterOperation.class); private HBaseConfiguration hBaseConfiguration = new HBaseConfiguration(); /** * 获取集群状态 */ public void clusterStatus() { Admin admin = hBaseConfiguration.admin(); try { ClusterStatus clusterStatus = admin.getClusterStatus(); log.info(clusterStatus); log.info("servers count:" + clusterStatus.getServersSize()); Collection<ServerName> servers = clusterStatus.getServers(); for (ServerName serverName : servers) { log.info("region server:" + serverName); ServerLoad serverLoad = clusterStatus.getLoad(serverName); log.info("serverLoad:" + serverLoad); Map<byte[], RegionLoad> regionsLoad = serverLoad.getRegionsLoad(); for (final RegionLoad regionLoad : regionsLoad.values()) { log.info("regionLoad:" + regionLoad); } } log.info("region count:" + clusterStatus.getRegionsCount()); log.info("hbase version:" + clusterStatus.getHBaseVersion()); } catch (IOException e) { e.printStackTrace(); } } }
true
dbf735c432952765b8b271ba7f43360ba0d4ab81
Java
1802343117/ziying-api
/src/main/java/com/example/ziying/service/impl/CartoonInforServiceImpl.java
UTF-8
955
1.929688
2
[]
no_license
package com.example.ziying.service.impl; import com.example.ziying.common.ResponseResult; import com.example.ziying.domain.entity.CartoonInfor; import com.example.ziying.mapper.CartoonInforMapper; import com.example.ziying.service.CartoonInforService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; /** * <p> * 服务实现类 * </p> * * @author Tunl * @since 2021-04-19 */ @Service public class CartoonInforServiceImpl extends ServiceImpl<CartoonInforMapper, CartoonInfor> implements CartoonInforService { @Resource private CartoonInforMapper cartoonInforMapper; @Override public ResponseResult cartoonInforList() { List<CartoonInfor> cartoonInforList = cartoonInforMapper.selectCartoonInfor(); return ResponseResult.success(cartoonInforList); } }
true
f961b96f63cdf8e6093d603a8ac687c58bfea274
Java
joergreichert/spray
/plugins/org.eclipselabs.spray.shapes/src/org/eclipselabs/spray/shapes/formatting/ShapeFormatter.java
UTF-8
7,634
2.03125
2
[]
no_license
/* * generated by Xtext */ package org.eclipselabs.spray.shapes.formatting; import java.util.ArrayList; import java.util.List; import org.eclipse.xtext.Keyword; import org.eclipse.xtext.formatting.impl.AbstractDeclarativeFormatter; import org.eclipse.xtext.formatting.impl.FormattingConfig; import org.eclipse.xtext.util.Pair; import org.eclipselabs.spray.shapes.services.ShapeGrammarAccess; import javax.inject.Inject; /** * This class contains custom formatting description. * see : http://www.eclipse.org/Xtext/documentation/latest/xtext.html#formatting * on how and when to use it * Also see {@link org.eclipse.xtext.xtext.XtextFormattingTokenSerializer} as an * example */ public class ShapeFormatter extends AbstractDeclarativeFormatter { @Inject private ShapeGrammarAccess grammar; @Override protected void configureFormatting(FormattingConfig c) { c.setLinewrap(0, 1, 2).before(grammar.getSL_COMMENTRule()); c.setLinewrap(0, 1, 2).before(grammar.getML_COMMENTRule()); c.setLinewrap(0, 1, 1).after(grammar.getML_COMMENTRule()); c.setAutoLinewrap(120); handleBlocks(c); List<Keyword> bracketsToIgnore = new ArrayList<Keyword>(); bracketsToIgnore.add(grammar.getHighlightingValuesAccess().getLeftParenthesisKeyword_1()); bracketsToIgnore.add(grammar.getCompartmentInfoAccess().getLeftParenthesisKeyword_1()); bracketsToIgnore.add(grammar.getCompartmentInfoAccess().getLeftParenthesisKeyword_2_1_1()); for (Pair<Keyword, Keyword> kw : grammar.findKeywordPairs("(", ")")) { if(!bracketsToIgnore.contains(kw.getFirst())) { c.setSpace(" ").before(kw.getFirst()); c.setNoSpace().after(kw.getFirst()); c.setNoSpace().before(kw.getSecond()); } } // no space around =, except for text value assignment for (Keyword kw : grammar.findKeywords("=")) { if (kw == grammar.getTextBodyAccess().getEqualsSignKeyword_2()) { c.setSpace(" ").around(kw); } else { c.setNoSpace().around(kw); } } c.setSpace(" ").around(grammar.getCompartmentInfoAccess().getEqualsSignKeyword_2_0_1()); List<Keyword> commasToIgnore = new ArrayList<Keyword>(); commasToIgnore.add(grammar.getCompartmentInfoAccess().getCommaKeyword_2_1_5()); // no space befor comma, one space after for (Keyword kw : grammar.findKeywords(",")) { if(!commasToIgnore.contains(kw)) { c.setNoSpace().before(kw); c.setSpace(" ").after(kw); } } c.setNoSpace().before(grammar.getCompartmentInfoAccess().getCommaKeyword_2_1_5()); c.setLinewrap().after(grammar.getCompartmentInfoAccess().getCommaKeyword_2_1_5()); handleNoSpaceBeforeINT(c); handleLineWrapBeforeKeywords(c); c.setLinewrap(2).between(grammar.getShapeDefinitionRule(), grammar.getShapeDefinitionRule()); c.setLinewrap(2).between(grammar.getConnectionDefinitionRule(), grammar.getConnectionDefinitionRule()); c.setLinewrap(2).between(grammar.getConnectionDefinitionRule(), grammar.getShapeDefinitionRule()); c.setLinewrap(2).between(grammar.getShapeDefinitionRule(), grammar.getConnectionDefinitionRule()); c.setIndentation( grammar.getCompartmentInfoAccess().getLeftParenthesisKeyword_1(), grammar.getCompartmentInfoAccess().getRightParenthesisKeyword_3() ); c.setLinewrap().after(grammar.getCompartmentInfoAccess().getLeftParenthesisKeyword_1()); c.setLinewrap().around(grammar.getCompartmentInfoAccess().getRightParenthesisKeyword_3()); c.setLinewrap().after(grammar.getHighlightingValuesAccess().getLeftParenthesisKeyword_1()); c.setLinewrap().around(grammar.getHighlightingValuesAccess().getRightParenthesisKeyword_6()); c.setLinewrap().around(grammar.getHighlightingValuesAccess().getSelectedAssignment_2_2()); c.setLinewrap().around(grammar.getHighlightingValuesAccess().getMultiselectedAssignment_3_2()); c.setLinewrap().around(grammar.getHighlightingValuesAccess().getAllowedAssignment_4_2()); c.setLinewrap().around(grammar.getHighlightingValuesAccess().getUnallowedAssignment_5_2()); c.setIndentation( grammar.getHighlightingValuesAccess().getLeftParenthesisKeyword_1(), grammar.getHighlightingValuesAccess().getRightParenthesisKeyword_6() ); c.setLinewrap().after(grammar.getCompartmentInfoAccess().getLeftParenthesisKeyword_2_1_1()); c.setLinewrap().around(grammar.getCompartmentInfoAccess().getRightParenthesisKeyword_2_1_9()); c.setLinewrap().around(grammar.getCompartmentInfoAccess().getStretchHAssignment_2_1_4()); c.setLinewrap().around(grammar.getCompartmentInfoAccess().getStretchVAssignment_2_1_8()); c.setIndentation( grammar.getCompartmentInfoAccess().getLeftParenthesisKeyword_2_1_1(), grammar.getCompartmentInfoAccess().getRightParenthesisKeyword_2_1_9() ); c.setLinewrap().around(grammar.getCommonLayoutRule()); } protected void handleLineWrapBeforeKeywords(FormattingConfig c) { // line wraps c.setLinewrap().before(grammar.getShapeRule()); c.setLinewrap().before(grammar.getShapeConnectionRule()); c.setLinewrap().before(grammar.getPointRule()); c.setLinewrap().before(grammar.getPlacingDefinitionAccess().getPlacingKeyword_0()); c.setLinewrap().before(grammar.getAnchorPositionRule()); c.setLinewrap().before(grammar.getCommonLayoutAccess().getPositionKeyword_1_0_0()); c.setLinewrap().before(grammar.getCommonLayoutAccess().getSizeKeyword_1_1_0()); c.setLinewrap().before(grammar.getRoundedRectangleLayoutAccess().getCurveKeyword_1_1_0()); c.setLinewrap().before(grammar.getTextLayoutAccess().getAlignKeyword_1_1_0()); c.setLinewrap().before(grammar.getTextBodyAccess().getIdKeyword_1()); c.setLinewrap().before(grammar.getShapestyleLayoutAccess().getStyleKeyword_1_0()); for (Keyword kw : grammar.findKeywords("line", "ellipse", "rectangle", "rounded-rectangle", "polyline", "polygon", "text", "description", "align", "id", "compartment", "layout", "invisible", "stretching", "margin", "spacing", "vertical")) { c.setLinewrap().before(kw); } c.setLinewrap().before(grammar.getCDTextRule()); } protected void handleNoSpaceBeforeINT(FormattingConfig c) { // no space before integers c.setNoSpace().before(grammar.getCommonLayoutAccess().getXcorN_INTParserRuleCall_1_0_4_0()); c.setNoSpace().before(grammar.getCommonLayoutAccess().getYcorN_INTParserRuleCall_1_0_8_0()); c.setNoSpace().before(grammar.getPointAccess().getXcorN_INTParserRuleCall_1_4_0()); c.setNoSpace().before(grammar.getPointAccess().getYcorN_INTParserRuleCall_1_8_0()); c.setNoSpace().before(grammar.getAnchorFixPointPositionAccess().getXcorINTTerminalRuleCall_2_0()); c.setNoSpace().before(grammar.getAnchorFixPointPositionAccess().getYcorINTTerminalRuleCall_6_0()); } protected void handleBlocks(FormattingConfig c) { for (Pair<Keyword, Keyword> kw : grammar.findKeywordPairs("{", "}")) { c.setLinewrap().after(kw.getFirst()); c.setLinewrap().around(kw.getSecond()); c.setIndentation(kw.getFirst(), kw.getSecond()); } } }
true
9556d4d711fe884fa60a7ab8dd20ba0a69eba423
Java
evertonsouzam/batecontacloud
/src/main/java/br/com/everton/bateconta/batecontacloud/repository/UsuarioRepository.java
UTF-8
399
1.875
2
[]
no_license
package br.com.everton.bateconta.batecontacloud.repository; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import br.com.everton.bateconta.batecontacloud.model.Usuario; @Repository public interface UsuarioRepository extends MongoRepository<Usuario, String>{ List<Usuario> findByNome(String nome); }
true
fc361cfcb1e427e7923c4697b2f81a5abd006db4
Java
avanderw/creature
/src/main/java/net/avdw/creature/tail/Tails.java
UTF-8
572
2.5
2
[]
no_license
package net.avdw.creature.tail; import com.google.inject.Inject; import com.google.inject.name.Named; import org.apache.commons.text.WordUtils; import java.util.List; public class Tails { public List<Tail> tails; public String description; @Inject Tails(List<Tail> tails) { this.tails = tails; } @Inject public void setDescription(@Named("tails.description") String description) { this.description = description; } public String uncapitalize(String string) { return WordUtils.uncapitalize(string); } }
true
fb6c0dfc72b2a2eb4991270cca438dd48cb11029
Java
enaawy/gproject
/gp_JADX/com/google/android/wallet/ui/common/C6796x.java
UTF-8
2,943
1.945313
2
[]
no_license
package com.google.android.wallet.ui.common; import android.text.TextUtils; import android.widget.TextView; import com.google.a.a.a.a.a.b.d; import com.google.android.wallet.p383e.C6625i; import com.google.android.wallet.ui.common.p402c.C6739a; import java.util.GregorianCalendar; import java.util.TimeZone; public final class C6796x extends C6739a { public static final TimeZone f33703a = TimeZone.getTimeZone("UTC"); public final DateEditText f33704b; public final GregorianCalendar f33705c; public final GregorianCalendar f33706d; public C6796x(DateEditText dateEditText, d dVar, d dVar2) { this.f33704b = dateEditText; this.f33705c = new GregorianCalendar(dVar.a, dVar.b - 1, 1); this.f33705c.setTimeZone(f33703a); this.f33705c.setLenient(false); try { this.f33705c.getTime(); this.f33706d = new GregorianCalendar(dVar2.a, dVar2.b - 1, 1); this.f33706d.setTimeZone(f33703a); this.f33706d.setLenient(false); try { this.f33706d.getTime(); } catch (Throwable e) { throw new IllegalArgumentException("Invalid maximum date, check the date component order?", e); } } catch (Throwable e2) { throw new IllegalArgumentException("Invalid minimum date, check the date component order?", e2); } } protected final boolean mo5632a(TextView textView) { if (TextUtils.isEmpty(textView.getText())) { return true; } boolean z; int month = this.f33704b.getMonth(); int year = this.f33704b.getYear(); if (month <= 0 || month > 12) { z = true; } else if (year == 0) { z = true; } else { GregorianCalendar gregorianCalendar = new GregorianCalendar(year, month - 1, 1); gregorianCalendar.setTimeZone(f33703a); if (gregorianCalendar.compareTo(this.f33705c) < 0) { z = true; } else if (gregorianCalendar.compareTo(this.f33706d) > 0) { z = true; } else { z = false; } } switch (z) { case true: this.i = this.f33704b.getContext().getString(C6625i.wallet_uic_error_expired_credit_card); return false; case false: this.i = null; return true; case true: this.i = this.f33704b.getContext().getString(C6625i.wallet_uic_error_year_invalid); return false; case true: this.i = this.f33704b.getContext().getString(C6625i.wallet_uic_error_month_invalid); return false; default: this.i = this.f33704b.getContext().getString(C6625i.wallet_uic_error_year_must_not_be_empty); return false; } } }
true
289735c959fba33f1da91a9ad90aefff94d1e0fb
Java
leoterry-ulrica/xiaozhi
/dcm-model/src/main/java/com/dist/bdf/model/dto/system/user/UserBasicDTO.java
UTF-8
2,445
2.34375
2
[]
no_license
package com.dist.bdf.model.dto.system.user; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.dist.bdf.common.constants.DomainType; import com.dist.bdf.model.dto.system.OrgRolesDTO; import com.dist.bdf.model.entity.system.DcmOrganization; import com.dist.bdf.model.entity.system.DcmRole; /** * 用户dto * @author weifj * @version 1.0,2016/01/12,创建机构dto * @version 1.1,2016/01/20,添加获取用户编码 * @version 1.2,2016/01/27,删除属性state * @version 1.3,2016/04/16,去掉机构相关属性 */ public class UserBasicDTO extends UserSimpleDTO { /** * */ private static final long serialVersionUID = 1L; /** * 邮件 */ private String email; /** * 移动电话 */ private String telephone; /** * 创建时间 */ private Date dateCreated; /** * 座机电话 */ private String phone; /** * qq联系方式 */ private String qq; /** * 获取空间域类型编码 * @return */ public String getDomainType(){ return DomainType.PERSON; } private List<OrgRolesDTO> orgRoles; /** * @return the email */ public String getEmail() { return email; } /** * @param email the email to set */ public void setEmail(String email) { this.email = email; } /** * @return the telephone */ public String getTelephone() { return telephone; } /** * @param telephone the telephone to set */ public void setTelephone(String telephone) { this.telephone = telephone; } /** * @return the dateCreated */ public Date getDateCreated() { return dateCreated; } /** * @param dateCreated the dateCreated to set */ public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } public List<OrgRolesDTO> getOrgRoles() { return orgRoles; } public void setOrgRoles(List<OrgRolesDTO> orgRoles) { this.orgRoles = orgRoles; } public synchronized void addOrgAndRoles(DcmOrganization org, List<DcmRole> roles){ if(null == orgRoles){ orgRoles = new ArrayList<OrgRolesDTO>(); } OrgRolesDTO dto = new OrgRolesDTO(); dto.setOrg(org); dto.setRoles(roles); orgRoles.add(dto); } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } }
true
ec185506a5acd5d1a72fb5787df9b6ff5bb9afa3
Java
yonghuayu/NetworkComponents
/src/com/winonetech/jhpplugins/utils/ICEUtil.java
UTF-8
357
1.671875
2
[ "MIT" ]
permissive
package com.winonetech.jhpplugins.utils; import com.winone.dhmp.rpc.service.terminalManage.TerminalServicePrx; public final class ICEUtil { /** * * @return 获取 新的一个TerminalServicePrx */ public static TerminalServicePrx geTerminalServicePrx() { return (TerminalServicePrx) RpcClientUtil.getServicePrx(TerminalServicePrx.class); } }
true
aac5a72b4adbc282dbfae454310f7df196dde7b0
Java
colinem/java-inside
/labthreeb/src/main/java/fr.umlv.javainside.labthreeb/fr/umlv/javainside/labthreeb/Main.java
UTF-8
182
1.5625
2
[]
no_license
package fr.umlv.javainside.labthreeb; public class Main { public static void main(String[] args) { System.out.println("Hello Pro !"); HelloConciseMethod.main(args); } }
true
679c7fe1a81a064ceec058c4522e73c7f1d5cc78
Java
peng267/spike
/src/main/java/com/cyf/spike/rabbitmq/MQSender.java
UTF-8
1,453
2.09375
2
[]
no_license
package com.cyf.spike.rabbitmq; import com.cyf.spike.Constants.PrefixContant; import com.cyf.spike.vo.SeckillMessage; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.amqp.core.ExchangeTypes; import org.springframework.amqp.rabbit.annotation.Exchange; import org.springframework.amqp.rabbit.annotation.Queue; import org.springframework.amqp.rabbit.annotation.QueueBinding; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @Author chenyuanfu * @Date 2020/9/2 17:14 **/ @Service @Slf4j public class MQSender { private static ObjectMapper objectMapper = new ObjectMapper(); @Autowired private AmqpTemplate amqpTemplate; public void sendMessage(SeckillMessage seckillMessage){ String messageStr = ""; try { messageStr = objectMapper.writeValueAsString(seckillMessage); log.info("send message: {}", messageStr); amqpTemplate.convertAndSend(PrefixContant.SECKILL_GOODS_KEY_PREFIX + "stock.decr",messageStr); } catch (JsonProcessingException e) { log.info("ObjectMapper: bean covert to String is fail"); e.printStackTrace(); } } }
true
ff58d2861a223689ed11b62448d7b765657370e5
Java
mscyan/leetcode
/src/graph/Graph_DST.java
UTF-8
2,533
3.484375
3
[]
no_license
package graph; import java.util.ArrayList; import java.util.List; /** * 深度优先搜索 depth first search */ public class Graph_DST { private Node node; private int time; private List<Node> nodes_G = new ArrayList<>(); private boolean hasBackEdge = false; public Graph_DST(){ } public void addNode(Node node){ nodes_G.add(node); } /** * 深度优先搜索 */ public void printAll(){ for(Node v : nodes_G){ v.color = Color.WHITE; v.parent = null; } time = 0; for(Node v : nodes_G){ if(v.color == Color.WHITE){ DFS(v); } else{ // System.out.println("Node had been visited, value is : " + v.val); } // System.out.println(time); } } private void DFS(Node u){ time = time + 1; u.d = time; u.color = Color.GRAY; // System.out.print(" (" + u.val); for(Node v : u.neighbors){ if(v.color == Color.WHITE){ v.parent = u; DFS(v); } } u.color = Color.BLACK; time = time + 1; u.f = time; // System.out.print(u.val + ") "); // System.out.println(u.val); } public static void main(String[] args){ Node node1 = new Node(); Node node2 = new Node(); Node node3 = new Node(); Node node4 = new Node(); Node node5 = new Node(); Node node6 = new Node(); node1.val = 1; node2.val = 2; node3.val = 3; node4.val = 4; node5.val = 5; node6.val = 6; node1.neighbors.add(node2); node1.neighbors.add(node3); node1.neighbors.add(node4); node2.neighbors.add(node1); node2.neighbors.add(node3); node2.neighbors.add(node4); node3.neighbors.add(node1); node3.neighbors.add(node2); node3.neighbors.add(node4); node4.neighbors.add(node1); node4.neighbors.add(node2); node4.neighbors.add(node3); node5.neighbors.add(node6); node6.neighbors.add(node5); Graph_DST graph_dst = new Graph_DST(); graph_dst.addNode(node1); graph_dst.addNode(node2); graph_dst.addNode(node3); graph_dst.addNode(node4); graph_dst.addNode(node5); graph_dst.addNode(node6); graph_dst.printAll(); System.out.println(); } }
true
007b14e8feff9fd861c864fda1567492fbbc6e7d
Java
jmad/jmad-core
/src/java/cern/accsoft/steering/jmad/modeldefs/io/impl/JMadModelDefinitionExporterImpl.java
UTF-8
12,566
1.882813
2
[ "Apache-2.0" ]
permissive
// @formatter:off /******************************************************************************* * * This file is part of JMad. * * Copyright (c) 2008-2011, CERN. All rights reserved. * * 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. * ******************************************************************************/ // @formatter:on /** * */ package cern.accsoft.steering.jmad.modeldefs.io.impl; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cern.accsoft.steering.jmad.domain.file.ModelFile; import cern.accsoft.steering.jmad.domain.machine.SequenceDefinition; import cern.accsoft.steering.jmad.domain.machine.SequenceDefinitionImpl; import cern.accsoft.steering.jmad.modeldefs.domain.JMadModelDefinition; import cern.accsoft.steering.jmad.modeldefs.domain.JMadModelDefinitionImpl; import cern.accsoft.steering.jmad.modeldefs.io.JMadModelDefinitionExportRequest; import cern.accsoft.steering.jmad.modeldefs.io.JMadModelDefinitionExporter; import cern.accsoft.steering.jmad.modeldefs.io.ModelDefinitionPersistenceService; import cern.accsoft.steering.jmad.modeldefs.io.ModelFileFinder; import cern.accsoft.steering.jmad.modeldefs.io.ModelFileFinderManager; import cern.accsoft.steering.jmad.util.FileUtil; import cern.accsoft.steering.jmad.util.StreamUtil; import cern.accsoft.steering.jmad.util.xml.PersistenceServiceException; /** * This is the default implementation of the {@link JMadModelDefinitionExporter} * * @author Kajetan Fuchsberger (kajetan.fuchsberger at cern.ch) */ public class JMadModelDefinitionExporterImpl implements JMadModelDefinitionExporter { /** * The persistence service to use to write model definition to xml. (injected by * spring) */ private List<ModelDefinitionPersistenceService> persistenceServices = new ArrayList<ModelDefinitionPersistenceService>(); /** * The class which keeps track of file finders for the model definitions. */ private ModelFileFinderManager fileFinderManager; /** The logger for the class */ private static final Logger LOGGER = LoggerFactory.getLogger(JMadModelDefinitionExporterImpl.class); @Override public File export(JMadModelDefinitionExportRequest exportRequest, File exportPath) { if (exportRequest == null) { LOGGER.error("No model definition given to export."); return null; } if (exportPath == null) { LOGGER.error("No file given. Cannot export model definition."); return null; } ModelDefinitionPersistenceService persistenceService = findPersistenceService(exportPath.getName()); if (persistenceService != null || exportPath.isDirectory()) { return exportAsFiles(exportRequest, exportPath); } else { /* per default we export as zip */ return exportAsZip(exportRequest, exportPath); } } @Override public File exportAsFiles(JMadModelDefinitionExportRequest exportRequest, File exportPath) { if (exportRequest == null) { LOGGER.error("No model definition given to export."); return null; } if (exportPath == null) { LOGGER.error("No destination dir given. Cannot export model definition."); return null; } JMadModelDefinition modelDefinition = tailorModelDefinition(exportRequest); File xmlFile; File destDir; if (exportPath.isDirectory()) { destDir = exportPath; /* per default we save as xml */ xmlFile = new File(destDir.getAbsolutePath() + File.separator + getFileName(modelDefinition)); } else { destDir = exportPath.getAbsoluteFile().getParentFile(); xmlFile = exportPath; } FileUtil.createDir(destDir, false); /* * first we save the model-def file. If it matches one of the extensions of the * persisters, then we use that one, otherwise we use the default. */ ModelDefinitionPersistenceService persistenceService = findPersistenceService(xmlFile.getAbsolutePath()); if (persistenceService == null) { xmlFile = new File(xmlFile.getAbsolutePath() + ModelDefinitionUtil.getDefaultFileExtension()); persistenceService = findPersistenceService(xmlFile.getAbsolutePath()); } if (persistenceService == null) { LOGGER.error("Cannot find appropriate persistence service for file '" + xmlFile.getAbsolutePath() + "'."); } try { persistenceService.save(modelDefinition, xmlFile); /* * then we loop through all model files and copy all the files. */ ModelFileFinder fileFinder = getFileFinderManager().getModelFileFinder(modelDefinition); for (ModelFile modelFile : getRequiredFiles(modelDefinition)) { /* * We use the archive path here. So the file structure is the same as inside the * zip archive. */ String archivePath = fileFinder.getArchivePath(modelFile); File file = new File(destDir.getAbsolutePath() + File.separator + archivePath); /* * ensure that the parent dir exists */ FileUtil.createDir(file.getAbsoluteFile().getParentFile(), false); InputStream inStream = fileFinder.getStream(modelFile); if (!StreamUtil.toFile(inStream, file)) { LOGGER.error("Could not write file '" + file.getAbsolutePath() + "'"); return null; } } return xmlFile; } catch (PersistenceServiceException e) { LOGGER.error("Could not save model definition to file '" + xmlFile.getAbsolutePath() + "'.", e); } return null; } private ModelDefinitionPersistenceService findPersistenceService(String fileName) { for (ModelDefinitionPersistenceService persistenceService : getPersistenceServices()) { if (persistenceService.isCorrectFileName(fileName)) { return persistenceService; } } return null; } @Override public File exportAsZip(JMadModelDefinitionExportRequest exportRequest, File file) { if (exportRequest == null) { LOGGER.error("No model definition given to export."); return null; } if (file == null) { LOGGER.error("No file given. Cannot export model definition."); return null; } JMadModelDefinition modelDefinition = tailorModelDefinition(exportRequest); File zipFile = ModelDefinitionUtil.ensureZipFileExtension(file); try { /* Create the output stream */ ZipOutputStream outStream; outStream = new ZipOutputStream(new FileOutputStream(zipFile)); String baseName = ModelDefinitionUtil.getProposedIdStringFromName(modelDefinition); /* Add a zip entry to the output stream each persister we have */ for (ModelDefinitionPersistenceService persistenceService : getPersistenceServices()) { outStream.putNextEntry(new ZipEntry(baseName + persistenceService.getFileExtension())); persistenceService.save(modelDefinition, outStream); outStream.closeEntry(); } /* * next we need the corresponding ModelFileFinder to find all the required files * and put them in the archive. */ ModelFileFinder fileFinder = getFileFinderManager().getModelFileFinder(modelDefinition); /* * now we are ready to copy all the files into the archive. */ for (ModelFile modelFile : getRequiredFiles(modelDefinition)) { outStream.putNextEntry(new ZipEntry(fileFinder.getArchivePath(modelFile))); InputStream inStream = fileFinder.getStream(modelFile); StreamUtil.copy(inStream, outStream); outStream.closeEntry(); inStream.close(); } outStream.close(); return zipFile; } catch (IOException e) { LOGGER.error("Could not save model definition to zip file '" + zipFile.getAbsolutePath() + "'", e); } catch (PersistenceServiceException e) { LOGGER.error("Could not save model definition to zip file '" + zipFile.getAbsolutePath() + "'", e); } return null; } private JMadModelDefinition tailorModelDefinition(JMadModelDefinitionExportRequest request) { JMadModelDefinition modelDefinitionForExport = cloneModel(request.getModelDefinition()); /* remove optics/sequences/ranges not selected */ modelDefinitionForExport.getOpticsDefinitions().removeIf(o -> !(request.getOpticsToExport().contains(o))); modelDefinitionForExport.getSequenceDefinitions().removeIf(s -> !(request.getSequencesToExport().contains(s))); modelDefinitionForExport.getSequenceDefinitions().forEach(// seq -> seq.getRangeDefinitions().removeIf(r -> !(request.getRangesToExport().contains(r)))); /* remove empty sequences (no ranges) */ modelDefinitionForExport.getSequenceDefinitions().removeIf(s -> s.getRangeDefinitions().isEmpty()); /* if we end up with an empty model, throw */ if (modelDefinitionForExport.getOpticsDefinitions().isEmpty()) { throw new IllegalArgumentException("no optics definitions have been selected for export!"); } if (modelDefinitionForExport.getSequenceDefinitions().isEmpty()) { throw new IllegalArgumentException("no sequence definitions have been selected for export!"); } if (modelDefinitionForExport.getRangeDefinitions().isEmpty()) { throw new IllegalArgumentException("no ranges have been selected for export!"); } /* fix defaults */ if (!modelDefinitionForExport.getOpticsDefinitions() .contains(modelDefinitionForExport.getDefaultOpticsDefinition())) { ((JMadModelDefinitionImpl) modelDefinitionForExport) .setDefaultOpticsDefinition(modelDefinitionForExport.getOpticsDefinitions().get(0)); } if (!modelDefinitionForExport.getSequenceDefinitions() .contains(modelDefinitionForExport.getDefaultSequenceDefinition())) { ((JMadModelDefinitionImpl) modelDefinitionForExport) .setDefaultSequenceDefinition(modelDefinitionForExport.getSequenceDefinitions().get(0)); } for (SequenceDefinition sequence : modelDefinitionForExport.getSequenceDefinitions()) { if (!sequence.getRangeDefinitions().contains(sequence.getDefaultRangeDefinition())) { ((SequenceDefinitionImpl) sequence).setDefaultRangeDefinition(sequence.getRangeDefinitions().get(0)); } } return modelDefinitionForExport; } private JMadModelDefinition cloneModel(JMadModelDefinition model) { for (ModelDefinitionPersistenceService cloneService : persistenceServices) { try { return cloneService.clone(model); } catch (Exception e) { /* try next service */ } } throw new IllegalStateException("no persistence service was able to clone the model definition"); } private String getFileName(JMadModelDefinition modelDefinition) { if ((modelDefinition.getSourceInformation() != null) && (modelDefinition.getSourceInformation().getFileName() != null)) { return modelDefinition.getSourceInformation().getFileName(); } return ModelDefinitionUtil.getProposedDefaultFileName(modelDefinition); } /** * collects all the required files for a model definition. it returns a * collection which will contain all the model files with the same archive path * only once. * * @param modelDefinition * the model definition for which to collect the files * @return all the files, with unique archive-path */ private Collection<ModelFile> getRequiredFiles(JMadModelDefinition modelDefinition) { ModelFileFinder fileFinder = getFileFinderManager().getModelFileFinder(modelDefinition); Map<String, ModelFile> modelFiles = new HashMap<String, ModelFile>(); for (ModelFile modelFile : ModelDefinitionUtil.getRequiredModelFiles(modelDefinition)) { String archivePath = fileFinder.getArchivePath(modelFile); modelFiles.put(archivePath, modelFile); } return modelFiles.values(); } public void setFileFinderManager(ModelFileFinderManager fileFinderManager) { this.fileFinderManager = fileFinderManager; } private ModelFileFinderManager getFileFinderManager() { return fileFinderManager; } public void setPersistenceServices(List<ModelDefinitionPersistenceService> persistenceServices) { this.persistenceServices = persistenceServices; } private List<ModelDefinitionPersistenceService> getPersistenceServices() { return persistenceServices; } }
true
3c07cddc70a7f16d503a97d6c266f5c98d897c90
Java
kkiruban/CSharpProjects
/webdriver/Testng/zzz/src/SucessedProgramsforinterview/Evennoprogram2.java
UTF-8
212
2.4375
2
[]
no_license
package SucessedProgramsforinterview; public class Evennoprogram2 { public static void main(String[] args){ int sum=10; for(sum=10;sum<=100;sum=sum+2){ System.out.println(sum); } } }
true
9a554f04c89f05a2d73dc428ac96c8a0b5484458
Java
sitelabs/easyweb
/com.alibaba.app.eclipse.easyweb/src/com/alibaba/app/eclipse/easyweb/util/AppUtils.java
GB18030
12,510
1.8125
2
[]
no_license
/* * Copyright 1999-2004 Alibaba.com All right reserved. This software is the confidential and proprietary information of * Alibaba.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only * in accordance with the terms of the license agreement you entered into with Alibaba.com. */ package com.alibaba.app.eclipse.easyweb.util; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.maven.model.Dependency; import org.apache.maven.model.Model; import org.apache.maven.model.Parent; import org.apache.maven.model.Plugin; import org.apache.maven.model.io.DefaultModelReader; import org.apache.maven.model.io.ModelParseException; import org.apache.maven.model.io.ModelReader; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaModelException; import com.alibaba.app.eclipse.easyweb.model.App; import com.alibaba.app.eclipse.easyweb.model.AppJsonObject; /** * MavenUtils.javaʵTODO ʵ * * @author yingjun.jiaoyj@alibaba-inc.com 2011-1-16 04:51:48 */ public class AppUtils { private static Map<String, App> pomApps = new HashMap(); private static Map<String, IJavaProject> pomPrjs = new HashMap(); public static final String POM_EXTENTS = "pom.xml"; public static final String BUNDLEWAR = "bundle.war"; private static ModelReader reader = new DefaultModelReader(); private static Map<String, Model> models; private static Map<String, IJavaProject> namePrjs; public static Map<String, App> init(List<App> apps) throws Exception { models = new HashMap<String, Model>(); pomPrjs = new HashMap<String, IJavaProject>(); namePrjs = new HashMap(); Map<String, AppJsonObject> appObjs = EclipseUtils.getAppProps(); List<IJavaProject> prjs = EclipseUtils.getAllJavaProjects(false); List<IJavaProject> warPrjs = new ArrayList<IJavaProject>(); List<String> webPaths = new ArrayList<String>(); for (IJavaProject prj : prjs) { // ҵweb-infĿ¼,web-infĿ¼Ϊweb namePrjs.put(prj.getElementName(), prj); if (prj.getElementName().indexOf(BUNDLEWAR) != -1) { String webinfPath = FileUtil.findWebInfPath(prj.getResource().getLocation().toString()); if (webinfPath != null && !"".equals(webinfPath)) { warPrjs.add(prj); webPaths.add(webinfPath); } } String pomPath = prj.getResource().getLocation().toString(); pomPath = pomPath.replaceAll("\\\\", "/"); pomPath += "/" + POM_EXTENTS; File pomFile = new File(pomPath); if (pomFile.exists()) { Model model = null; try { model = reader.read(pomFile, null); } catch (Exception e) { } if (model == null) { continue; } pomPrjs.put(model.getArtifactId(), prj); models.put(prj.getElementName(), model); } } for (int i = 0; i < warPrjs.size(); i++) { IJavaProject prj = warPrjs.get(i); String webinf = webPaths.get(i); Model model = models.get(prj.getElementName()); if (model != null) { String curPath = getAppPath(model);// model.getPomFile().getParent(); Model pmodel = null; try { pmodel = reader.read(new File(curPath), null); curPath = pmodel.getPomFile().getParent(); curPath = curPath.replaceAll("\\\\", "/"); } catch (FileNotFoundException e) { // continue; pmodel = model; } App app = new App(); app.setWarPomModel(model); app.setWebinf(webinf); app.setName(pmodel.getArtifactId()); String appPath = pmodel.getPomFile().getParent(); appPath = appPath.replaceAll("\\\\", "/"); app.setPath(appPath); app.setWarPrj(prj); wrapRerJar(prj, app); List<String> modules = pmodel.getModules(); for (String string : modules) { String path = curPath + "/" + string + "/" + POM_EXTENTS; Model cmodel = reader.read(new File(path), null); IJavaProject _prj = pomPrjs.get(cmodel.getArtifactId()); if (_prj == null) { continue; } app.addPrj(_prj); if (_prj.getElementName().indexOf(".deploy") != -1) { app.setDeployPrj(_prj); } // wrapRef(_prj, app); if (_prj.getElementName().indexOf(BUNDLEWAR) != -1 || cmodel.getPackaging().equals("jar")) { // System.out.println(pmodel.getVersion() + " " + cmodel.getParent().getVersion()); continue; } List<Plugin> plugins = null; try { plugins = cmodel.getBuild().getPlugins(); } catch (Exception e) { continue; } // ȡcar for (Plugin plugin : plugins) { if (plugin.getArtifactId().equals("maven-car-plugin")) { Object container = plugin.getConfiguration(); if (container != null) { if (container instanceof Xpp3Dom) { try { Xpp3Dom dom = (Xpp3Dom) container; Xpp3Dom webroot = dom.getChild("webrootDirectory"); if (webroot != null) { String value = webroot.getValue().replaceAll("\\$\\{basedir\\}", curPath + "/" + string); app.addCarPrj(cmodel.getName(), value); } } catch (Exception e) { } } } break; } } } AppJsonObject obj = appObjs.get(app.getName()); if (obj != null) { app.format(obj); } if (!apps.contains(app)) { apps.add(app); pomApps.put(pmodel.getArtifactId(), app); } } } return pomApps; } public static void wrapRerJar(IJavaProject prj, App app) { IClasspathEntry[] cls; try { cls = prj.getRawClasspath(); } catch (JavaModelException e) { return; } for (IClasspathEntry entry : cls) { String path = entry.getPath().toString(); String[] refs = path.split("/"); path = refs[refs.length - 1]; if (path.endsWith(".jar")) { path = path.substring(0, path.lastIndexOf(".jar")); } IJavaProject _prj = namePrjs.get(path); if (_prj != null) { app.addPrj(_prj); } } } private static void wrapRef(IJavaProject prj, App app) { String path = prj.getResource().getLocation() + File.separator + POM_EXTENTS; Model model = null; try { model = reader.read(new File(path), null); String curPath = getAppPath(model);// model.getPomFile().getParent(); Model pmodel = null; try { pmodel = reader.read(new File(curPath), null); List<Dependency> pdependencys = pmodel.getDependencies(); for (Dependency dependency : pdependencys) { String artifactId = dependency.getArtifactId(); if (!pmodel.getArtifactId().equals(artifactId)) { IJavaProject _prj = pomPrjs.get(artifactId); if (_prj != null) { app.addPrj(_prj); wrapRef(_prj, app); } } } } catch (FileNotFoundException e) { } List<Dependency> dependencys = model.getDependencies(); for (Dependency dependency : dependencys) { String artifactId = dependency.getArtifactId(); if (!model.getArtifactId().equals(artifactId)) { IJavaProject _prj = pomPrjs.get(artifactId); if (_prj != null) { app.addPrj(_prj); wrapRef(_prj, app); } } } } catch (FileNotFoundException e) { } catch (ModelParseException e) { } catch (IOException e) { } catch (Exception e) { } } /** * mavenģͣҳpom· * * @param model * @return * @throws Exception */ public static String getAppPath(Model model) throws Exception { String pomPath = model.getPomFile().getAbsolutePath(); String curLocation = pomPath.replaceAll(POM_EXTENTS, ""); File file = new File(curLocation); Parent parent = model.getParent(); String path = ""; if (parent != null) { String relativePath = model.getParent().getRelativePath(); int index = relativePath.indexOf("../"); int begin = 3; while (index != -1) { file = file.getParentFile(); if (file == null || !file.canRead()) { path = null; break; } path = file.getAbsolutePath(); path += File.separator + relativePath.substring(index + 3); index = relativePath.indexOf("../", begin); begin += index; } } return path; } /** * pomľ·ӦõĶpomwebinfPath˵web̵Ӧ * * @param pomPath * @param webinfPath * @throws Exception */ public static void getAppPath(String pomPath) throws Exception { String curLocation = pomPath.replaceAll(POM_EXTENTS, ""); Model model = reader.read(new File(pomPath), null); File file = new File(curLocation); Parent parent = model.getParent(); if (parent != null) { String relativePath = model.getParent().getRelativePath(); String path = ""; int index = relativePath.indexOf("../"); int begin = 3; while (index != -1) { file = file.getParentFile(); if (file == null || !file.canRead()) { path = null; break; } path = file.getAbsolutePath(); path += File.separator + relativePath.substring(index + 3); index = relativePath.indexOf("../", begin); begin += index; } if (new File(path).canRead()) { getAppPath(path); } else { models.put(model.getArtifactId(), model); } } } }
true
158875363c4eae0e4b4692181ab65611b340b27e
Java
woyaowoyao/xcloud-server
/src/main/java/com/xxx/xcloud/module/ceph/repository/CephFileRepository.java
UTF-8
3,556
2.15625
2
[]
no_license
package com.xxx.xcloud.module.ceph.repository; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.xxx.xcloud.module.ceph.entity.CephFile; /** * * <p> * Description: 文件存储持久层接口 * </p> * * @author wangkebiao * @date 2019年10月30日 */ @Repository public interface CephFileRepository extends CrudRepository<CephFile, String> { /**根据文件名称和租户名称查找文件存储 * @Title: findByNameAndTenantName * @Description: 根据文件名称和租户名称查找文件存储 * @param name 文件名称 * @param tenantName 租户名称 * @return CephFile * @throws */ CephFile findByNameAndTenantName(String name, String tenantName); /**根据文件名称和租户名称分页查找文件存储 * @Title: findByTenantNameAndName * @Description: 根据文件名称和租户名称分页查找文件存储 * @param tenantName 租户名称 * @param name 文件名称 * @param pageable * @return Page<CephFile> * @throws */ @Query("select s from CephFile s where s.name like ?2% and s.tenantName =?1") Page<CephFile> findByTenantNameAndName(String tenantName, String name, Pageable pageable); /**根据文件名称、租户名称和项目信息分页查找文件存储 * @Title: findByTenantNameAndNameAndProjectId * @Description: 根据文件名称、租户名称和项目信息分页查找文件存储 * @param tenantName 租户名称 * @param name 文件名称 * @param projectId 项目信息 * @param pageable * @return Page<CephFile> * @throws */ @Query("select s from CephFile s where s.name like ?2% and s.tenantName =?1 and s.projectId=?3") Page<CephFile> findByTenantNameAndNameAndProjectId(String tenantName, String name, String projectId, Pageable pageable); /**根据租户名称分页查找文件存储 * @Title: findByTenantName * @Description: 根据租户名称分页查找文件存储 * @param tenantName 租户名称 * @param pageable * @return Page<CephFile> * @throws */ Page<CephFile> findByTenantName(String tenantName, Pageable pageable); /**根据租户名称和项目信息分页查找文件存储 * @Title: findByTenantNameAndProjectId * @Description: 根据租户名称和项目信息分页查找文件存储 * @param tenantName 租户名称 * @param projectId 项目信息 * @param pageable * @return Page<CephFile> * @throws */ Page<CephFile> findByTenantNameAndProjectId(String tenantName, String projectId, Pageable pageable); /**根据租户名称查找文件存储 * @Title: findByTenantName * @Description: 根据租户名称查找文件存储 * @param tenantName 租户名称 * @return List<CephFile> * @throws */ List<CephFile> findByTenantName(String tenantName); /**根据租户名称删除文件存储 * @Title: deleteByTenantName * @Description: 根据租户名称删除文件存储 * @param tenantName void * @throws */ void deleteByTenantName(String tenantName); }
true
bac88ea2f77e49fa35815a80dd5abdcd96884291
Java
ceh522/w12-day4-FantasyallDayLab
/src/main/java/players/casters/Wizard.java
UTF-8
489
2.90625
3
[]
no_license
package players.casters; import items.AttackingItem; import players.Player; public class Wizard extends Caster { public Wizard(int healthPoints, String name, int attackRating, int defenceRating) { super(healthPoints, name, attackRating, defenceRating); } public void attack(Player opposingPlayer) { super.attack(opposingPlayer); } public String levitate(int distance) { return "The wizard has levitated by " + distance + " metres"; } }
true
1ae25e13f43f5e3022d98a0acbb594ba8ad18527
Java
Bulkinho/3U-Assignment03
/src/A3Q2.java
UTF-8
3,000
2.984375
3
[]
no_license
import becker.robots.City; import becker.robots.Direction; import becker.robots.Robot; import becker.robots.Wall; import becker.robots.Thing; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author bulka4927 */ public class A3Q2 { /** * @param args the command line arguments */ public static void main(String[] args) { //new city City mc = new City(); //place robot Robot bul = new Robot(mc, 0, 0, Direction.EAST); // TODO code application logic here //create wall new Wall(mc, 0, 0, Direction.NORTH); new Wall(mc, 0, 1, Direction.NORTH); new Wall(mc, 0, 2, Direction.NORTH); new Wall(mc, 0, 3, Direction.NORTH); new Wall(mc, 0, 3, Direction.EAST); new Wall(mc, 1, 3, Direction.EAST); new Wall(mc, 2, 3, Direction.EAST); new Wall(mc, 2, 3, Direction.SOUTH); new Wall(mc, 2, 2, Direction.SOUTH); new Wall(mc, 2, 1, Direction.SOUTH); new Wall(mc, 2, 0, Direction.SOUTH); new Wall(mc, 0, 0, Direction.WEST); new Wall(mc, 1, 0, Direction.WEST); new Wall(mc, 2, 0, Direction.WEST); //create things new Thing(mc, 0, 1); new Thing(mc, 1, 1); new Thing(mc, 1, 2); new Thing(mc, 1, 3); new Thing(mc, 2, 3); new Thing(mc, 2, 0); //street sweeper while (bul.frontIsClear()) { bul.move(); bul.pickThing(); bul.turnLeft(); bul.turnLeft(); bul.turnLeft(); bul.move(); bul.pickThing(); bul.turnLeft(); bul.move(); bul.pickThing(); bul.move(); bul.pickThing(); if (!bul.frontIsClear()) { bul.turnLeft(); bul.turnLeft(); bul.turnLeft(); bul.move(); bul.pickThing(); if (!bul.frontIsClear()) { bul.turnLeft(); bul.turnLeft(); bul.turnLeft(); bul.move(); bul.move(); bul.move(); bul.pickThing(); bul.turnLeft(); bul.turnLeft(); bul.turnLeft(); if (bul.getDirection() == Direction.NORTH) { bul.move(); bul.move(); if (bul.getStreet() == 0 && bul.getAvenue() == 0) { bul.turnLeft(); bul.turnLeft(); bul.turnLeft(); break; } } } } } } }
true
9b5223c585bd204701a846ebfab55d4e4b240ddf
Java
AbdelrahmanRagab38/Restaurant-Menu-app
/app/src/main/java/com/example/dell/foodapp/DrinkActivity.java
UTF-8
920
2.328125
2
[]
no_license
package com.example.dell.foodapp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView; public class DrinkActivity extends AppCompatActivity { public static final String Extra_DrinkNo="drinkno"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drink); int drinkno= (Integer) getIntent().getExtras().get(Extra_DrinkNo); Drink drink = Drink.ourDrink[drinkno]; TextView name =(TextView) findViewById(R.id.name1); TextView desc =(TextView) findViewById(R.id.desc1); ImageView drinkimage =(ImageView) findViewById(R.id.drinkimage); name.setText(drink.getName()); desc.setText(drink.getDescription()); drinkimage.setImageResource(drink.getImageId()); } }
true
120c119dee2dc29d7a7b659db81099460fefbb90
Java
kevincwu0515/morse
/src/morse/MorseServer.java
UTF-8
5,187
3.40625
3
[ "MIT" ]
permissive
package morse; import java.io.IOException; import static morse.MorseConstant.morseLetters; import static morse.MorseConstant.morseNumbers; import java.net.ServerSocket; import java.net.Socket; import java.util.Formatter; import java.util.Scanner; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * @class MorseServer * @author Kevin Wu * @date April 01 2016 */ public class MorseServer { private Client[] clients; private ServerSocket server; private ExecutorService runGame; private Lock morseLock; private Condition otherClientConnected; // set up Morse server public MorseServer() { clients = new Client[2]; // create array with two clients // create ExecutorService with a thread for each client runGame = Executors.newFixedThreadPool(2); morseLock = new ReentrantLock(); // create lock // condition variable for both clients being connected otherClientConnected = morseLock.newCondition(); try { server = new ServerSocket(MorseConstant.SERVER_PORT, 2); // set up ServerSocket } catch (IOException ioException) { ioException.printStackTrace(); System.exit(1); } } // wait for two connections so communication can be started public void execute() { // wait for each client to connect for (int i = 0; i < clients.length; i++) { try { clients[i] = new Client(server.accept(), i); runGame.execute(clients[i]); // execute client runnable } catch (IOException ioException) { ioException.printStackTrace(); System.exit(1); } } morseLock.lock(); // lock application to signal second client // first client was suspended to wait for second client try { otherClientConnected.signal(); // signal first client } finally { morseLock.unlock(); // unlock after signalling first client } } public void translate(String phrase, int clientNumber) { morseLock.lock(); // lock so only one client can proceed try { String morseCode = ""; // initialize Morse code of phrase // loop through the string for (int i = 0; i < phrase.length(); i++) { char alpha = phrase.charAt(i); // if the character is a number, access the number array if (Character.isDigit(alpha)) { morseCode += morseNumbers[alpha - '0'] + " "; } // if the character is a letter, access the letter array if (Character.isLetter(alpha)) { morseCode += morseLetters[Character.toUpperCase(alpha) - 'A'] + " "; } // if the character is a space, output two extra spaces if (alpha == ' ') { morseCode += " "; } } // let other client know the morseCode if (clientNumber == 0) { clients[1].showMorseCode(morseCode); } else { clients[0].showMorseCode(morseCode); } } finally { morseLock.unlock(); // unlock application to let other client go } } private class Client implements Runnable { private Socket connection; private Scanner input; private Formatter output; private int clientID; // set up client public Client(Socket socket, int number) { clientID = number; // store number connection = socket; // store socket try { // obtain i/o stream input = new Scanner(connection.getInputStream()); output = new Formatter(connection.getOutputStream()); } catch (IOException ioException) { ioException.printStackTrace(); System.exit(1); } } // send message containing other client's phrase public void showMorseCode(String morseCode) { output.format("%s\n", morseCode); // send Morse-code message output.flush(); } // control thread's execution public void run() { // if client 0, wait for another client to connect if (clientID == 0) { morseLock.lock(); // lock to wait for second client try { otherClientConnected.await(); // wait for client 1 } catch (InterruptedException exception) { exception.printStackTrace(); } finally { morseLock.unlock(); // unlock after second client } } while (true) { if (input.hasNextLine()) { translate(input.nextLine(), clientID); // translate } } } } }
true
de24245417512d25c5adeba3e0d34611f94ae269
Java
pedrocoquito/GustinEvento
/WebGustinReunioes/src/java/br/evento/dao/GenericsDao.java
UTF-8
1,031
2.1875
2
[ "MIT" ]
permissive
package br.evento.dao; import java.sql.SQLException; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public abstract class GenericsDao<C, K> { protected EntityManager conexao; private EntityManagerFactory emf; public GenericsDao() { emf = Persistence.createEntityManagerFactory("WebGustinReunioesPU"); conexao = emf.createEntityManager(); } public EntityManager getConexao() { return conexao; } public void close(){ conexao.close(); emf.close(); } public abstract void save(C obj) throws SQLException; public abstract void edit(C obj) throws SQLException; public abstract void delete(C obj) throws SQLException; public abstract List<C> findAll()throws SQLException; public abstract C findOne(K key)throws SQLException; public abstract long count()throws SQLException; }
true
38a788bdecfb7498afccb1435f0e0da68ba1273b
Java
hiepnhse61627/CapstoneProject
/04.Source/CapstoneMVC/src/main/java/com/capstone/services/StudentStatusServiceImpl.java
UTF-8
1,926
2.5
2
[]
no_license
package com.capstone.services; import com.capstone.entities.StudentStatusEntity; import com.capstone.jpa.exJpa.ExStudentStatusEntityJpaController; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import java.util.List; public class StudentStatusServiceImpl implements IStudentStatusService { private EntityManagerFactory emf = Persistence.createEntityManagerFactory("CapstonePersistence"); private ExStudentStatusEntityJpaController studentStatusEntityJpaController = new ExStudentStatusEntityJpaController(emf); @Override public void createStudentStatus(StudentStatusEntity entity) { try { studentStatusEntityJpaController.create(entity); } catch (Exception e) { e.printStackTrace(); } } @Override public List<StudentStatusEntity> getStudentStatusForStudentArrangement(int semesterId, List<String> statusList) { return studentStatusEntityJpaController.getStudentStatusForStudentArrangement(semesterId, statusList); } @Override public StudentStatusEntity getStudentStatusBySemesterIdAndStudentId(Integer semesterId, Integer studentId) { return studentStatusEntityJpaController.getStudentStatusBySemesterIdAndStudentId(semesterId, studentId); } @Override public void updateStudentStatus(StudentStatusEntity entity) { try { studentStatusEntityJpaController.edit(entity); } catch (Exception e) { e.printStackTrace(); } } @Override public List<StudentStatusEntity> getStudentStatusBySemesterId(Integer semesterId) { return studentStatusEntityJpaController.getStudentStatusBySemesterId(semesterId); } @Override public List<StudentStatusEntity> getStudentStatusesByStudentId(int studentId) { return studentStatusEntityJpaController.getStudentStatusesByStudentId(studentId); } }
true
f5c21573d09838e21a95a3295f0ea37c96070716
Java
pierfrancescoran/starterInMemoryProject
/src/main/java/com/peter/controller/RestControllersProduction.java
UTF-8
3,501
2.078125
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.peter.controller; import com.peter.bl.AppBL; import com.peter.jwt.AuthorizationLogic; import com.peter.jwt.JWTConfigurer; import com.peter.model.httpbody.AbstractMessage; import com.peter.model.httpbody.LoginVM; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Profile; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; /** * * @author peter */ @CrossOrigin(origins={"https://www.peter.com"}, allowedHeaders={"Content-Type", "Accept","Authorization"}, exposedHeaders={"Authorization"}, methods={RequestMethod.DELETE,RequestMethod.GET,RequestMethod.OPTIONS,RequestMethod.POST}, allowCredentials="false", maxAge = 4800) @RestController @Profile({"production", "default"}) @ComponentScan("com.peter.bl") @ComponentScan("com.peter.jwt") public class RestControllersProduction { @Autowired private AuthorizationLogic authorizationLogic; @Autowired private AppBL mobileBL; @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public String handleAllException(Exception ex) { return "There was a problem with your request"; } private void badRequestSender(BindingResult result) throws Exception{ if (result.hasErrors()) { throw new Exception(); } } @PostMapping("/authenticate") public void authorize(@Valid @RequestBody LoginVM loginVM, BindingResult result, HttpServletResponse response) throws Exception { if (result.hasErrors()) { badRequestSender(result); return; } try{ String jwt = authorizationLogic.authorize(loginVM); response.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer " + jwt); ResponseEntity.ok(); } catch(Exception e){ response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage()); } } @RequestMapping(value = "/appFired", method = RequestMethod.GET) public @ResponseBody AbstractMessage getVersion(HttpServletResponse response,@RequestParam(value = "appVersion", required = true) String appVersion) throws IOException, Exception { try { return mobileBL.doSomething(appVersion); } catch (Exception dae) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } return null; } }
true
9039213ad7771d67ecd51d676dc16d26f15d552b
Java
AjayJain10/MyApplication
/app/src/main/java/com/example/ajayj/myapplication/util/LoginDetails.java
UTF-8
1,267
2.34375
2
[]
no_license
package com.example.ajayj.myapplication.util; import android.content.Context; /** * Created by ajayj on 28-06-2017. */ public class LoginDetails { public static void storeUserDetails(Context context,String user){ context.getSharedPreferences("IsLoginusr",context.MODE_PRIVATE).edit().putString("username",user).apply(); } public static String isUser(Context context) { return context.getSharedPreferences("IsLoginusr",Context.MODE_PRIVATE).getString("username",null); } public static void storePasswordDetails(Context context,String pwd){ context.getSharedPreferences("IsLoginpwd",context.MODE_PRIVATE).edit().putString("password",pwd).apply(); } public static String isPwd(Context context) { return context.getSharedPreferences("IsLoginpwd",Context.MODE_PRIVATE).getString("password",null); } public static void storeRemindmeDetails(Context context,boolean isChecked) { context.getSharedPreferences("IsLoginRmd",context.MODE_PRIVATE).edit().putBoolean("remindme",isChecked).apply(); } public static boolean isChecked(Context context) { return context.getSharedPreferences("IsLoginRmd",Context.MODE_PRIVATE).getBoolean("remindme",false); } }
true
989c760da227a9775865481087a12b0ff655c2e2
Java
aeris170/16Games
/src/puzzlefifteen/Assets.java
UTF-8
722
2.59375
3
[ "MIT" ]
permissive
package puzzlefifteen; import java.awt.Rectangle; import java.io.IOException; import com.doa.engine.graphics.DoaSprites; public final class Assets { private Assets() {} public static void initializeAssets(int i) { try { for (int yy = 0; yy < Puzzle15.GRID_Y; yy++) { for (int xx = 0; xx < Puzzle15.GRID_X; xx++) if (i == 0) { DoaSprites.createSpriteFromSpriteSheet("" + (yy * Puzzle15.GRID_X + xx), "/puzzle15/bg.png", new Rectangle(xx * 128, yy * 128, 128, 128)); } else { DoaSprites.createSpriteFromSpriteSheet("" + (yy * Puzzle15.GRID_X + xx), "/puzzle15/15.png", new Rectangle(xx * 64, yy * 64, 64, 64)); } } } catch (IOException ex) { ex.printStackTrace(); } } }
true
f59e478a7a6f94b73c8e3a452556abe8ec35060e
Java
lryxxh/Study
/Test/io/io/BufferReadTest.java
UTF-8
1,329
2.9375
3
[]
no_license
package io; import java.io.IOException; public class BufferReadTest { /** * @param args */ public static void main(String[] args) { try { Runtime.getRuntime().exec("javaws -uninstall"); Runtime.getRuntime().exec("javaws -import -silent http://192.168.200.231/picbrowser.jnlp"); } catch (IOException e) { e.printStackTrace(); } System.out.println("123"); // String a = "abc"; // String b = "abc"; // String c = new String("abc"); // String d = new String("abc"); // System.out.println((a == b) + " " +( c == d) ); // HashMap<Integer, String> map = new HashMap<Integer, String>(); // map.put(1, a); // map.put(2, b); // System.out.println(map.get(1) == map.get(2)); // ByteBuffer buffer = ByteBuffer.allocate(25); // System.out.println(buffer); // buffer.putInt(24);//4 // System.out.println(buffer); // buffer.putDouble(123.4);//8 // System.out.println(buffer); // buffer.putLong(23l);//8 // System.out.println(buffer); // buffer.put((byte)1);//1 // System.out.println(buffer); // buffer.putFloat(123.4f);//4 // System.out.println(buffer); // buffer.flip(); // System.out.println(buffer.getInt()); // System.out.println(buffer.getDouble()); // System.out.println(buffer.getLong()); // System.out.println(buffer.get()); // System.out.println(buffer.getFloat()); } }
true
1a511524d1544d33fb0ba0dc6bc977440e152a3d
Java
bjpo/work
/src/com/hrbsys/kqxxbjxx/service/impl/KQXX_BJXXServiceImpl.java
UTF-8
40,129
1.984375
2
[]
no_license
package com.hrbsys.kqxxbjxx.service.impl; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.hrbsys.base.dao.BaseDao; import com.hrbsys.bean.KQXX_BJXX; import com.hrbsys.bean.XUEQI; import com.hrbsys.kqxxbjxx.service.KQXX_BJXXService; import com.hrbsys.tools.BaseChangeTool; public class KQXX_BJXXServiceImpl implements KQXX_BJXXService { private BaseDao baseDao; public BaseDao getBaseDao() { return baseDao; } public void setBaseDao(BaseDao baseDao) { this.baseDao = baseDao; } //add @Override public boolean addKQXX_BJXX(KQXX_BJXX y) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // y.setDJRQ(df.format(new Date()).toString()); // y.setXGRQ(df.format(new Date()).toString()); return baseDao.save(y); } //delete @Override public boolean delKQXX_BJXX(String y) { String[] ids = y.split(","); for (String id : ids) {KQXX_BJXX yhz=findKQXX_BJXX(id); if (!baseDao.delete(yhz)) { return false; } } return true; } //update @Override public boolean updateKQXX_BJXX(KQXX_BJXX t) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); KQXX_BJXX tmpt = baseDao.findAll("from KQXX_BJXX where KQXX_BJXX_ID='" + t.getKQXX_BJXX_ID() + "'",KQXX_BJXX.class).get(0); tmpt.setCQL(t.getCQL()); tmpt.setZTRS(t.getZTRS()); tmpt.setKCMC(t.getKCMC()); tmpt.setZCCXRS(t.getZCCXRS()); tmpt.setQXL(t.getQXL()); tmpt.setKCB_ID(t.getKCB_ID()); tmpt.setLS_ID(t.getLS_ID()); tmpt.setZHOU(t.getZHOU()); tmpt.setKESHI_ID(t.getKESHI_ID()); tmpt.setMS(t.getMS()); tmpt.setSKSJ(t.getSKSJ()); tmpt.setBZ(t.getBZ()); tmpt.setLSXM(t.getLSXM()); tmpt.setCDL(t.getCDL()); tmpt.setXINGQI(t.getXINGQI()); tmpt.setSJSKRS(t.getSJSKRS()); tmpt.setKCLB(t.getKCLB()); tmpt.setJSMC(t.getJSMC()); tmpt.setCDRS(t.getCDRS()); tmpt.setKCB_FKS_ID(t.getKCB_FKS_ID()); tmpt.setZTL(t.getZTL()); tmpt.setKSMC(t.getKSMC()); tmpt.setLSGH(t.getLSGH()); tmpt.setQXRS(t.getQXRS()); tmpt.setYSKRS(t.getYSKRS()); tmpt.setJS_ID(t.getJS_ID()); // tmpt.setXGRQ(df.format(new Date()).toString()); return baseDao.update(tmpt); } //findById @Override public KQXX_BJXX findKQXX_BJXX(String t_id) { return baseDao.findAll("from KQXX_BJXX where KQXX_BJXX_ID='" + t_id + "'",KQXX_BJXX.class).get(0); } //findByPage @Override public List<KQXX_BJXX> findKQXX_BJXXByPageApp(int start, int number,HashMap<String, String> params, String order, String sort) { String hql = "from KQXX_BJXX where 1=1 "; String param = ""; ArrayList<String> params2 = new ArrayList<String>(); if (null != params.get("KCMC") && !"".equals(params.get("KCMC"))) { param = "and KCMC like '%" + params.get("KCMC").toString() + "%'"; params2.add(param); param=""; } if (null != params.get("KCB_ID") && !"".equals(params.get("KCB_ID"))) { param = "and KCB_ID like '%" + params.get("KCB_ID").toString() + "%'"; params2.add(param); param=""; } if (null != params.get("LS_ID") && !"".equals(params.get("LS_ID"))) { param = "and LS_ID like '%" + params.get("LS_ID").toString() + "%'"; params2.add(param); param=""; } if (null != params.get("ZHOU") && !"".equals(params.get("ZHOU"))) { param = "and ZHOU like '%" + params.get("ZHOU").toString() + "%'"; params2.add(param); param=""; } if (null != params.get("KESHI_ID") && !"".equals(params.get("KESHI_ID"))) { param = "and KESHI_ID like '%" + params.get("KESHI_ID").toString() + "%'"; params2.add(param); param=""; } if (null != params.get("MS") && !"".equals(params.get("MS"))) { param = "and MS like '%" + params.get("MS").toString() + "%'"; params2.add(param); param=""; } if (null != params.get("SKSJ") && !"".equals(params.get("SKSJ"))) { param = "and SKSJ like '%" + params.get("SKSJ").toString() + "%'"; params2.add(param); param=""; } if (null != params.get("BZ") && !"".equals(params.get("BZ"))) { param = "and BZ like '%" + params.get("BZ").toString() + "%'"; params2.add(param); param=""; } if (null != params.get("LSXM") && !"".equals(params.get("LSXM"))) { param = "and LSXM like '%" + params.get("LSXM").toString() + "%'"; params2.add(param); param=""; } if (null != params.get("XINGQI") && !"".equals(params.get("XINGQI"))) { param = "and XINGQI like '%" + params.get("XINGQI").toString() + "%'"; params2.add(param); param=""; } if (null != params.get("KCLB") && !"".equals(params.get("KCLB"))) { param = "and KCLB like '%" + params.get("KCLB").toString() + "%'"; params2.add(param); param=""; } if (null != params.get("JSMC") && !"".equals(params.get("JSMC"))) { param = "and JSMC like '%" + params.get("JSMC").toString() + "%'"; params2.add(param); param=""; } if (null != params.get("KCB_FKS_ID") && !"".equals(params.get("KCB_FKS_ID"))) { param = "and KCB_FKS_ID like '%" + params.get("KCB_FKS_ID").toString() + "%'"; params2.add(param); param=""; } if (null != params.get("KSMC") && !"".equals(params.get("KSMC"))) { param = "and KSMC like '%" + params.get("KSMC").toString() + "%'"; params2.add(param); param=""; } if (null != params.get("LSGH") && !"".equals(params.get("LSGH"))) { param = "and LSGH like '%" + params.get("LSGH").toString() + "%'"; params2.add(param); param=""; } if (null != params.get("JS_ID") && !"".equals(params.get("JS_ID"))) { param = "and JS_ID like '%" + params.get("JS_ID").toString() + "%'"; params2.add(param); param=""; } List<KQXX_BJXX> list = baseDao.findByPage(hql, KQXX_BJXX.class, start, number, params2, order, sort); return list; } //getCount @Override public int getCountKQXX_BJXX(HashMap<String, String> params) { String hql = "SELECT COUNT(*) from KQXX_BJXX where 1=1 "; if (null != params.get("KCMC") && !"".equals(params.get("KCMC"))) { hql += "and KCMC like '%" + params.get("KCMC").toString() + "%'"; } if (null != params.get("KCB_ID") && !"".equals(params.get("KCB_ID"))) { hql += "and KCB_ID like '%" + params.get("KCB_ID").toString() + "%'"; } if (null != params.get("LS_ID") && !"".equals(params.get("LS_ID"))) { hql += "and LS_ID like '%" + params.get("LS_ID").toString() + "%'"; } if (null != params.get("ZHOU") && !"".equals(params.get("ZHOU"))) { hql += "and ZHOU like '%" + params.get("ZHOU").toString() + "%'"; } if (null != params.get("KESHI_ID") && !"".equals(params.get("KESHI_ID"))) { hql += "and KESHI_ID like '%" + params.get("KESHI_ID").toString() + "%'"; } if (null != params.get("MS") && !"".equals(params.get("MS"))) { hql += "and MS like '%" + params.get("MS").toString() + "%'"; } if (null != params.get("SKSJ") && !"".equals(params.get("SKSJ"))) { hql += "and SKSJ like '%" + params.get("SKSJ").toString() + "%'"; } if (null != params.get("BZ") && !"".equals(params.get("BZ"))) { hql += "and BZ like '%" + params.get("BZ").toString() + "%'"; } if (null != params.get("LSXM") && !"".equals(params.get("LSXM"))) { hql += "and LSXM like '%" + params.get("LSXM").toString() + "%'"; } if (null != params.get("XINGQI") && !"".equals(params.get("XINGQI"))) { hql += "and XINGQI like '%" + params.get("XINGQI").toString() + "%'"; } if (null != params.get("KCLB") && !"".equals(params.get("KCLB"))) { hql += "and KCLB like '%" + params.get("KCLB").toString() + "%'"; } if (null != params.get("JSMC") && !"".equals(params.get("JSMC"))) { hql += "and JSMC like '%" + params.get("JSMC").toString() + "%'"; } if (null != params.get("KCB_FKS_ID") && !"".equals(params.get("KCB_FKS_ID"))) { hql += "and KCB_FKS_ID like '%" + params.get("KCB_FKS_ID").toString() + "%'"; } if (null != params.get("KSMC") && !"".equals(params.get("KSMC"))) { hql += "and KSMC like '%" + params.get("KSMC").toString() + "%'"; } if (null != params.get("LSGH") && !"".equals(params.get("LSGH"))) { hql += "and LSGH like '%" + params.get("LSGH").toString() + "%'"; } if (null != params.get("JS_ID") && !"".equals(params.get("JS_ID"))) { hql += "and JS_ID like '%" + params.get("JS_ID").toString() + "%'"; } int count = Integer.parseInt(baseDao.findAll(hql, java.lang.Long.class) .get(0).toString()); return count; } //findbypagelike @Override public List<KQXX_BJXX> findKQXX_BJXXByPageApp(HashMap<String, String> params, String order, String sort) { String hql = "from KQXX_BJXX where 1=1"; String param=""; ArrayList<String> params2 = new ArrayList<String>(); if (null != params.get("KCMC") && !"".equals(params.get("KCMC"))) { param = "and KCMC like '%" + params.get("KCMC").toString() + "%'"; params2.add(param); } if (null != params.get("KCB_ID") && !"".equals(params.get("KCB_ID"))) { param = "and KCB_ID like '%" + params.get("KCB_ID").toString() + "%'"; params2.add(param); } if (null != params.get("LS_ID") && !"".equals(params.get("LS_ID"))) { param = "and LS_ID like '%" + params.get("LS_ID").toString() + "%'"; params2.add(param); } if (null != params.get("ZHOU") && !"".equals(params.get("ZHOU"))) { param = "and ZHOU like '%" + params.get("ZHOU").toString() + "%'"; params2.add(param); } if (null != params.get("KESHI_ID") && !"".equals(params.get("KESHI_ID"))) { param = "and KESHI_ID like '%" + params.get("KESHI_ID").toString() + "%'"; params2.add(param); } if (null != params.get("MS") && !"".equals(params.get("MS"))) { param = "and MS like '%" + params.get("MS").toString() + "%'"; params2.add(param); } if (null != params.get("SKSJ") && !"".equals(params.get("SKSJ"))) { param = "and SKSJ like '%" + params.get("SKSJ").toString() + "%'"; params2.add(param); } if (null != params.get("BZ") && !"".equals(params.get("BZ"))) { param = "and BZ like '%" + params.get("BZ").toString() + "%'"; params2.add(param); } if (null != params.get("LSXM") && !"".equals(params.get("LSXM"))) { param = "and LSXM like '%" + params.get("LSXM").toString() + "%'"; params2.add(param); } if (null != params.get("XINGQI") && !"".equals(params.get("XINGQI"))) { param = "and XINGQI like '%" + params.get("XINGQI").toString() + "%'"; params2.add(param); } if (null != params.get("KCLB") && !"".equals(params.get("KCLB"))) { param = "and KCLB like '%" + params.get("KCLB").toString() + "%'"; params2.add(param); } if (null != params.get("JSMC") && !"".equals(params.get("JSMC"))) { param = "and JSMC like '%" + params.get("JSMC").toString() + "%'"; params2.add(param); } if (null != params.get("KCB_FKS_ID") && !"".equals(params.get("KCB_FKS_ID"))) { param = "and KCB_FKS_ID like '%" + params.get("KCB_FKS_ID").toString() + "%'"; params2.add(param); } if (null != params.get("KSMC") && !"".equals(params.get("KSMC"))) { param = "and KSMC like '%" + params.get("KSMC").toString() + "%'"; params2.add(param); } if (null != params.get("LSGH") && !"".equals(params.get("LSGH"))) { param = "and LSGH like '%" + params.get("LSGH").toString() + "%'"; params2.add(param); } if (null != params.get("JS_ID") && !"".equals(params.get("JS_ID"))) { param = "and JS_ID like '%" + params.get("JS_ID").toString() + "%'"; params2.add(param); } List<KQXX_BJXX> list = baseDao.findAll(hql,KQXX_BJXX.class); return list; } //考勤信息统计: @Override public HashMap<String, Integer> getBJKQXX(String jsid, String jgid,String ksid, String kcbid,XUEQI xq, String xingqi,String zhou,String ksrq,String jsrq) { HashMap<String, Integer> map=new HashMap<String, Integer>(); int countYCXRS=0; int countQUEXIRS=0; int countZHENGCHANGRS=0; int countCHIDAORS=0; int countZAOTUIRS=0; int countCHIZAORS=0; String hql=" from KQXX_BJXX WHERE 1=1"; if (null !=jsid&&!"".equals(jsid)&&!"".equals(jsid)){ //增加教室ID hql+=" and JS_ID="+"'"+jsid+"'"; } if (null != jgid && !"".equals(jgid)){//增加老师ID hql+=" and LS_ID="+"'"+jgid+"'"; } if (null != ksid && !"".equals(ksid)){//增加课时id hql+=" and KESHI_ID="+"'"+ksid+"'"; } if (null != kcbid && !"".equals(kcbid)){//增加课程表ID hql+=" and KCB_ID="+"'"+kcbid+"'"; } if (null != ksrq && !"".equals(ksrq)){//增加开始日期 hql+=" and SKSJ>=to_date('"+ksrq+"','yyyy-mm-dd')"; } if (null != jsrq && !"".equals(jsrq)){//增加结束日期 hql+=" and SKSJ<=to_date('"+jsrq+" 23:59:59','yyyy-mm-dd hh24:mi:ss')"; } if (null != zhou&&!"".equals(zhou)){//周不为空 //如果星期不为空,则计算星期中课时 List<String> riqi=BaseChangeTool.getRIQIhouZHOUXINGQI(xq.getKSRQ(), xingqi, BaseChangeTool.getZHOUtoInt(zhou)); //根据时间查考勤信息表数////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// for(int i=0;i<riqi.size();i++){ String riqitmp=riqi.get(i); String tmphql=hql; if (null != riqitmp && !"".equals(riqitmp)){//增加课程表ID tmphql+=" and SKSJ>=to_date('"+riqitmp+"','yyyy-mm-dd') and SKSJ<=to_date('"+riqitmp+" 23:59:59','yyyy-mm-dd hh24:mi:ss')"; } if(null!=xq&&!"".equals(xq)){ tmphql+="and SKSJ between to_date('"+xq.getKSRQ().trim()+"','yyyy-mm-dd') and to_date('"+xq.getJSRQ().trim()+"','yyyy-mm-dd')"; } System.out.println("KQXX_BJXXServiceImpl中打印::"+"周不为空时,拼凑的hql::"+tmphql); List<KQXX_BJXX> all_kq1=baseDao.findAll(tmphql,KQXX_BJXX.class); for(KQXX_BJXX b:all_kq1){ countYCXRS+=b.getYSKRS(); countQUEXIRS+=b.getQXRS(); countZHENGCHANGRS+=b.getZCCXRS(); countCHIDAORS+=b.getCDRS(); countZAOTUIRS+=b.getZTRS(); if(null!=b.getCDZTRS()&&!"".equals(b.getCDZTRS())){ countCHIZAORS+=b.getCDZTRS(); } // countCHIZAORS+=b.getCDZTRS(); System.out.println("KQXX_BJXXServiceImpl中打印::"+"应上课人数:"+b.getYSKRS()+"-->"+countYCXRS); System.out.println("KQXX_BJXXServiceImpl中打印::"+"缺席人数:"+b.getQXRS()+"-->"+countQUEXIRS); System.out.println("KQXX_BJXXServiceImpl中打印::"+"迟到人数:"+b.getCDRS()+"-->"+countCHIDAORS); System.out.println("KQXX_BJXXServiceImpl中打印::"+"早退人数:"+b.getZTRS()+"-->"+countZAOTUIRS); System.out.println("KQXX_BJXXServiceImpl中打印::"+"正常人数:"+b.getZCCXRS()+"-->"+countZHENGCHANGRS); System.out.println("KQXX_BJXXServiceImpl中打印::"+"迟到早退人数:"+b.getCDZTRS()+"-->"+countCHIZAORS); } } }else{ //如果周为空 String tmphql=hql; if(null!=xingqi&&!"".equals(xingqi)){ tmphql+=" and XINGQI='"+xingqi+"'"; } if(null!=xq&&!"".equals(xq)){ tmphql+="and SKSJ between to_date('"+xq.getKSRQ().trim()+"','yyyy-mm-dd') and to_date('"+xq.getJSRQ().trim()+"','yyyy-mm-dd')"; } System.out.println("KQXX_BJXXServiceImpl中打印::"+"周是空时,拼凑的hql::"+tmphql); List<KQXX_BJXX> all_kq1=baseDao.findAll(tmphql,KQXX_BJXX.class); for(KQXX_BJXX b:all_kq1){ countYCXRS+=b.getYSKRS(); countQUEXIRS+=b.getQXRS(); countZHENGCHANGRS+=b.getZCCXRS(); countCHIDAORS+=b.getCDRS(); countZAOTUIRS+=b.getZTRS(); // System.out.println("KQXX_BJXXServiceImpl中打印::"+b.getCDZTRS()+"#########################################"); if(null!=b.getCDZTRS()&&!"".equals(b.getCDZTRS())){ countCHIZAORS+=b.getCDZTRS(); } System.out.println("KQXX_BJXXServiceImpl中打印::"+"应上课人数:"+b.getYSKRS()+"-->"+countYCXRS); System.out.println("KQXX_BJXXServiceImpl中打印::"+"缺席人数:"+b.getQXRS()+"-->"+countQUEXIRS); System.out.println("KQXX_BJXXServiceImpl中打印::"+"迟到人数:"+b.getCDRS()+"-->"+countCHIDAORS); System.out.println("KQXX_BJXXServiceImpl中打印::"+"早退人数:"+b.getZTRS()+"-->"+countZAOTUIRS); System.out.println("KQXX_BJXXServiceImpl中打印::"+"正常人数:"+b.getZCCXRS()+"-->"+countZHENGCHANGRS); System.out.println("KQXX_BJXXServiceImpl中打印::"+"迟到早退人数:"+b.getCDZTRS()+"-->"+countCHIZAORS); } } map.put("ycxrs", countYCXRS); map.put("qxrs",countQUEXIRS); map.put("zcrs", countZHENGCHANGRS); map.put("cdrs",countCHIDAORS); map.put("ztrs",countZAOTUIRS); map.put("czrs", countCHIZAORS); return map; } //统计考勤信息,分学院 @Override public HashMap<String, Integer> getBJKQXX(String jsid, String jgid,String ksid, String kcbid, XUEQI xq, String xingqi,String zhou, String ksrq, String jsrq, String xy_id) { if(null==xy_id||"".equals(xy_id)){ System.out.println("KQXX_BJXXServiceImpl中打印::"+"学院ID为空,调用全校方法..."); return getBJKQXX(jsid, jgid, ksid, kcbid, xq, xingqi, zhou, ksrq, jsrq); } HashMap<String, Integer> map=new HashMap<String, Integer>(); int countYCXRS=0; int countQUEXIRS=0; int countZHENGCHANGRS=0; int countCHIDAORS=0; int countZAOTUIRS=0; int countCHIZAORS=0; String hql="from KQXX_BJXX d where d.KCB_ID in(select c.KCB_ID from KECHENGB c where c.KCXX_ID in(select b.KECHENGXX_ID from KECHENGXX b where b.ZY_ID in (select a.ZY_ID from ZHUANYE a where a.XYID='"+xy_id+"')))"; if (null !=jsid&&!"".equals(jsid)&&!"".equals(jsid)){ //增加教室ID hql+=" and d.JS_ID="+"'"+jsid+"'"; } if (null != jgid && !"".equals(jgid)){//增加老师ID hql+=" and d.LS_ID="+"'"+jgid+"'"; } if (null != ksid && !"".equals(ksid)){//增加课时id hql+=" and d.KESHI_ID="+"'"+ksid+"'"; } if (null != kcbid && !"".equals(kcbid)){//增加课程表ID hql+=" and d.KCB_ID="+"'"+kcbid+"'"; } if (null != ksrq && !"".equals(ksrq)){//增加开始日期 hql+=" and d.SKSJ>=to_date('"+ksrq+"','yyyy-mm-dd')"; } if (null != jsrq && !"".equals(jsrq)){//增加结束日期 hql+=" and d.SKSJ<=to_date('"+jsrq+" 23:59:59','yyyy-mm-dd hh24:mi:ss')"; } if(null!=xq&&!"".equals(xq)){ hql+="and SKSJ between to_date('"+xq.getKSRQ().trim()+"','yyyy-mm-dd') and to_date('"+xq.getJSRQ().trim()+"','yyyy-mm-dd')"; } if (null != zhou&&!"".equals(zhou)){//周不为空 //如果星期不为空,则计算星期中课时 List<String>riqi=BaseChangeTool.getRIQIhouZHOUXINGQI(xq.getKSRQ(), xingqi, BaseChangeTool.getZHOUtoInt(zhou)); //根据时间查考勤信息表数////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// for(int i=0;i<riqi.size();i++){ String riqitmp=riqi.get(i); String tmphql=hql; if (null != riqitmp && !"".equals(riqitmp)){//增加课程表ID tmphql+=" and d.SKSJ>=to_date('"+riqitmp+"','yyyy-mm-dd') and d.SKSJ<=to_date('"+riqitmp+" 23:59:59','yyyy-mm-dd hh24:mi:ss')"; } System.out.println("KQXX_BJXXServiceImpl中打印::"+"分学院:周不为空时,拼凑的hql::"+tmphql); List<KQXX_BJXX> all_kq1=baseDao.findAll(tmphql,KQXX_BJXX.class); for(KQXX_BJXX b:all_kq1){ countYCXRS+=b.getYSKRS(); countQUEXIRS+=b.getQXRS(); countZHENGCHANGRS+=b.getZCCXRS(); countCHIDAORS+=b.getCDRS(); countZAOTUIRS+=b.getZTRS(); if(null!=b.getCDZTRS()&&!"".equals(b.getCDZTRS())){ countCHIZAORS+=b.getCDZTRS(); } } } }else{ //如果周为空 String tmphql=hql; if(null!=xingqi&&!"".equals(xingqi)){ tmphql+=" and d.XINGQI='"+xingqi+"'"; } System.out.println("KQXX_BJXXServiceImpl中打印::"+"分学院:周是空时,拼凑的hql::"+tmphql); List<KQXX_BJXX> all_kq1=baseDao.findAll(tmphql,KQXX_BJXX.class); for(KQXX_BJXX b:all_kq1){ countYCXRS+=b.getYSKRS(); countQUEXIRS+=b.getQXRS(); countZHENGCHANGRS+=b.getZCCXRS(); countCHIDAORS+=b.getCDRS(); countZAOTUIRS+=b.getZTRS(); if(null!=b.getCDZTRS()&&!"".equals(b.getCDZTRS())){ countCHIZAORS+=b.getCDZTRS(); } } } map.put("ycxrs", countYCXRS); map.put("qxrs",countQUEXIRS); map.put("zcrs", countZHENGCHANGRS); map.put("cdrs",countCHIDAORS); map.put("ztrs",countZAOTUIRS); map.put("czrs", countCHIZAORS); return map; } //统计考勤信息,分学院-->专业 @Override public HashMap<String, Integer> getBJKQXX(String jsid, String jgid,String ksid, String kcbid, XUEQI xq, String xingqi,String zhou, String ksrq, String jsrq, String xy_id,String zy_id) { if(null==zy_id||"".equals(zy_id)){ System.out.println("KQXX_BJXXServiceImpl中打印::"+"专业ID为空,调用全校方法..."); return getBJKQXX(jsid, jgid, ksid, kcbid, xq, xingqi, zhou, ksrq, jsrq,xy_id); } HashMap<String, Integer> map=new HashMap<String, Integer>(); int countYCXRS=0; int countQUEXIRS=0; int countZHENGCHANGRS=0; int countCHIDAORS=0; int countZAOTUIRS=0; int countCHIZAORS=0; String hql="from KQXX_BJXX d where d.KCB_ID in(select c.KCB_ID from KECHENGB c where c.KCXX_ID in(select b.KECHENGXX_ID from KECHENGXX b where b.ZY_ID='"+zy_id+"'))"; if (null !=jsid&&!"".equals(jsid)&&!"".equals(jsid)){ //增加教室ID hql+=" and d.JS_ID="+"'"+jsid+"'"; } if (null != jgid && !"".equals(jgid)){//增加老师ID hql+=" and d.LS_ID="+"'"+jgid+"'"; } if (null != ksid && !"".equals(ksid)){//增加课时id hql+=" and d.KESHI_ID="+"'"+ksid+"'"; } if (null != kcbid && !"".equals(kcbid)){//增加课程表ID hql+=" and d.KCB_ID="+"'"+kcbid+"'"; } if (null != ksrq && !"".equals(ksrq)){//增加开始日期 hql+=" and d.SKSJ>=to_date('"+ksrq+"','yyyy-mm-dd')"; } if (null != jsrq && !"".equals(jsrq)){//增加结束日期 hql+=" and d.SKSJ<=to_date('"+jsrq+" 23:59:59','yyyy-mm-dd hh24:mi:ss')"; } if(null!=xq&&!"".equals(xq)){ hql+="and SKSJ between to_date('"+xq.getKSRQ().trim()+"','yyyy-mm-dd') and to_date('"+xq.getJSRQ().trim()+"','yyyy-mm-dd')"; } if (null != zhou&&!"".equals(zhou)){//周不为空 //如果星期不为空,则计算星期中课时 List<String>riqi=BaseChangeTool.getRIQIhouZHOUXINGQI(xq.getKSRQ(), xingqi, BaseChangeTool.getZHOUtoInt(zhou)); //根据时间查考勤信息表数////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// for(int i=0;i<riqi.size();i++){ String riqitmp=riqi.get(i); String tmphql=hql; if (null != riqitmp && !"".equals(riqitmp)){//增加课程表ID tmphql+=" and d.SKSJ>=to_date('"+riqitmp+"','yyyy-mm-dd') and d.SKSJ<=to_date('"+riqitmp+" 23:59:59','yyyy-mm-dd hh24:mi:ss')"; } System.out.println("KQXX_BJXXServiceImpl中打印::"+"分转业:周不为空时,拼凑的hql::"+tmphql); List<KQXX_BJXX> all_kq1=baseDao.findAll(tmphql,KQXX_BJXX.class); for(KQXX_BJXX b:all_kq1){ countYCXRS+=b.getYSKRS(); countQUEXIRS+=b.getQXRS(); countZHENGCHANGRS+=b.getZCCXRS(); countCHIDAORS+=b.getCDRS(); countZAOTUIRS+=b.getZTRS(); if(null!=b.getCDZTRS()&&!"".equals(b.getCDZTRS())){ countCHIZAORS+=b.getCDZTRS(); } } } }else{ //如果周为空 String tmphql=hql; if(null!=xingqi&&!"".equals(xingqi)){ tmphql+=" and d.XINGQI="+xingqi; } System.out.println("KQXX_BJXXServiceImpl中打印::"+"分专业:周是空时,拼凑的hql::"+tmphql); List<KQXX_BJXX> all_kq1=baseDao.findAll(tmphql,KQXX_BJXX.class); for(KQXX_BJXX b:all_kq1){ countYCXRS+=b.getYSKRS(); countQUEXIRS+=b.getQXRS(); countZHENGCHANGRS+=b.getZCCXRS(); countCHIDAORS+=b.getCDRS(); countZAOTUIRS+=b.getZTRS(); if(null!=b.getCDZTRS()&&!"".equals(b.getCDZTRS())){ countCHIZAORS+=b.getCDZTRS(); } } } map.put("ycxrs", countYCXRS); map.put("qxrs",countQUEXIRS); map.put("zcrs", countZHENGCHANGRS); map.put("cdrs",countCHIDAORS); map.put("ztrs",countZAOTUIRS); map.put("czrs",countCHIZAORS); return map; } //统计考勤信息,分学院-->专业-->年级 @Override public HashMap<String, Integer> getBJKQXX(String jsid, String jgid,String ksid, String kcbid, XUEQI xq, String xingqi,String zhou, String ksrq, String jsrq, String xy_id,String zy_id,String nj_id) { if(null==xy_id||"".equals(xy_id)){ System.out.println("KQXX_BJXXServiceImpl中打印::"+"学院ID为空,调用全校方法..."); return getBJKQXX(jsid, jgid, ksid, kcbid, xq, xingqi, zhou, ksrq, jsrq); } HashMap<String, Integer> map=new HashMap<String, Integer>(); int countYCXRS=0; int countQUEXIRS=0; int countZHENGCHANGRS=0; int countCHIDAORS=0; int countZAOTUIRS=0; int countCHIZAORS=0; String hql="from KQXX_BJXX d where d.KCB_ID in(select c.KCB_ID from KECHENGB c where c.KCXX_ID in(select b.KECHENGXX_ID from KECHENGXX b where b.ZY_ID in (select a.ZY_ID from ZHUANYE a where a.XYID='"+xy_id+"')))"; if (null !=jsid&&!"".equals(jsid)&&!"".equals(jsid)){ //增加教室ID hql+=" and d.JS_ID="+"'"+jsid+"'"; } if (null != jgid && !"".equals(jgid)){//增加老师ID hql+=" and d.LS_ID="+"'"+jgid+"'"; } if (null != ksid && !"".equals(ksid)){//增加课时id hql+=" and d.KESHI_ID="+"'"+ksid+"'"; } if (null != kcbid && !"".equals(kcbid)){//增加课程表ID hql+=" and d.KCB_ID="+"'"+kcbid+"'"; } if (null != ksrq && !"".equals(ksrq)){//增加开始日期 hql+=" and d.SKSJ>=to_date('"+ksrq+"','yyyy-mm-dd')"; } if (null != jsrq && !"".equals(jsrq)){//增加结束日期 hql+=" and d.SKSJ<=to_date('"+jsrq+" 23:59:59','yyyy-mm-dd hh24:mi:ss')"; } if(null!=xq&&!"".equals(xq)){ hql+="and SKSJ between to_date('"+xq.getKSRQ().trim()+"','yyyy-mm-dd') and to_date('"+xq.getJSRQ().trim()+"','yyyy-mm-dd')"; } if (null != zhou&&!"".equals(zhou)){//周不为空 //如果星期不为空,则计算星期中课时 List<String>riqi=BaseChangeTool.getRIQIhouZHOUXINGQI(xq.getKSRQ(), xingqi, BaseChangeTool.getZHOUtoInt(zhou)); //根据时间查考勤信息表数////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// for(int i=0;i<riqi.size();i++){ String riqitmp=riqi.get(i); String tmphql=hql; if (null != riqitmp && !"".equals(riqitmp)){//增加课程表ID tmphql+=" and d.SKSJ>=to_date('"+riqitmp+"','yyyy-mm-dd') and d.SKSJ<=to_date('"+riqitmp+" 23:59:59','yyyy-mm-dd hh24:mi:ss')"; } System.out.println("KQXX_BJXXServiceImpl中打印::"+"分学院:周不为空时,拼凑的hql::"+tmphql); List<KQXX_BJXX> all_kq1=baseDao.findAll(tmphql,KQXX_BJXX.class); for(KQXX_BJXX b:all_kq1){ countYCXRS+=b.getYSKRS(); countQUEXIRS+=b.getQXRS(); countZHENGCHANGRS+=b.getZCCXRS(); countCHIDAORS+=b.getCDRS(); countZAOTUIRS+=b.getZTRS(); if(null!=b.getCDZTRS()&&!"".equals(b.getCDZTRS())){ countCHIZAORS+=b.getCDZTRS(); } } } }else{ //如果周为空 String tmphql=hql; if(null!=xingqi&&!"".equals(xingqi)){ tmphql+=" and d.XINGQI="+"'"+xingqi+"'"; } System.out.println("KQXX_BJXXServiceImpl中打印::"+"分学院:周是空时,拼凑的hql::"+tmphql); List<KQXX_BJXX> all_kq1=baseDao.findAll(tmphql,KQXX_BJXX.class); for(KQXX_BJXX b:all_kq1){ countYCXRS+=b.getYSKRS(); countQUEXIRS+=b.getQXRS(); countZHENGCHANGRS+=b.getZCCXRS(); countCHIDAORS+=b.getCDRS(); countZAOTUIRS+=b.getZTRS(); if(null!=b.getCDZTRS()&&!"".equals(b.getCDZTRS())){ countCHIZAORS+=b.getCDZTRS(); } } } map.put("ycxrs", countYCXRS); map.put("qxrs",countQUEXIRS); map.put("zcrs", countZHENGCHANGRS); map.put("cdrs",countCHIDAORS); map.put("ztrs",countZAOTUIRS); map.put("czrs", countCHIZAORS); return map; } //统计考勤信息,分学院-->专业-->年级-->班级 @Override public HashMap<String, Integer> getBJKQXX(String jsid, String jgid,String ksid, String kcbid, XUEQI xq, String xingqi,String zhou, String ksrq, String jsrq, String xy_id,String zy_id,String nj_id,String bj_id) { if(null==xy_id||"".equals(xy_id)){ System.out.println("KQXX_BJXXServiceImpl中打印::"+"学院ID为空,调用全校方法..."); return getBJKQXX(jsid, jgid, ksid, kcbid, xq, xingqi, zhou, ksrq, jsrq); } HashMap<String, Integer> map=new HashMap<String, Integer>(); int countYCXRS=0; int countQUEXIRS=0; int countZHENGCHANGRS=0; int countCHIDAORS=0; int countZAOTUIRS=0; int countCHIZAORS=0; String hql="from KQXX_BJXX d where d.KCB_ID in(select c.KCB_ID from KECHENGB c where c.KCXX_ID in(select b.KECHENGXX_ID from KECHENGXX b where b.ZY_ID in (select a.ZY_ID from ZHUANYE a where a.XYID='"+xy_id+"')))"; if (null !=jsid&&!"".equals(jsid)&&!"".equals(jsid)){ //增加教室ID hql+=" and d.JS_ID="+"'"+jsid+"'"; } if (null != jgid && !"".equals(jgid)){//增加老师ID hql+=" and d.LS_ID="+"'"+jgid+"'"; } if (null != ksid && !"".equals(ksid)){//增加课时id hql+=" and d.KESHI_ID="+"'"+ksid+"'"; } if (null != kcbid && !"".equals(kcbid)){//增加课程表ID hql+=" and d.KCB_ID="+"'"+kcbid+"'"; } if (null != ksrq && !"".equals(ksrq)){//增加开始日期 hql+=" and d.SKSJ>=to_date('"+ksrq+"','yyyy-mm-dd')"; } if (null != jsrq && !"".equals(jsrq)){//增加结束日期 hql+=" and d.SKSJ<=to_date('"+jsrq+" 23:59:59','yyyy-mm-dd hh24:mi:ss')"; } if(null!=xq&&!"".equals(xq)){ hql+="and SKSJ between to_date('"+xq.getKSRQ().trim()+"','yyyy-mm-dd') and to_date('"+xq.getJSRQ().trim()+"','yyyy-mm-dd')"; } if (null != zhou&&!"".equals(zhou)){//周不为空 //如果星期不为空,则计算星期中课时 List<String>riqi=BaseChangeTool.getRIQIhouZHOUXINGQI(xq.getKSRQ(), xingqi, BaseChangeTool.getZHOUtoInt(zhou)); //根据时间查考勤信息表数////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// for(int i=0;i<riqi.size();i++){ String riqitmp=riqi.get(i); String tmphql=hql; if (null != riqitmp && !"".equals(riqitmp)){//增加课程表ID tmphql+=" and d.SKSJ>=to_date('"+riqitmp+"','yyyy-mm-dd') and d.SKSJ<=to_date('"+riqitmp+" 23:59:59','yyyy-mm-dd hh24:mi:ss')"; } System.out.println("KQXX_BJXXServiceImpl中打印::"+"分学院:周不为空时,拼凑的hql::"+tmphql); List<KQXX_BJXX> all_kq1=baseDao.findAll(tmphql,KQXX_BJXX.class); for(KQXX_BJXX b:all_kq1){ countYCXRS+=b.getYSKRS(); countQUEXIRS+=b.getQXRS(); countZHENGCHANGRS+=b.getZCCXRS(); countCHIDAORS+=b.getCDRS(); countZAOTUIRS+=b.getZTRS(); if(null!=b.getCDZTRS()&&!"".equals(b.getCDZTRS())){ countCHIZAORS+=b.getCDZTRS(); } } } }else{ //如果周为空 String tmphql=hql; if(null!=xingqi&&!"".equals(xingqi)){ tmphql+=" and d.XINGQI="+"'"+xingqi+"'"; } System.out.println("KQXX_BJXXServiceImpl中打印::"+"分学院:周是空时,拼凑的hql::"+tmphql); List<KQXX_BJXX> all_kq1=baseDao.findAll(tmphql,KQXX_BJXX.class); for(KQXX_BJXX b:all_kq1){ countYCXRS+=b.getYSKRS(); countQUEXIRS+=b.getQXRS(); countZHENGCHANGRS+=b.getZCCXRS(); countCHIDAORS+=b.getCDRS(); countZAOTUIRS+=b.getZTRS(); if(null!=b.getCDZTRS()&&!"".equals(b.getCDZTRS())){ countCHIZAORS+=b.getCDZTRS(); } } } map.put("ycxrs", countYCXRS); map.put("qxrs",countQUEXIRS); map.put("zcrs", countZHENGCHANGRS); map.put("cdrs",countCHIDAORS); map.put("ztrs",countZAOTUIRS); map.put("czrs", countCHIZAORS); return map; } //统计考勤信息,分教师 @Override public HashMap<String, Integer> getBJXXKQXXbyJG(String jgid,String ksid, String kcbid, XUEQI xq, String xingqi,String zhou, String ksrq, String jsrq) { HashMap<String, Integer> map=new HashMap<String, Integer>(); String sql1="select t.kcb_id,t.kcmc,sum(t.yskrs) 应出席人数,sum(t.zccxrs) 正常出席人数,sum(t.qxrs) 缺席人数,sum(t.cdrs) 迟到人数,sum(t.ztrs) 早退人数,sum(t.cdztrs) 迟到早退人数 from kqxx_bjxx t where 1=1 "; String sql2=" group by t.kcb_id,t.kcmc"; if (null != jgid && !"".equals(jgid)){//增加老师ID sql1+=" and t.LS_ID='"+jgid+"'"; } if (null != ksid && !"".equals(ksid)){//增加课时id sql1+=" and t.KESHI_ID="+"'"+ksid+"'"; } if (null != kcbid && !"".equals(kcbid)){//增加课程表ID sql1+=" and t.KCB_ID="+"'"+kcbid+"'"; } if (null != ksrq && !"".equals(ksrq)){//增加开始日期 sql1+=" and t.SKSJ>=to_date('"+ksrq+"','yyyy-mm-dd')"; } if (null != jsrq && !"".equals(jsrq)){//增加结束日期 sql1+=" and t.SKSJ<=to_date('"+jsrq+" 23:59:59','yyyy-mm-dd hh24:mi:ss')"; } if(null!=xq&&!"".equals(xq)){ sql1+="and t.SKSJ between to_date('"+xq.getKSRQ().trim()+"','yyyy-mm-dd') and to_date('"+xq.getJSRQ().trim()+"','yyyy-mm-dd')"; } List allcq=null; if (null != zhou&&!"".equals(zhou)){//周不为空 //如果星期不为空,则计算星期中课时 List<String>riqi=BaseChangeTool.getRIQIhouZHOUXINGQI(xq.getKSRQ(), xingqi, BaseChangeTool.getZHOUtoInt(zhou)); //根据时间查考勤信息表数////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// for(int i=0;i<riqi.size();i++){ String riqitmp=riqi.get(i); String tmphql=sql1; if (null != riqitmp && !"".equals(riqitmp)){//增加课程表ID tmphql+=" and t.SKSJ>=to_date('"+riqitmp+"','yyyy-mm-dd') and t.SKSJ<=to_date('"+riqitmp+" 23:59:59','yyyy-mm-dd hh24:mi:ss')"; } tmphql+=sql2; System.out.println("KQXX_BJXXServiceImpl中打印::"+"周为空时,分老师统计考勤信息::"+tmphql); allcq=baseDao.executeSQL(tmphql); } }else{ //如果周为空 String tmphql=sql1; if(null!=xingqi&&!"".equals(xingqi)){ tmphql+=" and t.XINGQI="+xingqi; } tmphql+=sql2; System.out.println("KQXX_BJXXServiceImpl中打印::"+"周为空时,分老师统计考勤信息::"+tmphql); allcq=baseDao.executeSQL(tmphql); } if(null!=allcq){//如果有结果集 if(allcq.size()>0){ Object[] tmpObjArray=(Object[]) allcq.get(0); String kcb_id=(null==tmpObjArray[0])?"0":tmpObjArray[0].toString(); //课程表ID String kcb_kcmc=(null==tmpObjArray[1])?"0":tmpObjArray[1].toString();//课程表名称 String ycxrs=(null==tmpObjArray[2])?"0":tmpObjArray[2].toString();//应出席人数 String zccxrs=(null==tmpObjArray[3])?"0":tmpObjArray[3].toString();//正常出席人数 String qxrs=(null==tmpObjArray[4])?"0":tmpObjArray[4].toString();//缺席人数 String cdrs=(null==tmpObjArray[5])?"0":tmpObjArray[5].toString();// String ztrs=(null==tmpObjArray[6])?"0":tmpObjArray[6].toString(); String cdztrs=(null==tmpObjArray[7])?"0":tmpObjArray[7].toString(); map.put("ycxrs", Integer.parseInt(ycxrs)); map.put("qxrs",Integer.parseInt(qxrs)); map.put("zcrs",Integer.parseInt(zccxrs)); map.put("cdrs",Integer.parseInt(cdrs)); map.put("ztrs",Integer.parseInt(ztrs)); map.put("czrs",Integer.parseInt(cdztrs)); return map; } } return null; } //统计考勤信息,分教师 @Override public HashMap<String, Integer> getBJXXKQXXbyJS(String jsid,String ksid, String kcbid, XUEQI xq, String xingqi,String zhou, String ksrq, String jsrq) { HashMap<String, Integer> map=new HashMap<String, Integer>(); String sql1="select t.kcb_id,t.kcmc,sum(t.yskrs) 应出席人数,sum(t.zccxrs) 正常出席人数,sum(t.qxrs) 缺席人数,sum(t.cdrs) 迟到人数,sum(t.ztrs) 早退人数,sum(t.cdztrs) 迟到早退人数 from kqxx_bjxx t where 1=1 "; String sql2=" group by t.kcb_id,t.kcmc"; if (null != jsid && !"".equals(jsid)){//增加教室ID sql1+=" and t.JS_ID='"+jsid+"'"; } if (null != ksid && !"".equals(ksid)){//增加课时id sql1+=" and t.KESHI_ID="+"'"+ksid+"'"; } if (null != kcbid && !"".equals(kcbid)){//增加课程表ID sql1+=" and t.KCB_ID="+"'"+kcbid+"'"; } if (null != ksrq && !"".equals(ksrq)){//增加开始日期 sql1+=" and t.SKSJ>=to_date('"+ksrq+"','yyyy-mm-dd')"; } if (null != jsrq && !"".equals(jsrq)){//增加结束日期 sql1+=" and t.SKSJ<=to_date('"+jsrq+" 23:59:59','yyyy-mm-dd hh24:mi:ss')"; } if(null!=xq&&!"".equals(xq)){ sql1+="and t.SKSJ between to_date('"+xq.getKSRQ().trim()+"','yyyy-mm-dd') and to_date('"+xq.getJSRQ().trim()+"','yyyy-mm-dd')"; } List allcq=null; if (null != zhou&&!"".equals(zhou)){//周不为空 //如果星期不为空,则计算星期中课时 List<String>riqi=BaseChangeTool.getRIQIhouZHOUXINGQI(xq.getKSRQ(), xingqi, BaseChangeTool.getZHOUtoInt(zhou)); //根据时间查考勤信息表数////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// for(int i=0;i<riqi.size();i++){ String riqitmp=riqi.get(i); String tmphql=sql1; if (null != riqitmp && !"".equals(riqitmp)){//增加课程表ID tmphql+=" and t.SKSJ>=to_date('"+riqitmp+"','yyyy-mm-dd') and t.SKSJ<=to_date('"+riqitmp+" 23:59:59','yyyy-mm-dd hh24:mi:ss')"; } tmphql+=sql2; System.out.println("KQXX_BJXXServiceImpl中打印::"+"周为空时,分老师统计考勤信息::"+tmphql); allcq=baseDao.executeSQL(tmphql); } }else{ //如果周为空 String tmphql=sql1; if(null!=xingqi&&!"".equals(xingqi)){ tmphql+=" and t.XINGQI="+"'"+xingqi+"'"; } tmphql+=sql2; System.out.println("KQXX_BJXXServiceImpl中打印::"+"周为空时,分老师统计考勤信息::"+tmphql); allcq=baseDao.executeSQL(tmphql); } if(null!=allcq){//如果有结果集 if(allcq.size()>0){ Object[] tmpObjArray=(Object[]) allcq.get(0); String kcb_id=(null==tmpObjArray[0])?"0":tmpObjArray[0].toString(); //课程表ID String kcb_kcmc=(null==tmpObjArray[1])?"0":tmpObjArray[1].toString();//课程表名称 String ycxrs=(null==tmpObjArray[2])?"0":tmpObjArray[2].toString();//应出席人数 String zccxrs=(null==tmpObjArray[3])?"0":tmpObjArray[3].toString();//正常出席人数 String qxrs=(null==tmpObjArray[4])?"0":tmpObjArray[4].toString();//缺席人数 String cdrs=(null==tmpObjArray[5])?"0":tmpObjArray[5].toString();// String ztrs=(null==tmpObjArray[6])?"0":tmpObjArray[6].toString(); String cdztrs=(null==tmpObjArray[7])?"0":tmpObjArray[7].toString(); map.put("ycxrs", Integer.parseInt(ycxrs)); map.put("qxrs",Integer.parseInt(qxrs)); map.put("zcrs",Integer.parseInt(zccxrs)); map.put("cdrs",Integer.parseInt(cdrs)); map.put("ztrs",Integer.parseInt(ztrs)); map.put("czrs",Integer.parseInt(cdztrs)); return map; } } return null; } }
true
4b89a8af0e95dd86a41355d13e4739c5a4491ce8
Java
wuyifat/SearchEngine
/MyThreads.java
UTF-8
1,459
2.5625
3
[]
no_license
package com.company; import org.jsoup.Jsoup; import org.jsoup.helper.Validate; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.omg.CosNaming.NamingContextPackage.NotFound; import java.io.*; import java.util.*; import static com.company.Main.create_file; /** * Created by Jin on 4/9/2015. */ public class MyThreads implements Runnable{ private static String docNum; private String url; private String text; private String title; public MyThreads(String docNum,String url, String title){ this.docNum = docNum; this.url = url; this.title = title; } public void run(){ try { Document doc = Jsoup.connect(url).get(); text = doc.body().text(); }catch(IOException e){} try{ create_file(docNum); } catch(IOException e){ System.out.println("create file failed"); } try { PrintWriter writer = new PrintWriter(docNum); writer.println(title + "\n"); writer.println(text); writer.close(); } catch (FileNotFoundException e){ System.out.println("open file fail"); } } public static void create_file(String doc)throws IOException{ File f = new File(doc); f.createNewFile(); } }
true
2309348d34f60afa1ac6454fe9b701990e35405c
Java
jiangyukun/ttsales-web
/src/main/java/cn/ttsales/work/persistence/sys/WxUserBonusDao.java
UTF-8
2,496
2.09375
2
[]
no_license
/** * Copyright (c) 2014 RATANSFOT.All rights reserved. * @filename WxUserBonusDao.java * @package cn.ttsales.work.persistence.rbs * @author dandyzheng * @date 2012-7-27 */ package cn.ttsales.work.persistence.sys; import java.util.List; import cn.ttsales.work.domain.WxUserBonus; /** * WxUserBonus DAO * @author dandyzheng * */ public interface WxUserBonusDao { /** * 保存 WxUserBonus * @param wxUserBonus WxUserBonus * @return WxUserBonus * @author dandyzheng * @date 2013-3-27 * @see */ public WxUserBonus saveWxUserBonus(WxUserBonus wxUserBonus); /** * 批量保存WxUserBonus * @param wxUserBonuss WxUserBonuss * @return List<WxUserBonus> * @author dandyzheng * @date 2013-3-27 * @see */ public List<WxUserBonus> saveWxUserBonuss(List<WxUserBonus> wxUserBonuss); /** * 修改WxUserBonus * @param wxUserBonus WxUserBonus * @return WxUserBonus * @author dandyzheng * @date 2013-3-27 * @see */ public WxUserBonus editWxUserBonus(WxUserBonus wxUserBonus); /** * 批量修改WxUserBonus * @param wxUserBonuss WxUserBonuss * @return List<WxUserBonus> * @author dandyzheng * @date 2013-3-27 * @see */ public List<WxUserBonus> editWxUserBonuss(List<WxUserBonus> wxUserBonuss); /** * 删除WxUserBonus * @param WxUserBonus WxUserBonus * @author dandyzheng * @date 2013-3-27 * @see */ public void removeWxUserBonus(WxUserBonus wxUserBonus); /** * 批量删除WxUserBonus * @param WxUserBonuss WxUserBonuss * @author dandyzheng * @date 2013-3-27 * @see */ public void removeWxUserBonuss(List<WxUserBonus> wxUserBonuss); /** * 根据WxUserBonus' id,删除WxUserBonus * @param wxUserBonusId WxUserBonus's id * @author dandyzheng * @date 2013-3-27 * @see */ public void removeWxUserBonus(String wxUserBonusId); /** * 根据WxUserBonus' id,获取WxUserBonus * @param wxUserBonusId WxUserBonus's id * @return WxUserBonus * @author dandyzheng * @date 2013-3-27 * @see */ public WxUserBonus getWxUserBonus(String wxUserBonusId); /** * 获取所有WxUserBonus * @return List<WxUserBonus> * @author dandyzheng * @date 2013-3-27 * @see */ public List<WxUserBonus> getAllWxUserBonuss(); /** * 根据ownerId bonusId 获取微信红包 * @param ownerId * @param bonusId * @return * @author zhaoxiaobin * @date 2015-1-30 * @see */ public WxUserBonus getWxUserBonusByOwnerIdAndbonusId(String ownerId, String bonusId); }
true
9c9d6865430149217d09fd4acd22ebc7955ac493
Java
cjeanGitHub/exercies
/springstart/src/main/java/com/cjean/springstart/TestGetBean.java
GB18030
2,086
2.625
3
[ "Apache-2.0" ]
permissive
package com.cjean.springstart; /** * Copyright (C), 2015-2019, XXX޹˾ * FileName: TestGetBean * Author: 14172 * Date: 2019/12/11 9:24 * History: * <author> <time> <version> <desc> * ޸ʱ 汾 */ import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.ClassPathResource; /** * @author 14172 * @create 2019/12/11 * @since 1.0.0 */ public class TestGetBean implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { TestGetBean.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext() { return applicationContext; } public static void main(String[] args) { ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); Person person = (Person)classPathXmlApplicationContext.getBean("person"); System.out.println(person.getAge()); classPathXmlApplicationContext.getBean("food"); System.out.println(person.getFood().getApple()); String[] beans = TestGetBean.getApplicationContext().getBeanDefinitionNames(); for (String beanName : beans) { Class<?> beanType = TestGetBean.getApplicationContext() .getType(beanName); System.out.println("BeanName:" + beanName); System.out.println("Beanͣ" + beanType); System.out.println("Beanڵİ" + beanType.getPackage()); System.out.println("Bean" + TestGetBean.getApplicationContext().getBean( beanName)); } } }
true
03f55ccb9ee2eca3e0eb9845745e69a25af512cf
Java
appelation/code-android
/philately-catalog/app/src/main/java/com/appleation/library/DrawLine.java
UTF-8
692
2.4375
2
[]
no_license
package com.appleation.library; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.View; /** * Created by DELL7537 on 02-03-2016. */ public class DrawLine extends View { Paint paint = new Paint(); public DrawLine(Context context) { super(context); paint.setColor(Color.BLACK); } @Override public void onDraw(Canvas canvas) { canvas.drawLine(0, 0, 20, 20, paint); canvas.drawLine(20, 0, 0, 20, paint); } } //******* Usage ******** //drawView = new DrawView(this); //drawView.setBackgroundColor(Color.WHITE); //setContentView(drawView);
true
0f88b22e6b4b4ecea9adb17241614e4a970fece2
Java
roxanavp87/Java
/src/JavaII/Measurable.java
UTF-8
141
2.21875
2
[]
no_license
package JavaII; /** * Created by roxana on 5/19/17. */ public interface Measurable { double getPerimeter(); double getArea(); }
true
9c73ca53e298ec64c8fa6373eee4d0a4fe935a70
Java
Hunter0x7c7/HelloAndroid
/app/src/main/java/com/hunter/helloandroid/module/custom/CustomViewActivity.java
UTF-8
8,431
2
2
[]
no_license
package com.hunter.helloandroid.module.custom; import android.animation.ObjectAnimator; import android.content.Intent; import android.graphics.Path; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.animation.DecelerateInterpolator; import android.view.animation.LinearInterpolator; import com.hunter.helloandroid.R; import com.hunter.helloandroid.module.custom.hexagon.HexgonActivity; import com.hunter.helloandroid.module.custom.path.AnimatorPath.AnimatorPath; import com.hunter.helloandroid.module.custom.path.AnimatorPath.PathEvaluator; import com.hunter.helloandroid.module.custom.path.AnimatorPath.PathPoint; import com.hunter.helloandroid.module.custom.path.PathCopy; import com.hunter.helloandroid.module.custom.path.PathView; import com.hunter.helloandroid.module.custom.path.SvgPathParser; import java.text.ParseException; import butterknife.BindView; import butterknife.ButterKnife; /** * ================================================================ * <p> * 版 权: (c)2018 * <p> * 作 者: Huang zihang * <p> * 版 本: V1.0 * <p> * 创建日期: 2018/4/10 15:52 * <p> * 描 述:自定义View * <p> * <p> * 修订历史: * <p> * ================================================================ */ public class CustomViewActivity extends AppCompatActivity { @BindView(R.id.mpv_player) MusicPlayerView mMusicPlayerView; @BindView(R.id.rcv) RotateCircleImageView mRotateCircle; @BindView(R.id.epv_earth_path) EarthPathView mEarthPathView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custom_view); ButterKnife.bind(this); mMusicPlayerView.start(); // int w = getResources().getDisplayMetrics().widthPixels; // int h = getResources().getDisplayMetrics().heightPixels; // // int min = Math.min(w, h); // Path path = buildPath(w / 2 - 200, h / 2 - 200, min / 8); // mEarthPathView.setPath(path); mEarthPathView.startAnim(); setPath(); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // startAnimatorPath(fab, "fab", mPathView.getPath()); startAnimator(fab, mPathView.getPath()); } }); initPathCopy(); } public void startRotate(View v) { mRotateCircle.startRotate(); } public void stopRotate(View v) { mRotateCircle.stopRotate(); } private Path buildPath(float x, float y, float radius) { Path mPath = new Path(); mPath.addCircle(x, y, radius, Path.Direction.CW); return mPath; } @BindView(R.id.fab) FloatingActionButton fab; @BindView(R.id.pv_fab) PathView mPathView; private AnimatorPath mAnimatorPath;//声明动画集合 /** * 设置动画路径 */ public void setPath() { mAnimatorPath = new AnimatorPath(); // mAnimatorPath.moveTo(0, 0); // mAnimatorPath.lineTo(400, 400); // mAnimatorPath.secondBesselCurveTo(600, 200, 800, 400); //订单 // mAnimatorPath.thirdBesselCurveTo(100, 600, 900, 1000, 200, 1200); mAnimatorPath.moveTo(60, 60); mAnimatorPath.lineTo(460, 460); mAnimatorPath.secondBesselCurveTo(660, 260, 860, 460); //订单 mAnimatorPath.thirdBesselCurveTo(160, 660, 960, 1060, 260, 1260); } /** * 设置动画 * * @param view 使用动画的View * @param propertyName 属性名字 * @param path 动画路径集合 */ private void startAnimatorPath(View view, String propertyName, AnimatorPath path) { ObjectAnimator anim = ObjectAnimator.ofObject(view, propertyName, new PathEvaluator(), path.getPoints().toArray()); anim.setInterpolator(new DecelerateInterpolator()); anim.setDuration(3000); anim.start(); } /** * 设置View的属性通过ObjectAnimator.ofObject()的反射机制来调用 */ public void setFab(PathPoint newLoc) { fab.setTranslationX(newLoc.mX); fab.setTranslationY(newLoc.mY); } /** * 给个路径(path)我送你个动画 */ @SuppressWarnings("all") private void startAnimator(View mView, Path path) { //mView 用来执行动画的View ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mView, View.X, View.Y, path); objectAnimator.setInterpolator(new LinearInterpolator()); objectAnimator.setDuration(6000); objectAnimator.start(); } /** * 矩形动画 * * @return */ private Path rectanglePath(View mView, int width) { Path path = new Path(); //view本身的宽度,不减去就跑出屏幕外面了 int v_width = mView.getWidth(); path.moveTo(0, 0); path.lineTo(width - v_width, 0); path.lineTo(width - v_width, width); path.lineTo(0, width); path.lineTo(0, 0); return path; } /** * 圆弧动画 叶子型动画(两个弧形对接) * * @return */ private Path arcPath(View mView, int width) { Path path = new Path(); int v_width = mView.getWidth(); int d_width = width - v_width; path.moveTo(0, 0); path.quadTo(0, d_width, d_width, d_width); path.moveTo(d_width, d_width); path.quadTo(d_width, 0, 0, 0); return path; } /** * 模拟正弦曲线 */ private Path sinPath(View mView, int width) { Path path = new Path(); int vWidth = mView.getWidth(); int dWidth = width - vWidth; path.moveTo(0, 0); path.quadTo(0, dWidth, dWidth / 4, dWidth); path.moveTo(dWidth / 4, dWidth); path.cubicTo(dWidth / 2, dWidth, dWidth / 2, 0, dWidth * 3 / 4, 0); path.moveTo(dWidth * 3 / 4, 0); path.quadTo(dWidth, 0, dWidth, dWidth); return path; } public void onClickHexagon(View view) { startActivity(new Intent(this, HexgonActivity.class)); } public void onClickSVG(View view) throws ParseException { SvgPathParser svgPathParser = new SvgPathParser(); String pathStr = "M 495.00,0.00\n" + " C 495.00,0.00 495.00,417.00 495.00,417.00\n" + " 495.00,417.00 0.00,417.00 0.00,417.00\n" + " 0.00,417.00 0.00,0.00 0.00,0.00\n" + " 0.00,0.00 495.00,0.00 495.00,0.00 Z\n" + " M 81.18,219.39\n" + " C 75.28,224.66 73.26,233.55 71.61,241.00\n" + " 68.81,256.26 68.66,271.70 71.61,287.00\n" + " 72.76,294.37 74.47,301.98 79.68,307.70\n" + " 85.29,313.85 91.52,314.81 99.00,316.73\n" + " 99.00,316.73 126.00,321.96 126.00,321.96\n" + " 126.00,321.96 134.00,321.96 134.00,321.96\n" + " 134.00,321.96 144.00,323.00 144.00,323.00\n" + " 156.04,323.14 168.13,322.58 180.00,320.39\n" + " 187.27,319.04 193.58,317.17 198.20,310.91\n" + " 202.27,305.40 200.54,300.30 201.28,294.00\n" + " 201.28,294.00 202.00,244.00 202.00,244.00\n" + " 201.98,234.15 201.61,228.06 192.91,221.85\n" + " 187.58,218.04 176.56,216.51 170.00,215.41\n" + " 153.07,212.57 126.99,210.70 110.00,212.28\n" + " 101.11,213.56 88.05,213.25 81.18,219.39 Z"; Path parsePath = svgPathParser.parsePath(pathStr); System.out.println(".........parsePath:" + parsePath); } @Override public void onBackPressed() { super.onBackPressed(); } @BindView(R.id.flv_fly_line) FlyLineView mFlyLineView; @BindView(R.id.pc_path_copy) PathCopy mPathCopy; private void initPathCopy() { mPathCopy.setPath(mPathView.getPath()); } }
true
37c13910b4c2fb7ae5ff14a5f9b702c751277e2c
Java
azaat/unary-primes
/src/main/java/utils/WordUtils.java
UTF-8
8,601
2.75
3
[ "Apache-2.0" ]
permissive
package utils; import models.UnrestrictedGrammar; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import static converters.TmToUnrestrictedGrammar.BLANK; import static converters.TmToUnrestrictedGrammar.EPS; import static models.TuringMachine.*; import static models.UnrestrictedGrammar.GrammarSymbol; import static models.UnrestrictedGrammar.Production; public class WordUtils { public static class DerivationUnit { private final Production production; private final List<GrammarSymbol> sentence; public DerivationUnit(Production production, List<GrammarSymbol> sentence) { this.production = production; this.sentence = sentence; } public Production getProduction() { return production; } public List<GrammarSymbol> getSentence() { return sentence; } } public static final GrammarSymbol epsBlankSym = new GrammarSymbol("[" + EPS + "|" + BLANK + "]", false); public static boolean isWordHieroglyph(GrammarSymbol sym) { return sym.getValue().contains("[") && !sym.getValue().equals(epsBlankSym.getValue()); } public static Optional<List<DerivationUnit>> contains(UnrestrictedGrammar grammar, int n, Set<State> finalStates) { return contains(grammar, n, finalStates, false); } public static Optional<List<DerivationUnit>> contains( UnrestrictedGrammar grammar, int n, Set<State> finalStates, boolean needDerivation ) { List<Production> productions = grammar.getProductions().stream().sorted( Comparator.comparingInt(p -> p.getBody().size()) ).collect(Collectors.toList()); final class Node { final int depth; final List<GrammarSymbol> sentence; final List<DerivationUnit> derivation; Node( List<GrammarSymbol> sentence, int depth, List<DerivationUnit> derivation ) { this.sentence = sentence; this.depth = depth; this.derivation = derivation; } } // Getting max head length Optional<Integer> optMaxHead = productions.stream().map( p -> p.getHead().size() ).max(Comparator.naturalOrder()); LinkedList<Node> queue = new LinkedList<>(); Set<List<GrammarSymbol>> visited = new HashSet<>(); queue.add(new Node(List.of(grammar.getStartSymbol()), 0, new LinkedList<>())); while (!queue.isEmpty()) { Node node = queue.poll(); List<GrammarSymbol> sentence = node.sentence; boolean foundFinal = false; if (!needDerivation) { for (State finalState : finalStates) { Optional<Integer> optWordSize = getWordSizeIfHasFinal(sentence, productions, finalState); if (optWordSize.isPresent()) { int wordSize = optWordSize.get(); if (wordSize == n) { //System.out.println("Found match " + sentence + " len: " + sentence.size()); return Optional.of(node.derivation); } else if (wordSize > n) { //System.out.println("Did not find any match"); return Optional.empty(); } foundFinal = true; } } } if (!visited.contains(sentence)) { visited.add(sentence); if (foundFinal) { //System.out.println("Sent with final state " + sentence + " len: " + sentence.size()); // If we encountered sentence with final state we don't open it up further continue; } if (sentence.stream().filter( WordUtils::isWordHieroglyph ).count() > n) { // Encountered more than n hieroglyphs, should not open up further //System.out.println("Sent with more than n hieroglyphs, skipping.."); continue; } if (sentence.stream().allMatch( GrammarSymbol::isTerminal )) { // All terminals, generated word if (sentence.size() > n) return Optional.empty(); else if (sentence.size() == n) return Optional.of(node.derivation); //System.out.println("Generated " + sentence + " depth: " + node.depth); } for (int pos = 0; pos < sentence.size(); pos++) { int limit = optMaxHead.orElse(sentence.size() - pos); for (int partSize = 1; partSize <= Math.min(limit, sentence.size() - pos); partSize++) { // Checking all substrings from pos with partSize length as possible "children" // limiting substring size with max head length as optimization for (Production production : productions) { // Remove eps from head (since eps = empty sym) List<GrammarSymbol> headNoEps = new ArrayList<>(production.getHead()); headNoEps.removeIf( sym -> sym.getValue().equals(EPS) ); if (sentence.subList(pos, pos + partSize).equals(headNoEps) ) { List<GrammarSymbol> start = sentence.subList(0, pos); List<GrammarSymbol> end = sentence.subList(pos + partSize, sentence.size()); // Remove eps from body (since eps = empty sym) List<GrammarSymbol> bodyNoEps = new ArrayList<>(production.getBody()); bodyNoEps.removeIf( sym -> sym.getValue().equals(EPS) ); // Construct new sentence from chosen substring with current production // [pref] [new body] [suff] List<GrammarSymbol> newSentence = new LinkedList<>(start); newSentence.addAll(bodyNoEps); newSentence.addAll(end); queue.add(new Node( newSentence, node.depth + 1, Stream.concat(node.derivation.stream(), Stream.of(new DerivationUnit(production, newSentence))) .collect(Collectors.toList()) )); } } } } } } // Exited loop without returning, so we did not find accepting sentence return Optional.empty(); } private static Optional<Integer> getWordSizeIfHasFinal(List<GrammarSymbol> sentence, List<Production> productions, State finalState) { // Hacky optimization to accept word when encountered final state // without opening all the variables with BFS if (sentence.contains(new GrammarSymbol(finalState.getValue(), false))) { // Apply eps productions for (Production production : productions) { List<GrammarSymbol> head = production.getHead(); if ( head.size() == 1 && sentence.contains(head.get(0)) && production.getBody().size() == 1 && production.getBody().get(0).getValue().equals(EPS) ) { sentence.removeIf( grammarSymbol -> grammarSymbol.equals(head.get(0)) ); } } // Remove symbols generating into blanks sentence.removeIf( grammarSymbol -> grammarSymbol.equals(epsBlankSym) ); return Optional.of(sentence.size()); } else if (sentence.stream().anyMatch(s -> s.getValue().contains(finalState.getValue()))) { return Optional.of(sentence.size()); } else { return Optional.empty(); } } }
true
a9a7b8fec417a816423fbe03571c65be18434dfc
Java
TechnicianFreak/TecTech
/src/main/java/com/github/technus/tectech/loader/RecipeLoader.java
UTF-8
1,599
1.898438
2
[ "MIT" ]
permissive
package com.github.technus.tectech.loader; import com.github.technus.tectech.compatibility.dreamcraft.DreamCraftRecipeLoader; import com.github.technus.tectech.elementalMatter.definitions.complex.dAtomDefinition; import com.github.technus.tectech.thing.casing.TT_Container_Casings; import cpw.mods.fml.common.Loader; import gregtech.api.enums.Materials; import gregtech.api.enums.OrePrefixes; import gregtech.api.util.GT_OreDictUnificator; import gregtech.api.util.GT_Utility; import net.minecraft.item.ItemStack; import static gregtech.api.enums.GT_Values.RA; /** * Created by danie_000 on 16.11.2016. */ public class RecipeLoader implements Runnable { public void run() { dAtomDefinition.setTransformation(); // =================================================================================================== // Recipes init - common goes here rest goes into methods below // =================================================================================================== for(int i=0;i<=15;i++) RA.addAssemblerRecipe(new ItemStack[]{ GT_Utility.getIntegratedCircuit(i), GT_OreDictUnificator.get(OrePrefixes.dust,Materials.Cobalt,1)}, Materials.Aluminium.getMolten(864), new ItemStack(TT_Container_Casings.sHintCasingsTT, 1,i),32,120); if (Loader.isModLoaded("dreamcraft")) new DreamCraftRecipeLoader().run();//TODO init recipes for GTNH version else new BloodyRecipeLoader().run();//TODO init recipes for NON-GTNH version } }
true
5902864a516de882996fab7e6cc6ae0463d40035
Java
AndrewAK1619/CodeWars
/src/main/java/pl/example/CodeWars/Vowels.java
UTF-8
349
3.203125
3
[]
no_license
package pl.example.CodeWars; public class Vowels { public static int getCount(String str) { int vowelsCount = 0; vowelsCount = (int) str.chars() .filter(c -> c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') .count(); return vowelsCount; } public static void main(String[] args) { Vowels.getCount("abracadabra"); } }
true
919e116df55faba8437531a91ca37167d0c8fa22
Java
a-nuo/UnderstandingJVM
/src/chapter8/TestSlot8_2.java
UTF-8
350
2.46875
2
[]
no_license
package chapter8; /** * Full GC 内存未回收 ParOldGen: 65536K->65823K(174592K) * placeholder 原本所占用的Slot未被其他变量复用,这种关联违背打断 * @author a_nuo * */ public class TestSlot8_2 { public static void main(String[] args) { { byte[] placeholder = new byte[64 * 1024 * 1024]; } System.gc(); } }
true
a992992299c65f9b32d00fceaa5768bfe13743fc
Java
georgezeng/lhc2
/lhc2-server/src/main/java/net/geozen/lhc3/domain/base/PosBaseEntity.java
UTF-8
4,654
2.0625
2
[]
no_license
package net.geozen.lhc3.domain.base; import javax.persistence.MappedSuperclass; @MappedSuperclass public abstract class PosBaseEntity extends BaseEntity { public int getPos() { return pos; } public void setPos(int pos) { this.pos = pos; } public int getTotalColsYz() { return totalColsYz; } public void setTotalColsYz(int totalColsYz) { this.totalColsYz = totalColsYz; } public int getrColsYz() { return rColsYz; } public void setrColsYz(int rColsYz) { this.rColsYz = rColsYz; } public int getMaxColYz() { return maxColYz; } public void setMaxColYz(int maxColYz) { this.maxColYz = maxColYz; } public int getW1() { return w1; } public void setW1(int w1) { this.w1 = w1; } public int getW2() { return w2; } public void setW2(int w2) { this.w2 = w2; } public int getW3() { return w3; } public void setW3(int w3) { this.w3 = w3; } public int getW4() { return w4; } public void setW4(int w4) { this.w4 = w4; } public int getW5() { return w5; } public void setW5(int w5) { this.w5 = w5; } public int getW6() { return w6; } public void setW6(int w6) { this.w6 = w6; } public int getW7() { return w7; } public void setW7(int w7) { this.w7 = w7; } public int getW8() { return w8; } public void setW8(int w8) { this.w8 = w8; } public int getW9() { return w9; } public void setW9(int w9) { this.w9 = w9; } public int getW10() { return w10; } public void setW10(int w10) { this.w10 = w10; } public int getW11() { return w11; } public void setW11(int w11) { this.w11 = w11; } public int getW12() { return w12; } public void setW12(int w12) { this.w12 = w12; } public int getLt1() { return lt1; } public void setLt1(int lt1) { this.lt1 = lt1; } public int getLt2() { return lt2; } public void setLt2(int lt2) { this.lt2 = lt2; } public int getLt3() { return lt3; } public void setLt3(int lt3) { this.lt3 = lt3; } public int getLt4() { return lt4; } public void setLt4(int lt4) { this.lt4 = lt4; } public int getLt5() { return lt5; } public void setLt5(int lt5) { this.lt5 = lt5; } public int getLt6() { return lt6; } public void setLt6(int lt6) { this.lt6 = lt6; } public int getLt7() { return lt7; } public void setLt7(int lt7) { this.lt7 = lt7; } public int getLt8() { return lt8; } public void setLt8(int lt8) { this.lt8 = lt8; } public int getLt9() { return lt9; } public void setLt9(int lt9) { this.lt9 = lt9; } public int getLt10() { return lt10; } public void setLt10(int lt10) { this.lt10 = lt10; } public int getLt11() { return lt11; } public void setLt11(int lt11) { this.lt11 = lt11; } public int getLt12() { return lt12; } public void setLt12(int lt12) { this.lt12 = lt12; } public int getT1() { return t1; } public void setT1(int t1) { this.t1 = t1; } public int getT2() { return t2; } public void setT2(int t2) { this.t2 = t2; } public int getT3() { return t3; } public void setT3(int t3) { this.t3 = t3; } public int getT4() { return t4; } public void setT4(int t4) { this.t4 = t4; } public int getT5() { return t5; } public void setT5(int t5) { this.t5 = t5; } public int getT6() { return t6; } public void setT6(int t6) { this.t6 = t6; } public int getT7() { return t7; } public void setT7(int t7) { this.t7 = t7; } public int getT8() { return t8; } public void setT8(int t8) { this.t8 = t8; } public int getT9() { return t9; } public void setT9(int t9) { this.t9 = t9; } public int getT10() { return t10; } public void setT10(int t10) { this.t10 = t10; } public int getT11() { return t11; } public void setT11(int t11) { this.t11 = t11; } public int getT12() { return t12; } public void setT12(int t12) { this.t12 = t12; } private int pos; private int totalColsYz; // 所有列的遗值和 private int rColsYz; // 倒1-倒5 遗值和 private int maxColYz; // 同一行最大遗值和 private int w1; private int w2; private int w3; private int w4; private int w5; private int w6; private int w7; private int w8; private int w9; private int w10; private int w11; private int w12; private int lt1; private int lt2; private int lt3; private int lt4; private int lt5; private int lt6; private int lt7; private int lt8; private int lt9; private int lt10; private int lt11; private int lt12; private int t1; private int t2; private int t3; private int t4; private int t5; private int t6; private int t7; private int t8; private int t9; private int t10; private int t11; private int t12; }
true
3b329db531e8bd945870c4c23d95becdd4eca9d4
Java
XiaoFei-97/StudentManager
/src/com/jzfblog/service/StudentService.java
UTF-8
1,266
2.46875
2
[]
no_license
package com.jzfblog.service; import java.sql.SQLException; import java.util.List; import com.jzfblog.domain.PageBean; import com.jzfblog.domain.Student; /** * 这是学生的业务处理规则 * @author 蒋振飞 * */ public interface StudentService { /** * 查询当页的数据 * @param currentPage * @return * @throws SQLException */ PageBean findStudentPage(int currentPage) throws SQLException; /** * 查询所有学生 * @return List<Student> */ List<Student> findAll() throws SQLException; /** * 根据ID查询单个学生对象 * @param sid * @return * @throws SQLException */ Student findStudentById(int sid) throws SQLException; /** * 添加学生 * @param student * @throws SQLException */ void insert(Student student) throws SQLException; /** * 删除学生 * @param sid * @throws SQLException */ void delete(int sid) throws SQLException; /** * 更新学生信息 * @param student * @throws SQLException */ void update(Student student) throws SQLException; /** * 模糊查询 * @param sname 学生姓名 * @param gender 学生性别 * @return 学生 * @throws SQLException */ List<Student> searchStudent(String sname, String gender) throws SQLException; }
true
feca44d7a6077c8da08857162e5a00fada580733
Java
nissim490/The-Library-System
/src/common/Functions.java
UTF-8
7,298
2.390625
2
[]
no_license
package common; import java.awt.Desktop; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.sql.ResultSet; import java.text.DateFormat; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.*; import java.text.SimpleDateFormat; //import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException; import ClientPack.MainClientApp; //import sun.print.resources.serviceui; public class Functions { final static String DATE_FORMAT = "dd-MM-yyyy"; public static Integer lock = 1; public static ArrayList<String> msg = null; public static MyFile msgFile = null; public static boolean isNumeric(String str) { try { double d = Double.parseDouble(str); } catch(NumberFormatException nfe) { return false; } return true; } public static boolean Checkid(String id) throws Exception { int sum, bikoret; if(id.length()==9) { sum = idVerification(id); bikoret = Character.getNumericValue(id.charAt(8)); if((sum+bikoret)%10==0) { return true; } else { throw new Exception("The ID is ilegal!!"); } } else { throw new Exception("An Israeli ID must contain 9 numbers. "); } } public static int idVerification(String id) { String a; int sum=0, i, j, num; for(i=0; i<8; i++) { if(i==0 || i%2==0) { num = Character.getNumericValue(id.charAt(i)); sum = sum+num; } else { num = Character.getNumericValue(id.charAt(i)); if((num*2)>10) { a = Integer.toString(num*2); for(j=0; j<2; j++) { num = Character.getNumericValue(a.charAt(j)); sum = sum+num; } } else sum = sum+(num*2); } } return sum; } public static boolean validateJavaDate(String strDate) throws Exception { /* Check if date is 'null' */ if (strDate.trim().equals("")) { return true; } /* Date is not 'null' */ else { /* * Set preferred date format, * For example MM-dd-yyyy, MM.dd.yyyy,dd.MM.yyyy etc.*/ SimpleDateFormat sdfrmt = new SimpleDateFormat("MM/dd/yyyy"); sdfrmt.setLenient(false); /* Create Date object * parse the string into date */ try { Date javaDate = sdfrmt.parse(strDate); } /* Date format is invalid */ catch (Exception e) { throw new Exception("Date"+" is Invalid Date format"); } /* Return true if date format is valid */ return true; } } public static ArrayList<ArrayList<String>> askFromDB(String sql , ArrayList<String> key,ArrayList<String> askForResult) { Thread t = new Thread(new Runnable() { @Override public void run() { synchronized (lock) { if(sql.toUpperCase().contains("SELECT")) { key.add(0, "AskForResult"); key.add(1, sql); ArrayList<String> str = new ArrayList<String>(); str.addAll(key); str.add("###"); str.addAll(askForResult); MainClientApp.ClientOfLibrary.handleMessageFromClientUI(str); try { lock.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else try { throw new Exception("try to get a result from d.b without select"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); t.start(); try { t.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } ArrayList<ArrayList<String>> ReturnList = new ArrayList<ArrayList<String>>(); ArrayList<String> perRun = new ArrayList<String>(); for(int i =0; i < msg.size();i++){ if(!msg.get(i).equals("#"))perRun.add(msg.get(i)); else { System.out.println("temp:"+perRun); ArrayList<String> temp = new ArrayList<String>(); temp.addAll(perRun); ReturnList.add(temp); perRun.clear(); } } System.out.println(ReturnList); return ReturnList; } public static void askFromFILE(String URL){ Thread t = new Thread(new Runnable() { @Override public void run() { synchronized (lock) { ArrayList<String> str = new ArrayList<String>(); str.add(0, "AskForFile"); str.add(1, URL); MainClientApp.ClientOfLibrary.handleMessageFromClientUI(str); } } }); t.start(); try { t.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void UplodeFILE(File file){ Thread t = new Thread(new Runnable() { @Override public void run() { synchronized (lock) { String url = file.getPath(); String lastWord = url.substring(url.lastIndexOf("\\")+1); System.out.println(lastWord); MyFile file= new MyFile(lastWord); String LocalfilePath=url; try{ File newFile = new File (LocalfilePath); byte [] mybytearray = new byte [(int)newFile.length()]; FileInputStream fis = new FileInputStream(newFile); BufferedInputStream bis = new BufferedInputStream(fis); file.initArray(mybytearray.length); file.setSize(mybytearray.length); bis.read(file.getMybytearray(),0,mybytearray.length); MainClientApp.ClientOfLibrary.handleMessageFromClientUI(file); } catch (Exception e) { System.out.println("Error send (Files)msg) to Server"); } } } }); t.start(); try { t.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void askFromDB(String sql , ArrayList<String> key){ Thread t = new Thread(new Runnable() { @Override public void run() { synchronized (lock) { key.add(0, "AskForUpdate"); key.add(1, sql); ArrayList<String> str = new ArrayList<String>(); str.addAll(key); MainClientApp.ClientOfLibrary.handleMessageFromClientUI(str); } } }); t.start(); try { t.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
090e9d5416bf04ef10cb6fb6079695fc9725066d
Java
Pkenandi/PFE2021
/Spring-backend/Springbackend/src/main/java/com/dravicenne/backend/services/UserService.java
UTF-8
10,766
2.25
2
[]
no_license
package com.dravicenne.backend.services; import com.dravicenne.backend.models.*; import com.dravicenne.backend.models.dto.*; import com.dravicenne.backend.models.exception.NotFoundException; import com.dravicenne.backend.models.exception.RdvAlreadyTaken; import com.dravicenne.backend.models.plaindto.PlainDossierDto; import com.dravicenne.backend.models.plaindto.PlainRendezVousDto; import com.dravicenne.backend.repositories.MedecinRepository; import com.dravicenne.backend.repositories.PatientRepository; import com.dravicenne.backend.repositories.UserRepository; import lombok.AllArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; @Service @AllArgsConstructor @Transactional public class UserService { private final UserRepository userRepository; private final MedecinRepository medecinRepository; private final PatientRepository patientRepository; private final RendezVousService rendezVousService; private final DossierService dossierService; private final AgendaService agendaService; // Users public void SaveUser(User user) { this.userRepository.save(user); } public List<User> getAllUser() { return this.userRepository.findAll(); } public User findUserByEmail(String email) { return this.userRepository.findUserByEmail(email); } public User findUserByPassword(String password) { return this.userRepository.findUserByPassword(password); } public User findById(Long id){ return this.userRepository.findById(id) .orElseThrow(() -> new NotFoundException(" User not found !")); } // Medecins public List<Medecin> findAllMedecins() { return this.medecinRepository.findAll(); } public Medecin findMedecinByCinAndPassword(String cin, String password) { return this.medecinRepository.findMedecinByCinAndPassword(cin,password); } public Medecin findMedecinByCin(String cin) { return this.medecinRepository.findMedecinBycin(cin); } public Medecin findByEmail(String email){ return this.medecinRepository.findByEmail(email); } public void resetPassword(ResetPasswordDto resetPasswordDto, String cin){ this.medecinRepository.resetPassword(resetPasswordDto.getPassword(),resetPasswordDto.getCpassword(),cin); } public List<Medecin> findMedecinByNom(String nom){ return this.medecinRepository.findMedecinByNom(nom); } public Medecin updateMedecin(Medecin medecin, String cin){ Medecin medToUpdate = this.medecinRepository.findMedecinBycin(cin); if(medToUpdate != null){ medToUpdate.setCin(medecin.getCin()); medToUpdate.setSpecialite(medecin.getSpecialite()); medToUpdate.setNom(medecin.getNom()); medToUpdate.setPrenom(medecin.getPrenom()); medToUpdate.setVille(medecin.getVille()); medToUpdate.setPhone(medecin.getPhone()); medToUpdate.setPassword(medecin.getPassword()); medToUpdate.setCpassword(medecin.getPassword()); medToUpdate.setEmail(medecin.getEmail()); return this.medecinRepository.save(medToUpdate); } return null; } public List<Medecin> findMedecinBySpecialite(String specialite) { return this.medecinRepository.findMedecinBySpecialite(specialite); } public Medecin setProfileMedecin(String picture, String cin){ Medecin medecin = this.findMedecinByCin(cin); if(Objects.nonNull(medecin)){ this.medecinRepository.setProfilePicture(picture, cin); return medecin; }else { return null; } } public Medecin removeProfilePicture(String cin){ Medecin medecin = this.findMedecinByCin(cin); medecin.setPicture(null); return medecin; } public Medecin connectToRendezVous(String cin, Long rdvId){ Medecin medecin = this.medecinRepository.findMedecinBycin(cin); RendezVous rendezVous = this.rendezVousService.findById(rdvId); if(Objects.nonNull(rendezVous.getMedecin())){ throw new RdvAlreadyTaken(rdvId, rendezVous.getMedecin().getCin()); }else{ medecin.connectToRendezVous(rendezVous); rendezVous.setMedecin(medecin); return medecin; } } public Medecin connectToDossier(String cin, Long dossier_id){ Medecin medecin = this.medecinRepository.findMedecinBycin(cin); DossierMedical dossierMedical = this.dossierService.findById(dossier_id); medecin.connectToDossier(dossierMedical); dossierMedical.setMedecin(medecin); return medecin; } public Medecin addAgenda(String cin, Long id){ Medecin medecin = this.medecinRepository.findMedecinBycin(cin); Agenda agenda = this.agendaService.findById(id); if(Objects.nonNull(agenda.getMedecin())){ throw new NotFoundException(" Agenda already taken "); }else{ medecin.setAgenda(agenda); agenda.setMedecin(medecin); return medecin; } } public Medecin removeAgenda(String cin, Long id){ Medecin medecin = this.medecinRepository.findMedecinBycin(cin); Agenda agenda = this.agendaService.findById(id); medecin.setAgenda(null); this.agendaService.deleteAgenda(id); return medecin; } // Patients public Patient findPatientByUsername(String username) { return this.patientRepository.findPatientByUsername(username); } public Patient findPatientByUsernameAndPassword(String username, String password) { return this.patientRepository.findPatientByUsernameAndPassword(username,password); } public List<Patient> findAllPatients() { return this.patientRepository.findAll(); } public Patient updatePatient(Patient patient, String username) { Patient newPatient = this.patientRepository.findPatientByUsername(username); if(newPatient != null) { newPatient.setAge(patient.getAge()); newPatient.setNom(patient.getNom()); newPatient.setPrenom(patient.getPrenom()); newPatient.setUsername(patient.getUsername()); newPatient.setGroupeSang(patient.getGroupeSang()); newPatient.setVille(patient.getVille()); newPatient.setPhone(patient.getPhone()); newPatient.setPassword(patient.getPassword()); newPatient.setCpassword(patient.getPassword()); newPatient.setDateNaiss(patient.getDateNaiss()); newPatient.setEmail(patient.getEmail()); return this.patientRepository.save(newPatient); } return null; } public Patient deletePatientByUsername(String username) { Patient patient = this.patientRepository.findPatientByUsername(username); if(patient == null) { throw new NotFoundException(" Patient not found"); }else { this.patientRepository.delete(patient); return patient; } } public Patient addRendezVous(String username, Long RdvId){ Patient patient = this.patientRepository.findPatientByUsername(username); RendezVous rendezVous = this.rendezVousService.findById(RdvId); if(Objects.nonNull(rendezVous.getPatient())) { throw new RdvAlreadyTaken(RdvId,rendezVous.getPatient().getUsername()); }else{ patient.addRendezVous(rendezVous); rendezVous.setPatient(patient); return patient; } } public Patient findByPatientEmail(final String email){ return this.patientRepository.findByEmail(email); } public void resetPatientPassword(ResetPasswordDto resetPasswordDto, String username){ this.patientRepository.resetPassword(resetPasswordDto.getPassword(),resetPasswordDto.getCpassword(),username); } public Patient setProfilePatient(String picture, String username){ Patient patient = this.findPatientByUsername(username); if(Objects.nonNull(patient)){ this.patientRepository.setProfilePicture(picture, username); return patient; }else{ return null; } } public Patient removeProfilePatient(String username){ Patient patient = this.findPatientByUsername(username); patient.setPicture(null); return patient; } public Patient deleteRendezVous(String username, Long RdvId){ Patient patient = this.patientRepository.findPatientByUsername(username); RendezVous rendezVous = this.rendezVousService.findById(RdvId); if(patient == null) { throw new NotFoundException(" Patient not found !"); }else { patient.removeRendezVous(rendezVous); return patient; } } public Patient addDossierMedical(String username, Long dossierId) { Patient patient = this.patientRepository.findPatientByUsername(username); DossierMedical dossierMedical = this.dossierService.findById(dossierId); if(Objects.nonNull(dossierMedical.getPatient())){ throw new NotFoundException(" Dossier already taken "); }else{ patient.setDossierMedical(dossierMedical); dossierMedical.setPatient(patient); return patient; } } public Patient deleteDossierMedical(String username, Long id){ Patient patient = this.patientRepository.findPatientByUsername(username); DossierMedical dossierMedical = this.dossierService.findById(id); if(Objects.nonNull(dossierMedical.getPatient())){ throw new NotFoundException(" Dossier not found "); }else{ patient.setDossierMedical(null); this.dossierService.disablePatientId(id); return patient; } } public Patient findPatientWithRdv(String username) { Patient patient = this.patientRepository.findPatientByUsername(username); if(patient != null){ if(patient.getRendezVousList().isEmpty()){ return null; }else{ return patient; } } return null; } public Patient findByDossierId(Long id){ return this.patientRepository.findByDossierMedicalId(id); } }
true
4580be0b8a5d9b2847d5aff7ea7cee6ee0882f14
Java
castrofernando/01-Java_JPA_Hibernate
/src/br/com/entity/Autor.java
UTF-8
2,412
2.28125
2
[]
no_license
package br.com.entity; import java.util.Calendar; import java.util.List; import javax.persistence.CascadeType; 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.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @Table(name = "TB_AUTOR") @SequenceGenerator(allocationSize = 1, name = "seqAutor", sequenceName = "SQ_AUTOR") public class Autor { @Id @Column(name = "id") @GeneratedValue(generator = "seqAutor", strategy = GenerationType.SEQUENCE) private int codigo; @Column(name = "nome", nullable = false, length = 300) private String nome; @Column(name = "sexo", nullable = false) private Sexo sexo; @Column(name = "sobrenome", nullable = false, length = 300) private String sobrenome; @Column(name = "dt_nascimento") @Temporal(TemporalType.DATE) private Calendar dataNascimento; @ManyToMany(cascade=CascadeType.PERSIST, fetch=FetchType.LAZY) @JoinTable(name = "TB_AUTOR_LIVRO", joinColumns = { @JoinColumn(name = "AUTOR_id") }, inverseJoinColumns = { @JoinColumn(name = "LIVRO_isnb") }) private List<Livro> livros; public Autor(String nome, Sexo sexo, String sobrenome, Calendar dataNascimento) { super(); this.nome = nome; this.sexo = sexo; this.sobrenome = sobrenome; this.dataNascimento = dataNascimento; } public Autor() { super(); } public int getCodigo() { return codigo; } public void setCodigo(int id) { this.codigo = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public Sexo getSexo() { return sexo; } public void setSexo(Sexo sexo) { this.sexo = sexo; } public String getSobrenome() { return sobrenome; } public void setSobrenome(String sobrenome) { this.sobrenome = sobrenome; } public Calendar getDataNascimento() { return dataNascimento; } public void setDataNascimento(Calendar dataNascimento) { this.dataNascimento = dataNascimento; } public List<Livro> getLivros() { return livros; } public void setLivros(List<Livro> livros) { this.livros = livros; } }
true
d5a50d5010a8d35c2cbf2fd880fc274c2fe5f723
Java
daweedek2/efhomework
/src/test/java/com/kostka/efhomework/service/validation/revokedPermissionService/CheckGroupWithParentRevokedPermissionsIntegrationTest.java
UTF-8
7,845
2.265625
2
[]
no_license
package com.kostka.efhomework.service.validation.revokedPermissionService; import com.kostka.efhomework.EfHomeworkApplication; import com.kostka.efhomework.entity.Group; import com.kostka.efhomework.entity.Permission; import com.kostka.efhomework.exception.NoPermissionException; import com.kostka.efhomework.service.management.register.GroupService; import com.kostka.efhomework.service.management.register.PermissionService; import com.kostka.efhomework.service.management.register.UserService; import com.kostka.efhomework.service.validation.RevokedPermissionService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.transaction.Transactional; import java.util.HashSet; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(classes = EfHomeworkApplication.class) @Transactional public class CheckGroupWithParentRevokedPermissionsIntegrationTest { private static final String TEST_PERMISSION_1 = "VIEW_DETAIL"; private static final String TEST_PERMISSION_2 = "CREATE_DETAIL"; private static final String TEST_NAME_1 = "ALPHA"; private static final String TEST_NAME_2 = "BETA"; private static final String TEST_NAME_3 = "GAMA"; private static final String TEST_NAME_4 = "DELTA"; @Autowired private PermissionService permissionService; @Autowired private GroupService groupService; @Autowired private UserService userService; @Autowired private RevokedPermissionService revokedPermissionService; // Testing presence of Revoked permission for Group with Parent Group @Test public void verifyRevokedPermissionIsPresentInGroupWithParentIntegrationTest() { Permission permission1 = permissionService.createPermission(TEST_PERMISSION_1); Permission permission2 = permissionService.createPermission(TEST_PERMISSION_2); Set<Permission> permissionSet = new HashSet<>(); permissionSet.add(permission1); permissionSet.add(permission2); Group group = groupService.createGroup(TEST_NAME_1); Group parentGroup = groupService.createGroup(TEST_NAME_2); Set<Group> parentGroupSet = new HashSet<>(); parentGroupSet.add(parentGroup); group.setRevokedPermissions(permissionSet); group.setParentGroups(parentGroupSet); Exception e = assertThrows(NoPermissionException.class, () -> { revokedPermissionService.checkPermissionRevokedForGroup(permission1, group); }); assertTrue(e.getMessage().contains("Permission '" + TEST_PERMISSION_1 + "' is revoked.")); } @Test public void verifyRevokedPermissionIsPresentInParentGroupIntegrationTest() { Permission permission1 = permissionService.createPermission(TEST_PERMISSION_1); Permission permission2 = permissionService.createPermission(TEST_PERMISSION_2); Set<Permission> permissionSet = new HashSet<>(); permissionSet.add(permission1); permissionSet.add(permission2); Group group = groupService.createGroup(TEST_NAME_1); Group parentGroup = groupService.createGroup(TEST_NAME_2); Set<Group> parentGroupSet = new HashSet<>(); parentGroupSet.add(parentGroup); parentGroup.setRevokedPermissions(permissionSet); group.setParentGroups(parentGroupSet); Exception e = assertThrows(NoPermissionException.class, () -> { revokedPermissionService.checkPermissionRevokedForGroup(permission1, group); }); assertTrue(e.getMessage().contains("Permission '" + TEST_PERMISSION_1 + "' is revoked.")); } // Testing presence of Revoked permission for Group with Parent Group with grand-parent group @Test public void verifyRevokedPermissionIsPresentInGrandParentGroupIntegrationTest() { Permission permission1 = permissionService.createPermission(TEST_PERMISSION_1); Permission permission2 = permissionService.createPermission(TEST_PERMISSION_2); Set<Permission> permissionSet = new HashSet<>(); permissionSet.add(permission1); permissionSet.add(permission2); Group group = groupService.createGroup(TEST_NAME_1); Group parentGroup = groupService.createGroup(TEST_NAME_2); Set<Group> parentGroupSet = new HashSet<>(); parentGroupSet.add(parentGroup); Group grandParentGroup = groupService.createGroup(TEST_NAME_3); Set<Group> grandParentGroupSet = new HashSet<>(); grandParentGroupSet.add(grandParentGroup); grandParentGroup.setRevokedPermissions(permissionSet); group.setParentGroups(parentGroupSet); parentGroup.setParentGroups(grandParentGroupSet); Exception e = assertThrows(NoPermissionException.class, () -> { revokedPermissionService.checkPermissionRevokedForGroup(permission1, group); }); assertTrue(e.getMessage().contains("Permission '" + TEST_PERMISSION_1 + "' is revoked.")); } @Test public void verifyRevokedPermissionIsPresentInParentGroupWithGrandParentGroupIntegrationTest() { Permission permission1 = permissionService.createPermission(TEST_PERMISSION_1); Permission permission2 = permissionService.createPermission(TEST_PERMISSION_2); Set<Permission> permissionSet = new HashSet<>(); permissionSet.add(permission1); permissionSet.add(permission2); Group group = groupService.createGroup(TEST_NAME_1); Group parentGroup = groupService.createGroup(TEST_NAME_2); Group grandParentGroup = groupService.createGroup(TEST_NAME_3); Set<Group> parentGroupSet = new HashSet<>(); parentGroupSet.add(parentGroup); Set<Group> granParentGroupSet = new HashSet<>(); granParentGroupSet.add(grandParentGroup); parentGroup.setRevokedPermissions(permissionSet); group.setParentGroups(parentGroupSet); parentGroup.setParentGroups(granParentGroupSet); Exception e = assertThrows(NoPermissionException.class, () -> { revokedPermissionService.checkPermissionRevokedForGroup(permission1, group); }); assertTrue(e.getMessage().contains("Permission '" + TEST_PERMISSION_1 + "' is revoked.")); } @Test public void verifyRevokedPermissionIsPresentInParentGroupAndChildGroupIntegrationTest() { Permission permission1 = permissionService.createPermission(TEST_PERMISSION_1); Permission permission2 = permissionService.createPermission(TEST_PERMISSION_2); Set<Permission> permissionSet = new HashSet<>(); permissionSet.add(permission1); permissionSet.add(permission2); Group group = groupService.createGroup(TEST_NAME_1); Group parentGroup = groupService.createGroup(TEST_NAME_2); Group grandParentGroup = groupService.createGroup(TEST_NAME_3); Set<Group> parentGroupSet = new HashSet<>(); parentGroupSet.add(parentGroup); Set<Group> grandParentGroupSet = new HashSet<>(); grandParentGroupSet.add(grandParentGroup); parentGroup.setRevokedPermissions(permissionSet); group.setRevokedPermissions(permissionSet); group.setParentGroups(parentGroupSet); parentGroup.setParentGroups(grandParentGroupSet); Exception e = assertThrows(NoPermissionException.class, () -> { revokedPermissionService.checkPermissionRevokedForGroup(permission1, group); }); assertTrue(e.getMessage().contains("Permission '" + TEST_PERMISSION_1 + "' is revoked.")); } }
true
213da224aa570039e0fba54b5514820c2402dee3
Java
jon23lam/LAMONIA
/src/Entities/WildCard.java
UTF-8
613
3.046875
3
[]
no_license
package Entities; public class WildCard implements Card{ private int id; private Colors colors; public WildCard(int id, Colors colors){ this.id = id; this.colors = colors; } @Override public Type getType() { return Type.WildCard; } @Override public int getId() { return id; } public Colors getColors(){ return colors; } public enum Colors{ RED_BLUE, BLUE_PINK, PINK_PURPLE, PURPLE_GREEN, GREEN_YELLOW, YELLOW_ORANGE, ORANGE_BROWN, BROWN_RED } }
true
9afdf9d540ec6cf1073169258c97c08718266c75
Java
zhuolikevin/leetcode-java
/238.product-of-array-except-self.107574757.ac.java
UTF-8
885
3.46875
3
[]
no_license
/* * [238] Product of Array Except Self * * https://leetcode.com/problems/product-of-array-except-self * * Medium (48.69%) * Total Accepted: * Total Submissions: * Testcase Example: '[0,0]' * * Can you solve this problem? 🤔 */ public class Solution { public int[] productExceptSelf(int[] nums) { int len = nums.length; if (len == 0) { return nums; } int[] output = new int[len]; output[0] = nums[0]; for (int i = 1; i < len; i++) { output[i] = output[i-1] * nums[i]; } int curRightProd = 1; for (int i = len - 1; i > 0; i--) { int curLeftProd = output[i-1]; output[i] = curLeftProd * curRightProd; curRightProd *= nums[i]; } output[0] = curRightProd; return output; } }
true
0b6ef87022b8a29f770fa9ab3d2aa01671b4fb3a
Java
Arp87Galaxy/Ink
/Ink/ink/ink-core/src/main/java/com/arpgalaxy/ink/core/controller/LogViewController.java
UTF-8
2,207
2.046875
2
[]
no_license
package com.arpgalaxy.ink.core.controller; import java.util.Arrays; import java.util.Map; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.arpgalaxy.ink.core.entity.LogViewEntity; import com.arpgalaxy.ink.core.service.LogViewService; import com.arpgalaxy.ink.common.utils.PageUtils; import com.arpgalaxy.ink.common.utils.response.R; /** * 阅读日志 * * @author arpgalaxy * @email 13605560342@163.com * @date 2020-09-05 14:47:37 */ @RestController @RequestMapping("core/logview") public class LogViewController { @Autowired private LogViewService logViewService; /** * 列表 */ @RequestMapping("/list") @RequiresPermissions("core:logview:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = logViewService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") @RequiresPermissions("core:logview:info") public R info(@PathVariable("id") Long id){ LogViewEntity logView = logViewService.getById(id); return R.ok().put("logView", logView); } /** * 保存 */ @RequestMapping("/save") @RequiresPermissions("core:logview:save") public R save(@RequestBody LogViewEntity logView){ logViewService.save(logView); return R.ok(); } /** * 修改 */ @RequestMapping("/update") @RequiresPermissions("core:logview:update") public R update(@RequestBody LogViewEntity logView){ logViewService.updateById(logView); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") @RequiresPermissions("core:logview:delete") public R delete(@RequestBody Long[] ids){ logViewService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
true
abe1d4425c385349de6db5ced0d1564b2f271ee5
Java
Morishita1/Collections_03
/src/com/biz/coll/list/List_03.java
UTF-8
699
3.5625
4
[]
no_license
package com.biz.coll.list; import java.util.LinkedList; import java.util.List; import java.util.Random; public class List_03 { public static void main(String[] args) { Random rnd=new Random(); List<Integer> intList=new LinkedList<Integer>(); for(int i=0;i<50;i++) { int intR=rnd.nextInt(50); // 0부터 49까지 임의 수 생성 intList.add(intR); // 리스트에 추가 } // intList에 30이 포함되어 있는지 확이 int intLen=intList.size(); for(int i=0;i<intLen;i++) { if(intList.get(i)==30) { System.out.println("찾았습니다"); } } for(Integer i:intList) { if(i==30) { System.out.println("찾았습니다"); } } } }
true
d8f936fde8f43dffea89e65de6dcb6db49edeb58
Java
simeonpilgrim/nikon-firmware-tools
/Java/Emulator/src/main/com/nikonhacker/gui/component/breakTrigger/SyscallBreakTriggerCreateDialog.java
UTF-8
7,234
2.296875
2
[]
no_license
package com.nikonhacker.gui.component.breakTrigger; import com.nikonhacker.Format; import com.nikonhacker.disassembly.ParsingException; import com.nikonhacker.disassembly.Symbol; import com.nikonhacker.disassembly.fr.FrCPUState; import com.nikonhacker.disassembly.fr.Syscall; import com.nikonhacker.emu.memory.Memory; import com.nikonhacker.emu.trigger.BreakTrigger; import org.apache.commons.lang3.StringUtils; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.*; import java.util.List; public class SyscallBreakTriggerCreateDialog extends JDialog implements ActionListener { private final BreakTrigger trigger; private final List<JLabel> labels = new ArrayList<JLabel>(); private final List<JTextField> values = new ArrayList<JTextField>(); private final JComboBox syscallCombo = new JComboBox(); private List<Syscall> syscallList = null; public SyscallBreakTriggerCreateDialog(JDialog owner, BreakTrigger trigger, String title, Memory memory) { super(owner, title, true); this.trigger = trigger; JPanel mainPanel = new JPanel(new BorderLayout()); JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); JPanel editPanel = new JPanel(new GridLayout(17, 2)); JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); mainPanel.add(topPanel, BorderLayout.NORTH); mainPanel.add(editPanel, BorderLayout.CENTER); mainPanel.add(bottomPanel, BorderLayout.SOUTH); try { syscallList = new ArrayList<Syscall>(); syscallList.addAll(Syscall.getMap(memory).values()); Collections.sort(syscallList, new Comparator<Syscall>() { public int compare(Syscall o1, Syscall o2) { return o1.getName().compareTo(o2.getName()); } }); topPanel.add(new JLabel("System call:")); Vector<String> syscallNames = new Vector<String>(); for (Syscall syscall : syscallList) { syscallNames.add(syscall.getName()); } syscallCombo.setModel(new DefaultComboBoxModel(syscallNames.toArray())); syscallCombo.setMaximumRowCount(15); syscallCombo.addActionListener(this); topPanel.add(syscallCombo); for (int i = 0; i < 17; i++) { JLabel label = new JLabel(); labels.add(label); editPanel.add(label); JTextField field = new JTextField(); values.add(field); editPanel.add(field); } refreshParams(); JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { save(); } }); bottomPanel.add(okButton); } catch (ParsingException e) { topPanel.add(new JLabel("Error parsing syscall definition file")); } JButton okButton = new JButton("Cancel"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); bottomPanel.add(okButton); setContentPane(mainPanel); pack(); setLocationRelativeTo(null); } public void actionPerformed(ActionEvent e) { refreshParams(); } public void refreshParams() { int selectedIndex = syscallCombo.getSelectedIndex(); Syscall syscall = syscallList.get(selectedIndex); List<Symbol.Parameter> parameterList = syscall.getParameterList(); Map<Integer,String> inParameterMap = new HashMap<Integer, String>(); if (parameterList != null) { for (Symbol.Parameter parameter : parameterList) { if (StringUtils.isNotBlank(parameter.getInVariableName())) { inParameterMap.put(parameter.getRegister(), parameter.getInVariableName()); } } } for (int i = 0; i < 16; i++) { if (i == 12) { labels.get(i).setText("R12 - Function Code"); labels.get(i).setEnabled(false); values.get(i).setText(Format.asHex(syscall.getFunctionCode(), 8)); values.get(i).setEnabled(false); } else { if (inParameterMap.containsKey(i)) { labels.get(i).setText("R" + i + " - " + inParameterMap.get(i)); labels.get(i).setVisible(true); values.get(i).setVisible(true); } else { labels.get(i).setVisible(false); values.get(i).setVisible(false); values.get(i).setText(""); } } } labels.get(16).setText("PC"); labels.get(16).setEnabled(false); values.get(16).setText(Format.asHex(Syscall.getInt40address(), 8)); values.get(16).setEnabled(false); } private void save() { FrCPUState cpuStateFlags = new FrCPUState(); FrCPUState cpuStateValues = new FrCPUState(); cpuStateFlags.clear(); int selectedIndex = syscallCombo.getSelectedIndex(); Syscall syscall = syscallList.get(selectedIndex); String triggerName = syscall.getName() +"("; List<Symbol.Parameter> parameterList = syscall.getParameterList(); Map<Integer,String> inParameterMap = new HashMap<Integer, String>(); if (parameterList != null) { for (Symbol.Parameter parameter : parameterList) { if (StringUtils.isNotBlank(parameter.getInVariableName())) { inParameterMap.put(parameter.getRegister(), parameter.getInVariableName()); } } } for (int i = 0; i < 16; i++) { if (i == 12) { cpuStateFlags.setReg(12, 0xFFFFFFFF); cpuStateValues.setReg(12, syscall.getFunctionCode()); } else { if (inParameterMap.containsKey(i) && StringUtils.isNotBlank(values.get(i).getText())) { cpuStateFlags.setReg(i, 0xFFFFFFFF); int value = Format.parseIntHexField(values.get(i)); cpuStateValues.setReg(i, value); if (!triggerName.endsWith("(")) { triggerName += ", "; } triggerName += inParameterMap.get(i) + "=0x" + Format.asHex(value, 8); } } } cpuStateFlags.pc = 0xFFFFFFFF; cpuStateValues.pc = Syscall.getInt40address(); trigger.setCpuStateFlags(cpuStateFlags); trigger.setCpuStateValues(cpuStateValues); trigger.setName(triggerName + ")"); dispose(); } }
true
98016242de3df38ad1bf14fbc6b0c524f7b3bfb6
Java
mdebeljuh/njp-helloworld
/src/main/java/hr/vsite/njp/proverbs/domain/ProverbsManagerImpl.java
UTF-8
5,681
2.265625
2
[]
no_license
package hr.vsite.njp.proverbs.domain; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.interceptor.TransactionAspectSupport; import javax.persistence.EntityManager; import java.util.List; import java.util.Optional; @Service @Transactional(readOnly = true) public class ProverbsManagerImpl implements ProverbsManager { private final static Logger LOGGER = LoggerFactory.getLogger(ProverbsManagerImpl.class); private final ProverbsRepository proverbsRepository; private final ProverbMapper proverbMapper; private final EntityManager entityManager; public ProverbsManagerImpl(ProverbsRepository proverbsRepository, ProverbMapper proverbMapper, EntityManager entityManager) { this.proverbsRepository = proverbsRepository; this.proverbMapper = proverbMapper; this.entityManager = entityManager; } @Override public List<ProverbDTO> findAll() { return proverbMapper.toProverbDTO(proverbsRepository .findAll()); /*Iterable<Proverb> proverbs = proverbsRepository.findAll(); Iterator<Proverb> proverbsIterator = proverbs.iterator(); List<ProverbDTO> proverbDTOS = new LinkedList<>(); for (Proverb proverb : proverbs) { // while (proverbs.hasNext()){ // Proverb proverb = proverbs.next(); ProverbDTO proverbDTO = new ProverbDTO(proverb.getId(), proverb.getProverb()); proverbDTOS.add(proverbDTO); } return proverbDTOS; // return null;*/ } @Override // @Transactional(readOnly = true) // (2) isto kao da i nema aktivne transakcije @Transactional() // (1) aktivne transakcije public Optional<ProverbDTO> findOne(Long id) { // proverbsRepository.findByProverbContainsOrIdGreaterThan("aa", (long) 12); // return proverbsRepository.findById(id).map(proverbMapper::toProverbDTO); Optional<Proverb> proverbOptional = proverbsRepository.findById(id); // Proverb p = proverbOptional.get(); //// entityManager.detach(p); // p.setProverb("Read modified2"); // ako su aktivne transakcije i // ako nije napravljen detach tada ce se i ovo spremiti return proverbOptional.map(proverbMapper::toProverbDTO); // Optional<Proverb> proverb = proverbsRepository.findById(id); // Optional<ProverbDTO> proverbDTO = proverb.map(prov -> new ProverbDTO(prov.getId(), prov.getProverb())); // return proverbDTO; // return proverbsRepository.findById(id) // .map(p->new ProverbDTO(p.getId(), p.getProverb())) // .orElse(null); } @Override @Transactional( // propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class ) public void save(ProverbDTO proverbDto) throws Exception { // Proverb proverb = new Proverb(); // proverb.setId(proverbDto.getId()); // proverb.setProverb(proverbDto.getProverb()); Proverb converted = proverbMapper.fromProverbDTO(proverbDto); Proverb pFromSaved = proverbsRepository.save(converted); converted.setProverb("Converted Proverb"); //nece se spremiti jer nije povezano na entity managera pFromSaved.setProverb("From saved proverb"); // ova promjena ce se spremiti if (proverbDto.getId() != null) { Optional<Proverb> drugi = proverbsRepository.findById(1L); if (drugi.isPresent()) { Proverb p2 = drugi.get(); p2.setProverb("also changed"); // i ovo ce se spremiti jer entiti manager prati tu instancu } } saveNewInternal(); // entityManager.flush(); LOGGER.info("Done saving"); //rollback TransactionStatus transactionStatus = TransactionAspectSupport.currentTransactionStatus(); if (pFromSaved.getId()>2){ // transactionStatus.setRollbackOnly(); LOGGER.info("Rollback"); throw new RuntimeException(); } // throw new Exception(); // entityManager.flush(); } @Transactional( propagation = Propagation.REQUIRES_NEW // rollbackFor = Exception.class ) public void saveNewInternal() throws Exception { Proverb proverb = new Proverb(); proverb.setId(9999L); proverb.setProverb("Internal saved"); proverbsRepository.save(proverb); } @Override public void delete(Long id) { proverbsRepository.deleteById(id); } @Override public Optional<ProverbDTO> random() { Long id = proverbsRepository.randomId(); return proverbsRepository.findById(id).map(proverbMapper::toProverbDTO); // "SELECT id FROM proverb " + // "OFFSET floor(random()*(select count(*) from proverb)) LIMIT 1"; } @Override public Optional<ProverbDTO> random(Integer i) { return proverbsRepository.randomProverb(i).map(proverbMapper::toProverbDTO); } @Override public List<ProverbDTO> findCustomBy(String text, Integer type) { final Long start = System.currentTimeMillis(); List<ProverbDTO> proverbDTOS = proverbMapper.toProverbDTO(proverbsRepository.findCustomBy(text, type)); LOGGER.warn("Execution type {} time {}", type, System.currentTimeMillis() - start); return proverbDTOS; } }
true
8efcb94f8f3c8fff11c624a2a7d001c6877f5704
Java
kevinh415/SMorse
/AndroidStudioProjects/SMorse/app/src/main/java/smorse/com/smorse/MainActivity.java
UTF-8
22,864
1.859375
2
[]
no_license
package smorse.com.smorse; import android.Manifest; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.VibrationEffect; import android.os.Vibrator; import android.provider.ContactsContract; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.telephony.SmsManager; import android.util.Log; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.util.HashMap; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private static final int READ_SMS_PERMISSIONS_REQUEST = 1; private static final int SEND_SMS_PERMISSIONS_REQUEST = 1; private static final int RECEIVE_SMS_PERMISSIONS_REQUEST = 1; private static MainActivity inst; ArrayList<String> smsMessagesList = new ArrayList<>(); ArrayAdapter arrayAdapter; SmsManager smsManager = SmsManager.getDefault(); HashMap<String, String> alphabet = new HashMap<>(); // interval of the vibrations int shortVibrationSpeed = 20; int longVibrationSpeed = 100; int waitVibrationSpeed = 500; public static MainActivity instance() { return inst; } @Override public void onStart() { super.onStart(); inst = this; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); alphabet.put("A", ".-"); alphabet.put("B", "-..."); alphabet.put("C", "-.-."); alphabet.put("D", "-.."); alphabet.put("E", "."); alphabet.put("F", "..-."); alphabet.put("G", "--."); alphabet.put("H", "...."); alphabet.put("I", ".."); alphabet.put("J", ".---"); alphabet.put("K", "-.-"); alphabet.put("L", ".-.."); alphabet.put("M", "--"); alphabet.put("N", "-."); alphabet.put("O", "---"); alphabet.put("P", ".---."); alphabet.put("Q", "--.-"); alphabet.put("R", ".-."); alphabet.put("S", "..."); alphabet.put("T", "-"); alphabet.put("U", "..-"); alphabet.put("V", "...-"); alphabet.put("W", ".--"); alphabet.put("X", "-..-"); alphabet.put("Y", "-.--"); alphabet.put("Z", "--.."); alphabet.put("1", ".----"); alphabet.put("2", "..---"); alphabet.put("3", "...--"); alphabet.put("4", "....-"); alphabet.put("5", "....."); alphabet.put("6", "-...."); alphabet.put("7", "--..."); alphabet.put("8", "---.."); alphabet.put("9", "----."); alphabet.put(".", ".-.-.-"); alphabet.put(",", "--..--"); alphabet.put("?", "..--.."); alphabet.put("'", "-----"); alphabet.put("!", "-.-.--"); alphabet.put("/", "-..-."); alphabet.put("(", "-.--."); alphabet.put(")", "-.--.-"); alphabet.put("&", ".-..."); alphabet.put(":", "---..."); alphabet.put(";", "-.-.-."); alphabet.put("=", "-...-"); alphabet.put("+", ".-.-."); alphabet.put("-", "-....-"); alphabet.put("_", "..--.-"); alphabet.put("$", "...-..-"); alphabet.put("@", ".--.-."); alphabet.put(".-","A"); alphabet.put("-...","B"); alphabet.put("-.-.","C"); alphabet.put("-..","D"); alphabet.put(".","E"); alphabet.put("..-.","F"); alphabet.put("--.","G"); alphabet.put("....","H"); alphabet.put("..","I"); alphabet.put(".---","J"); alphabet.put("-.-","K"); alphabet.put(".-..","L"); alphabet.put("--","M"); alphabet.put("-.","N"); alphabet.put("---","O"); alphabet.put(".---.","P"); alphabet.put("--.-","Q"); alphabet.put(".-.","R"); alphabet.put("...","S"); alphabet.put("-","T"); alphabet.put("..-","U"); alphabet.put("...-","V"); alphabet.put(".--","W"); alphabet.put("-..-","X"); alphabet.put("-.--","Y"); alphabet.put("--..","Z"); alphabet.put(".----","1"); alphabet.put("..---","2"); alphabet.put("...--","3"); alphabet.put("....-","4"); alphabet.put(".....","5"); alphabet.put("-....","6"); alphabet.put("--...","7"); alphabet.put("---..","8"); alphabet.put("----.","9"); alphabet.put(".-.-.-","."); alphabet.put("--..--",","); alphabet.put("..--..","?"); alphabet.put("-----","'"); alphabet.put("-.-.--","!"); alphabet.put("-..-.","/"); alphabet.put("-.--.","("); alphabet.put("-.--.-",")"); alphabet.put(".-...","&"); alphabet.put("---...",":"); alphabet.put("-.-.-.", ";"); alphabet.put("-...-","="); alphabet.put(".-.-.","+"); alphabet.put("-....-", "-"); alphabet.put("..--.-","_"); alphabet.put("...-..-", "$"); alphabet.put(".--.-.", "@"); alphabet.put("/", " "); ListView messages = (ListView) findViewById(R.id.messages); arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, smsMessagesList); messages.setAdapter(arrayAdapter); if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) { getPermissionToReadSMS(); } else { refreshSmsInbox(); } if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { getPermissionToReadContacts(); } else { refreshSmsInbox(); } if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) { getPermissionToReceiveSMS(); } else { refreshSmsInbox(); } Button contactButton = findViewById(R.id.contact); contactButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI); startActivityForResult(contactPickerIntent, 1); } }); // make the phone vibrate Button vibrationButton = findViewById(R.id.short_button); final Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); vibrationButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { vibrator.vibrate(VibrationEffect.createOneShot(20, VibrationEffect.DEFAULT_AMPLITUDE)); } }); // make the phone vibrate Button longVibrationButton = findViewById(R.id.long_button); longVibrationButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { vibrator.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE)); } }); final EditText phoneNumber = findViewById(R.id.phone_number); final EditText message = findViewById(R.id.text); Button send = (Button) findViewById(R.id.send); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!phoneNumber.getText().toString().equals("") && !message.getText().toString().equals("")) { Snackbar.make(view, "sending message...", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); onSendClick(view, phoneNumber.getText().toString(), message.getText().toString()); } } }); /* SeekBar short_bar = findViewById(R.id.short_length); SeekBar long_bar = findViewById(R.id.long_length); SeekBar pause_bar = findViewById(R.id.pause_length); TextView short_value = findViewById(R.id.short_value); TextView long_value = findViewById(R.id.long_value); TextView pause_value = findViewById(R.id.pause_value); shortVibrationSpeed = short_bar.getProgress() + 1; // get progress value from the Seek bar short_value.setText(shortVibrationSpeed + ""); longVibrationSpeed = long_bar.getProgress() + 1; long_value.setText(longVibrationSpeed + ""); waitVibrationSpeed = pause_bar.getProgress() + 1; pause_value.setText(waitVibrationSpeed + ""); */ } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1 && resultCode == RESULT_OK) { // Get the URI and query the content provider for the phone number Uri contactUri = data.getData(); String[] projection = new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}; Cursor cursor = getApplicationContext().getContentResolver().query(contactUri, projection, null, null, null); // If the cursor returned is valid, get the phone number if (cursor != null && cursor.moveToFirst()) { int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); String number = cursor.getString(numberIndex); // Do something with the phone number ((EditText) findViewById(R.id.phone_number)).setText(number); } cursor.close(); } } public void onSendClick(View view, String phone_number, String message) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { getPermissionToSendSMS(); } else { // convert the message into morse code before sending message = convertToMorse(message); Snackbar.make(view, "Message sent!", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); smsManager.sendTextMessage(phone_number, null, message, null, null); } } public String getContactName(final String phoneNumber, Context context) { Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber)); String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}; String contactName = ""; Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { contactName = cursor.getString(0); } cursor.close(); } return contactName; } public void refreshSmsInbox() { ContentResolver contentResolver = getContentResolver(); //getting permission // getPermissionToReadSMS(); Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null); int indexBody = smsInboxCursor.getColumnIndex("body"); int indexAddress = smsInboxCursor.getColumnIndex("address"); if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return; arrayAdapter.clear(); int count = 0; do { String contactName = getContactName(smsInboxCursor.getString(indexAddress).substring(2), this); if (contactName.equals("")) contactName = "Unknown"; String received = smsInboxCursor.getString(indexBody); String str; if (received.contains("-") || received.contains(".")){ str = contactName + "\n" + received + "\n" + "Translated: " + convertToString(received) + "\n"; } else { str = contactName + "\n" + received + "\n"; } arrayAdapter.add(str); count++; } while (smsInboxCursor.moveToNext() && count < 20 ); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { setContentView(R.layout.settings); return true; } return super.onOptionsItemSelected(item); } public void getPermissionToReadSMS() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "getting permission to read sm...", Toast.LENGTH_SHORT).show(); if (shouldShowRequestPermissionRationale( Manifest.permission.READ_SMS)) { Toast.makeText(this, "Please allow permission!", Toast.LENGTH_SHORT).show(); } requestPermissions(new String[]{Manifest.permission.READ_SMS}, READ_SMS_PERMISSIONS_REQUEST); } } public void getPermissionToSendSMS() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "getting permission to send sms...", Toast.LENGTH_SHORT).show(); if (shouldShowRequestPermissionRationale( Manifest.permission.SEND_SMS)) { Toast.makeText(this, "Please allow permission!", Toast.LENGTH_SHORT).show(); } requestPermissions(new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSIONS_REQUEST); } } public void getPermissionToReceiveSMS() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "getting permission to receive sms...", Toast.LENGTH_SHORT).show(); if (shouldShowRequestPermissionRationale( Manifest.permission.RECEIVE_SMS)) { Toast.makeText(this, "Please allow permission!", Toast.LENGTH_SHORT).show(); } requestPermissions(new String[]{Manifest.permission.RECEIVE_SMS}, RECEIVE_SMS_PERMISSIONS_REQUEST); } } public void getPermissionToReadContacts() { // Here, thisActivity is the current activity if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { // Permission is not granted // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. } else { // No explanation needed; request the permission ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 1); // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an // app-defined int constant. The callback method gets the // result of the request. } } else { // Permission has already been granted } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { // Make sure it's our original READ_CONTACTS request if (requestCode == READ_SMS_PERMISSIONS_REQUEST) { if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "SMS permission granted", Toast.LENGTH_SHORT).show(); refreshSmsInbox(); } else { Toast.makeText(this, "Read SMS permission denied", Toast.LENGTH_SHORT).show(); } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } public String cleanse(String input) { String cleansedInput = input.replaceAll("[^A-Za-z0-9.,?!/()&:;=+_$@'$ ]", ""); return cleansedInput; } public String convertToMorse(String cleansedString) { String morseString = ""; for (int i = 0; i < cleansedString.length(); i++) { String temp = cleansedString.substring(i, i + 1); if (temp.compareTo(" ") == 0) { morseString = morseString + " / "; } else { String replace = alphabet.get(temp.toUpperCase()); morseString = morseString + replace + " "; } } return morseString; } public String convertToString(String cleansedString) { String morseString = ""; String[] arr = cleansedString.split(" "); for (int i = 0; i < arr.length; i++) { String temp = arr[i]; morseString = morseString + alphabet.get(temp); } return morseString; } // this method is called when the user gets a new message. public void getLatestMessage() { ContentResolver contentResolver = getContentResolver(); Cursor smsInboxCursor = contentResolver.query(Uri.parse("content://sms/inbox"), null, null, null, null); int indexBody = smsInboxCursor.getColumnIndex("body"); int indexAddress = smsInboxCursor.getColumnIndex("address"); if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return; int count = 0; arrayAdapter.clear(); // vibrate to the first string new Vibrations().execute(smsInboxCursor.getString(indexBody)); do { String contactName = getContactName(smsInboxCursor.getString(indexAddress).substring(2), this); if (contactName.equals("")) contactName = "Unknown"; String received = smsInboxCursor.getString(indexBody); String str; if (received.contains("-") || received.contains(".")){ str = contactName + "\n" + received + "\n" + "Translated: " + convertToString(received) + "\n"; } else { str = contactName + "\n" + received + "\n"; } arrayAdapter.add(str); count++; } while (smsInboxCursor.moveToNext() && count < 20 ); } // this class handles the viration notifications. Using AsyncTask because of how long it takes for the message to be received private class Vibrations extends AsyncTask<String, Void, String> { // Do the long-running work in here protected String doInBackground(String... params) { for (String s : params) { // call the mouseVibrate message for the message morseVibrate(s); } return null; } @Override protected void onPostExecute(String result) { // might want to change "executed" for the returned string passed // into onPostExecute() but that is upto you } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(Void... values) { } public void morseVibrate(String message) { // make the phone vibrate final Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); if (message.matches(".*[a-zA-Z]+.*")){ message = convertToMorse(message); } // iterate through each character in the message for (char c : message.toCharArray()) { // short vibration if the character is a '.' if (c == '.') { vibrator.vibrate(VibrationEffect.createOneShot(shortVibrationSpeed, 255)); try { // slight pause between characters Thread.sleep(waitVibrationSpeed); } catch (InterruptedException e) { e.printStackTrace(); } } // long vibration if the character is a '-' else if (c == '-') { vibrator.vibrate(VibrationEffect.createOneShot(longVibrationSpeed, 255)); try { // slight pause between characters Thread.sleep(waitVibrationSpeed); } catch (InterruptedException e) { e.printStackTrace(); } } // pause if there is a space else if (c == ' ') { try { // slight pause between characters Thread.sleep(waitVibrationSpeed); } catch (InterruptedException e) { e.printStackTrace(); } } } } } }
true
3e8fd523c1740f402c22ada41d4d2204c656e664
Java
AaronYang23/DataBindingPractice
/app/src/main/java/com/yyx/databiding/Person.java
UTF-8
1,262
2.71875
3
[]
no_license
package com.yyx.databiding; import androidx.databinding.BaseObservable; import androidx.databinding.Bindable; import com.yyx.BR; /** * Author: AaronYang \ aymiracle37@gmail.com * Date: 2021/1/8 * Function: */ public class Person extends BaseObservable { String name; int age; // TODO: 2021/1/8 int 类型的如何界面变化引起数据变化 public Person(String name, int age) { this.name = name; this.age = age; } //@Bindable观察数据变化 @Bindable public String getName() { return name; } //数据变化界面要变化要加notifyPropertyChanged 和对应字段 public void setName(String name) { this.name = name; notifyPropertyChanged(BR.name); } //@Bindable观察数据变化 @Bindable public int getAge() { return age; } //数据变化界面要变化要加notifyPropertyChanged 和对应字段 public void setAge(int age) { this.age = age; notifyPropertyChanged(BR.age); } public void growAge() { setAge(++age); } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
true
52411d1bd1d3d7a2514fc416a5c799e12dadb25d
Java
yunusborazan/NeverPuk
/NeverPuk/net/na/l.java
UTF-8
1,520
1.828125
2
[]
no_license
package net.na; import com.google.common.collect.Maps; import java.util.Map; import net.na.e; import net.na.u; import net.u.d; import net.yz.m_; public class l { private static final Map p = Maps.newHashMap(); private static final Map a = Maps.newHashMap(); public static void o(e.w var0) { m_ var1 = var0.I(); Class var2 = var0.C(); if(p.containsKey(var1)) { throw new IllegalArgumentException("Can\'t re-register entity property name " + var1); } else if(a.containsKey(var2)) { throw new IllegalArgumentException("Can\'t re-register entity property class " + var2.getName()); } else { p.put(var1, var0); a.put(var2, var0); } } public static e.w d(m_ var0) { int var10000 = e.w.y(); e.w var2 = (e.w)p.get(var0); int var1 = var10000; if(var2 == null) { throw new IllegalArgumentException("Unknown loot entity property \'" + var0 + "\'"); } else { if(d.y() == null) { ++var1; e.w.q(var1); } return var2; } } public static e.w b(e var0) { e.w.y(); e.w var2 = (e.w)a.get(var0.getClass()); if(var2 == null) { throw new IllegalArgumentException("Unknown loot entity property " + var0); } else { d.h(new d[1]); return var2; } } static { o(new u.j()); } private static IllegalArgumentException a(IllegalArgumentException var0) { return var0; } }
true
131472722d846138041c43dfe7427a486050038c
Java
matthew77cro/opp-project
/izvorniKod/backend/src/main/java/hr/fer/opp/bugbusters/servleti/banker/BankarRacuniServlet.java
UTF-8
5,014
1.976563
2
[]
no_license
package hr.fer.opp.bugbusters.servleti.banker; import java.io.IOException; import java.math.BigDecimal; import java.sql.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import hr.fer.opp.bugbusters.control.LoginHandler; import hr.fer.opp.bugbusters.dao.DAOProvider; import hr.fer.opp.bugbusters.dao.model.Constants; import hr.fer.opp.bugbusters.dao.model.Profil; import hr.fer.opp.bugbusters.dao.model.Racun; import hr.fer.opp.bugbusters.dao.model.VrstaRacuna; @SuppressWarnings("serial") @WebServlet(name="bankar-racuni", urlPatterns= {"/banka/bankar-racuni"}) @MultipartConfig public class BankarRacuniServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if(!LoginHandler.isLoggedIn(req, resp) || !LoginHandler.equalsRazinaOvlasti(req, resp, Constants.bankar)) { resp.sendRedirect("login"); return; } if(LoginHandler.needsPasswordChange(req, resp)) { resp.sendRedirect("passwordchange"); return; } req.setAttribute("vrste", DAOProvider.getDao().getAllVrstaRacuna()); req.getRequestDispatcher("/WEB-INF/pages/banker/bankerAccounts.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if(!LoginHandler.isLoggedIn(req, resp) || !LoginHandler.equalsRazinaOvlasti(req, resp, Constants.bankar)) { resp.sendRedirect("login"); return; } if(LoginHandler.needsPasswordChange(req, resp)) { resp.sendRedirect("passwordchange"); return; } String action = req.getParameter("action"); if(action==null) { req.setAttribute("errorMsg", "Request error - no action"); doGet(req, resp); return; } switch(action) { case "search" : String oib = req.getParameter("oib"); if(oib==null || oib.length()==0) { req.setAttribute("errorMsg", "Request error - OIB not sent"); break; } Profil profil = DAOProvider.getDao().getProfil(oib); if(profil==null) { req.setAttribute("errorMsg", "Request error - incorrect OIB"); break; } List<Racun> racuni = DAOProvider.getDao().getRacunByOib(oib); Map<Integer, VrstaRacuna> vrsteRacuna = new HashMap<>(); Map<Racun, VrstaRacuna> racunJsp = new HashMap<>(); for(var racun : racuni) { VrstaRacuna vrsta = vrsteRacuna.getOrDefault(racun.getSifVrsteRacuna(), DAOProvider.getDao().getVrstaRacuna(racun.getSifVrsteRacuna())); vrsteRacuna.put(vrsta.getSifVrsteRacuna(), vrsta); racunJsp.put(racun, vrsta); } req.setAttribute("oib", oib); req.setAttribute("racuni", racunJsp); break; case "add" : oib = req.getParameter("oib"); if(oib==null || oib.length()==0) { req.setAttribute("errorMsg", "Request error - OIB not sent"); break; } profil = DAOProvider.getDao().getProfil(oib); if(profil==null) { req.setAttribute("errorMsg", "Request error - incorrect OIB"); break; } int sifVrsteRacuna = Integer.parseInt(req.getParameter("vrstaRacuna")); String brojRacuna = req.getParameter("brojRacuna"); String prekoracenje = req.getParameter("prekoracenje"); String kamStopa = req.getParameter("kamStopa"); Racun racun = DAOProvider.getDao().getRacun(brojRacuna); if(racun!=null) { req.setAttribute("errorMsg", "Request error - account number already exists"); break; } BigDecimal prekoracenjeBD = null, kamStopaBD = null; try { prekoracenjeBD = new BigDecimal(prekoracenje); kamStopaBD = new BigDecimal(kamStopa); } catch (NumberFormatException ex) { req.setAttribute("errorMsg", "Request error - invalid values"); break; } boolean update = DAOProvider.getDao().addRacun(new Racun(brojRacuna, oib, new Date(System.currentTimeMillis()), BigDecimal.ZERO, sifVrsteRacuna, prekoracenjeBD, kamStopaBD, null)); if(!update) { req.setAttribute("errorMsg", "Request error"); break; } break; case "delete" : oib = req.getParameter("oib"); brojRacuna = req.getParameter("brojRacuna"); racun = DAOProvider.getDao().getRacun(brojRacuna); if(racun==null || !racun.getOib().equals(oib)) { req.setAttribute("errorMsg", "Request error - invalid parameters"); break; } if(racun.getStanje().compareTo(BigDecimal.ZERO) != 0) { req.setAttribute("errorMsg", "Request error - account has balance"); break; } DAOProvider.getDao().removeRacun(brojRacuna); break; default : req.setAttribute("errorMsg", "Request error - invalid action"); } doGet(req, resp); } }
true
88bd60a941692fd5b4ae41a6bbeedc0cd1e7e189
Java
deeplh/joytemplate
/bcwms/src/com/com/keepjoy/core/util/http/HttpHeaderUtil.java
UTF-8
4,495
2.234375
2
[]
no_license
package com.keepjoy.core.util.http; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.keepjoy.core.KeepJoyConstant; import org.apache.commons.lang.StringUtils; public class HttpHeaderUtil { public static String getIpAddr(HttpServletRequest request){ String unknownKey="unknown"; String ip = request.getHeader("x-forwarded-for"); if(ip == null || ip.length() == 0 || unknownKey.equalsIgnoreCase (ip)){ ip = request.getHeader("Proxy-Client-IP"); } if(ip == null || ip.length() == 0 || unknownKey.equalsIgnoreCase (ip)){ ip = request.getHeader("WL-Proxy-Client-IP"); } if(ip == null || ip.length() == 0 || unknownKey.equalsIgnoreCase(ip)){ ip = request.getRemoteAddr(); } return ip; } public static boolean isContentTypeImage(String contentType){ if(contentType.equals(KeepJoyConstant.CONTENT_TYPE_GIF) ||contentType.equals(KeepJoyConstant.CONTENT_TYPE_PNG) ||contentType.equals(KeepJoyConstant.CONTENT_TYPE_JPG)){ return true; }else{ return false; } } // public static boolean isContentTypeF(String contentType){ // if(contentType.equals(KeepJoyConstant.CONTENT_TYPE_GIF) // ||contentType.equals(KeepJoyConstant.CONTENT_TYPE_PNG) // ||contentType.equals(KeepJoyConstant.CONTENT_TYPE_JPG)){ // return true; // }else{ // return false; // } // } public static String getContentTypeByFileName(String fileName){ if(StringUtils.isEmpty(fileName))return null; fileName=fileName.toLowerCase(); int index=fileName.indexOf("?"); if(index>-1)fileName=fileName.substring(0,index); String contentType=null; if(fileName.endsWith(KeepJoyConstant.XLS.getValue())||fileName.endsWith(KeepJoyConstant.XLSX.getValue())){ contentType=KeepJoyConstant.CONTENT_TYPE_EXCEL.getValue(); }else if(fileName.endsWith(KeepJoyConstant.PDF.getValue())){ contentType=KeepJoyConstant.CONTENT_TYPE_PDF.getValue(); }else if(fileName.endsWith(KeepJoyConstant.HTML.getValue())){ contentType=KeepJoyConstant.CONTENT_TYPE_HTML.getValue(); }else if(fileName.endsWith(KeepJoyConstant.PNG.getValue())){ contentType=KeepJoyConstant.CONTENT_TYPE_PNG.getValue();; }else if(fileName.endsWith(KeepJoyConstant.JPG.getValue())){ contentType=KeepJoyConstant.CONTENT_TYPE_JPG.getValue(); }else if(fileName.endsWith(KeepJoyConstant.GIF.getValue())){ contentType=KeepJoyConstant.CONTENT_TYPE_GIF.getValue(); }else if(fileName.endsWith(KeepJoyConstant.CSS.getValue())){ contentType=KeepJoyConstant.CONTENT_TYPE_CSS.getValue(); }else if(fileName.endsWith(KeepJoyConstant.JS.getValue())||fileName.endsWith(KeepJoyConstant.MAP.getValue())){ contentType=KeepJoyConstant.CONTENT_TYPE_JS.getValue(); }else if(fileName.endsWith(KeepJoyConstant.DOC.getValue())||fileName.endsWith(KeepJoyConstant.DOCX.getValue())){ contentType=KeepJoyConstant.CONTENT_TYPE_DOC.getValue(); }else if(fileName.endsWith(KeepJoyConstant.WOFF.getValue()) ||fileName.endsWith(KeepJoyConstant.WOFF2.getValue())){ contentType=KeepJoyConstant.CONTENT_TYPE_WOFF.getValue(); }else if(fileName.endsWith(KeepJoyConstant.SVG.getValue())){ contentType=KeepJoyConstant.CONTENT_TYPE_SVG.getValue(); }else if(fileName.endsWith(KeepJoyConstant.TTF.getValue())){ contentType=KeepJoyConstant.CONTENT_TYPE_TTF.getValue(); } return contentType; } public static String setResponseHeader(HttpServletResponse response,String responseContentType,String responseCharacterEncoding){ response.setHeader("Cache-Control", "no-datadict"); response.setHeader("Expires", "0"); response.setHeader("Pragma", "no-datadict"); if(StringUtils.isEmpty(response.getContentType())){ //vtab.getJta().responseContentType() response.setContentType(responseContentType); } String charset=null; // JsonTagConfigFactory.getRequestCharacterEncoding(); //vtab.getJta().responseCharacterEncoding() if(StringUtils.isNotEmpty(responseCharacterEncoding)){ charset=responseCharacterEncoding; } //必须要用这样一个临时变量contentType,因为调用setCharacterEncoding后,会把ContentType里面的内容也改变 String contentType=response.getContentType(); int c=-1; if(null!=contentType)c=contentType.lastIndexOf(";"); if(c>-1){ contentType=contentType.substring(0,c); int d=contentType.lastIndexOf("="); if(d>-1)charset=contentType.substring(d+1); } response.setCharacterEncoding(charset); return contentType; } }
true
8c7d206cbd33c8f33347ead245a72b66b6067c6e
Java
jnp2018/N7_19_AppChat
/src/Client/src/main/LoginForm.java
UTF-8
15,327
2.125
2
[]
no_license
package main; import function.FileChooser; import function.Method; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.net.ConnectException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.filechooser.FileFilter; public class LoginForm extends javax.swing.JFrame { public LoginForm() { initComponents(); open(); } private void open() { Method.setTextFieldSyle(txtUser, "User Name"); Method.setTextFieldSyle(txtIP, "IP Address"); showStatus(ms); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); txtIP = new javax.swing.JTextField(); txtUser = new javax.swing.JTextField(); cmdLogin = new swing.Button(); jLayeredPane1 = new javax.swing.JLayeredPane(); lbStatus = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Log in"); setResizable(false); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); txtIP.setBackground(new java.awt.Color(204, 204, 204)); txtIP.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N txtIP.setHorizontalAlignment(javax.swing.JTextField.CENTER); txtIP.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 10, 1, 10)); txtIP.setSelectionColor(new java.awt.Color(131, 188, 227)); txtIP.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtIPKeyTyped(evt); } }); txtUser.setBackground(new java.awt.Color(204, 204, 204)); txtUser.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N txtUser.setHorizontalAlignment(javax.swing.JTextField.CENTER); txtUser.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 10, 1, 10)); txtUser.setSelectionColor(new java.awt.Color(131, 188, 227)); txtUser.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { txtUserKeyTyped(evt); } }); cmdLogin.setBackground(new java.awt.Color(255, 153, 153)); cmdLogin.setForeground(new java.awt.Color(255, 255, 255)); cmdLogin.setText("Log in"); cmdLogin.setColorClick(new java.awt.Color(152, 196, 239)); cmdLogin.setColorOver(new java.awt.Color(31, 121, 208)); cmdLogin.setFillBorder(20); cmdLogin.setFocusable(false); cmdLogin.setFont(new java.awt.Font("sansserif", 1, 14)); // NOI18N cmdLogin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmdLoginActionPerformed(evt); } }); jLayeredPane1.setLayout(new javax.swing.OverlayLayout(jLayeredPane1)); lbStatus.setFont(new java.awt.Font("Arial", 0, 14)); // NOI18N lbStatus.setForeground(new java.awt.Color(204, 0, 0)); lbStatus.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lbStatus.setEnabled(false); jLabel1.setText("USERNAME"); jLabel2.setText("YOUR IP"); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N jLabel3.setForeground(new java.awt.Color(204, 0, 153)); jLabel3.setText("GROUP CHAT JAVA"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(28, 28, 28) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(34, 34, 34) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(39, 39, 39) .addComponent(jLabel3))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txtIP, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbStatus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(195, 195, 195) .addComponent(cmdLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(62, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(28, 28, 28))) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtIP, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE) .addComponent(cmdLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(lbStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void cmdLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdLoginActionPerformed try { if (txtUser.getText().equals("") || !txtUser.getName().equals("have")) { txtUser.grabFocus(); showStatus("Please input your user name"); } else { if (txtUser.getText().trim().length() > 20) { txtUser.grabFocus(); showStatus("User name must less than 20 character"); } else { String IP = txtIP.getText().trim(); if (txtIP.getText().equals("") || !txtIP.getName().equals("have")) { IP = "localhost"; } String userName = txtUser.getText().trim(); Registry re = LocateRegistry.getRegistry(IP, 5000); rmi.Method rmi = (rmi.Method) re.lookup("super"); if (rmi.checkName(userName)) { Method.connect(profile_pic, userName, IP); this.dispose(); MainForm.main(null); } else { showStatus("User name has already"); } } } } catch (java.rmi.UnknownHostException e) { showStatus("Unknown host : " + txtIP.getText()); } catch (ConnectException e) { showStatus("Server not found"); } catch (java.rmi.ConnectException e) { showStatus("Server not found"); } catch (Exception e) { showStatus("Network is unreachable : connect"); System.out.println(e); } }//GEN-LAST:event_cmdLoginActionPerformed private void borderMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_borderMouseClicked if (evt.getClickCount() == 2 && SwingUtilities.isLeftMouseButton(evt)) { JFileChooser ch = new JFileChooser(); FileChooser preview = new FileChooser(); ch.setAccessory(preview); ch.addPropertyChangeListener(preview); ch.setFileFilter(new FileFilter() { @Override public boolean accept(File file) { String name = file.getName(); return file.isDirectory() || name.endsWith(".png") || name.endsWith(".PNG") || name.endsWith("jpg") || name.endsWith("JPG"); } @Override public String getDescription() { return "png,jpg"; } }); int opt = ch.showOpenDialog(this); if (opt == JFileChooser.APPROVE_OPTION) { ImageIcon image = new ImageIcon(ch.getSelectedFile().getAbsolutePath()); Image img; if (image.getIconWidth() > image.getIconHeight()) { img = image.getImage().getScaledInstance(100, -1, Image.SCALE_SMOOTH); } else { img = image.getImage().getScaledInstance(-1, 100, Image.SCALE_SMOOTH); } profile_pic = new ImageIcon(img); } } }//GEN-LAST:event_borderMouseClicked private void txtUserKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUserKeyTyped if (evt.getKeyChar() == 10) { txtIP.grabFocus(); } if (txtUser.getText().trim().length() >= 15) { evt.consume(); } }//GEN-LAST:event_txtUserKeyTyped private void txtIPKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtIPKeyTyped if (evt.getKeyChar() == 10) { cmdLoginActionPerformed(null); } }//GEN-LAST:event_txtIPKeyTyped private ImageIcon profile_pic; private Timer timer = new Timer(5000, new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { timer.stop(); } }); private void showStatus(String error) { if (timer.isRunning()) { timer.stop(); } timer.start(); } private static String ms = ""; public static void main(String args[]) { try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { if (args.length == 1) { ms = args[0]; } new LoginForm().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private swing.Button cmdLogin; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLayeredPane jLayeredPane1; private javax.swing.JPanel jPanel1; private javax.swing.JLabel lbStatus; private javax.swing.JTextField txtIP; private javax.swing.JTextField txtUser; // End of variables declaration//GEN-END:variables }
true
838d9c8b2b6cae918796bf24f6e13d8b49672bbc
Java
lipeilin7570/wei_bus
/src/main/java/com/wgjev/weibus/controller/beacon/LoadBeaconBySiteIDController.java
UTF-8
639
1.921875
2
[]
no_license
package com.wgjev.weibus.controller.beacon; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.wgjev.weibus.entity.BusResult; import com.wgjev.weibus.service.BeaconService; @Controller @RequestMapping("/beacon") public class LoadBeaconBySiteIDController { @Resource private BeaconService beaconService; @RequestMapping("/loadBeanconBySiteID.do") @ResponseBody public BusResult execute(Integer siteID){ return beaconService.loadBeaconBySiteID(siteID); } }
true
0fa988c955840ecefff9b9ace4493f45de216449
Java
popovichia/spring_part1
/spring_project/spring_mvc_eshop/src/main/java/ru/popovichia/eshop/controllers/CustomersController.java
UTF-8
924
2.09375
2
[]
no_license
package ru.popovichia.eshop.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import ru.popovichia.eshop.services.DataService; /** * * @author Igor Popovich, email: iapopo17@mts.ru, phone: +7 913 902 36 36, * company: mts.ru */ @Controller @RequestMapping(path = "/") public class CustomersController { private final static String CUSTOMERS_VIEWS_DIR = "customers/"; @Autowired private DataService dataService; @GetMapping(path = "/getAllCustomers") public String getAllCustomers( Model model ) { model.addAttribute("listCustomers", dataService.getAllCustomersSortedByFullNameAsc()); return CUSTOMERS_VIEWS_DIR + "customers"; } }
true
e8740b7b1f6e8cd6344709a08d7dbb99b1fec81c
Java
Mayank283/Interview
/src/data/structure/heaps/HeapTest.java
UTF-8
521
3.359375
3
[]
no_license
package data.structure.heaps; public class HeapTest { public static void main(String[] args) { int arr[] = { 4, 7, 8, 3, 2, 16, 5 }; Heap heap = new Heap(); arr = heap.buildMaxHeap(arr); display(arr); System.out.println(heap.parentOfElement(arr, 16)); arr = heap.deleteElement(arr); display(arr); arr = heap.insertElement(arr, 15); display(arr); } public static void display(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } }
true
74dc9a88c85502ee3b1b665207f851e33fcc71dc
Java
programmingII/oop-practice-1-RobertMares
/Exercises 4-10 February/exercise13_Rectangle.java
ISO-8859-1
906
3.890625
4
[]
no_license
import java.util.Scanner; //Importacin del cdigo de la clase Scanner desde la biblioteca Java public class exercise13_Rectangle{ //declaracion de la clase public static void main (String [ ] args){//declaracion del programa principal Scanner in=new Scanner(System.in); //se crea el objeto de la clase Scanner para poder capturar desde teclado System.out.println("Capture la altura del rectangulo "); //se imprime en pantalla la instruccion float altura=in.nextFloat(); //se le da el valor a altura el numero capturado System.out.println("Capture el ancho del rectangulo "); //se imprime en pantalla la instruccion float ancho=in.nextFloat(); //se le da el valor a ancho el numero capturado System.out.println("El perimetro del circulo es: "+(altura*ancho)+"\n El area del Circulo es: "+ (2*(altura+ancho))); //se imprime y calcula el perimetro y area del rectangulo } }
true
bf8099cace61fb3ba457cc832e4f9746aac9a07e
Java
ana-athayde/clinica
/controller/FuncionarioController.java
UTF-8
9,183
2.28125
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 controller; import classes.Funcionario; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseListener; import java.util.List; import javax.swing.JCheckBox; import javax.swing.JFormattedTextField; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; import model.services.FuncionarioServices; import view.CadastroFuncionario; import view.TelaPrincipal; /** * * @author Marlon Quilante */ public class FuncionarioController implements ActionListener { CadastroFuncionario cadastroFuncionario; private FuncionarioServices funcionarioServices = new FuncionarioServices(); public static Funcionario funcionario = new Funcionario(); public static boolean estadoComponentes = false; public FuncionarioController(CadastroFuncionario cadastroFuncionario) { this.cadastroFuncionario = cadastroFuncionario; this.cadastroFuncionario.getBtnNovo().addActionListener(this); this.cadastroFuncionario.getBtnCancelar().addActionListener(this); this.cadastroFuncionario.getBtnCadastrar().addActionListener(this); this.cadastroFuncionario.getBtnSair().addActionListener(this); this.cadastroFuncionario.getBtnPesquisar().addActionListener(this); this.cadastroFuncionario.getBtnExcluir().addActionListener(this); DefaultTableModel modeloTabela = (DefaultTableModel) this.cadastroFuncionario.getjTableFuncionarios().getModel(); modeloTabela.setNumRows(0); habilitarEdicao(false); for (Funcionario funcionarioAtual : this.funcionarioServices.Buscar()) { modeloTabela.addRow(new Object[]{ funcionarioAtual.getId(), funcionarioAtual.getNome(), funcionarioAtual.getCpf(), funcionarioAtual.getRg(), funcionarioAtual.getTelefone(), funcionarioAtual.getCelular(), funcionarioAtual.getEmail(), funcionarioAtual.getSexo()}); } } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == this.cadastroFuncionario.getBtnPesquisar()) { habilitarEdicao(false); DefaultTableModel modeloTabela = (DefaultTableModel) this.cadastroFuncionario.getjTableFuncionarios().getModel(); modeloTabela.setNumRows(0); List<Funcionario> listaFuncionario; listaFuncionario = this.funcionarioServices.buscarFiltrando(this.cadastroFuncionario.getTxtPesquisa().getText()); for (Funcionario funcionarioAtual : listaFuncionario) { modeloTabela.addRow(new Object[]{ funcionarioAtual.getId(), funcionarioAtual.getNome(), funcionarioAtual.getCpf(), funcionarioAtual.getRg(), funcionarioAtual.getTelefone(), funcionarioAtual.getCelular(), funcionarioAtual.getEmail(), funcionarioAtual.getSexo()}); } } else if (e.getSource() == this.cadastroFuncionario.getBtnNovo()) { habilitarEdicao(true); } else if (e.getSource() == this.cadastroFuncionario.getBtnCancelar()) { habilitarEdicao(false); } else if (e.getSource() == this.cadastroFuncionario.getBtnCadastrar()) { String sexo; if (this.cadastroFuncionario.getjCheckBoxFeminino().isSelected()) { sexo = "FEMININO"; } else { sexo = "MASCULINO"; } Funcionario funcionario = new Funcionario(); funcionario.setId(this.funcionario.getId()); funcionario.setNome(this.cadastroFuncionario.getTxtNome().getText()); funcionario.setCpf(this.cadastroFuncionario.getjFTcpf().getText()); funcionario.setRg(this.cadastroFuncionario.getjFTrg().getText()); funcionario.setEmail(this.cadastroFuncionario.getTxtEmail().getText()); funcionario.setTelefone(this.cadastroFuncionario.getjFTtelefone().getText()); funcionario.setCelular(this.cadastroFuncionario.getjFTcelular().getText()); funcionario.setSexo(sexo); funcionarioServices.cadastrar(funcionario); boolean sucesso = true; DefaultTableModel modeloTabela = (DefaultTableModel) this.cadastroFuncionario.getjTableFuncionarios().getModel(); modeloTabela.setNumRows(0); habilitarEdicao(false); for (Funcionario funcionarioAtual : this.funcionarioServices.Buscar()) { modeloTabela.addRow(new Object[]{ funcionarioAtual.getId(), funcionarioAtual.getNome(), funcionarioAtual.getCpf(), funcionarioAtual.getRg(), funcionarioAtual.getTelefone(), funcionarioAtual.getCelular(), funcionarioAtual.getEmail(), funcionarioAtual.getSexo()}); } if (sucesso == true) { JOptionPane.showMessageDialog(null, "Cadastro bem sucedido.", "Cadastro de funcionários", JOptionPane.INFORMATION_MESSAGE); habilitarEdicao(false); } else { JOptionPane.showMessageDialog(null, "Erro no processo de cadastro", "Cadastro de funcionários", JOptionPane.INFORMATION_MESSAGE); } } else if (e.getSource() == this.cadastroFuncionario.getBtnSair()) { this.cadastroFuncionario.dispose(); TelaPrincipal tela = new TelaPrincipal(); tela.setVisible(true); } else if (e.getSource() == this.cadastroFuncionario.getBtnExcluir()){ DefaultTableModel modelo = (DefaultTableModel) this.cadastroFuncionario.getjTableFuncionarios().getModel(); int objeto = (int) this.cadastroFuncionario.getjTableFuncionarios().getValueAt((int)this.cadastroFuncionario.getjTableFuncionarios().getSelectedRow(), 0); funcionarioServices.Delete(objeto); modelo.setNumRows(0); for (Funcionario funcionarioAtual : this.funcionarioServices.Buscar()) { modelo.addRow(new Object[]{ funcionarioAtual.getId(), funcionarioAtual.getNome(), funcionarioAtual.getCpf(), funcionarioAtual.getRg(), funcionarioAtual.getTelefone(), funcionarioAtual.getCelular(), funcionarioAtual.getEmail(), funcionarioAtual.getSexo()}); } } } private void habilitarEdicao(boolean tipoOperacao) { if (tipoOperacao == true) { this.cadastroFuncionario.getBtnNovo().setEnabled(false); this.cadastroFuncionario.getBtnCancelar().setEnabled(true); this.cadastroFuncionario.getBtnCadastrar().setEnabled(true); this.cadastroFuncionario.getBtnSair().setEnabled(false); desLigaComponentesForm(true); } else { this.cadastroFuncionario.getBtnNovo().setEnabled(true); this.cadastroFuncionario.getBtnCancelar().setEnabled(false); this.cadastroFuncionario.getBtnCadastrar().setEnabled(false); this.cadastroFuncionario.getBtnSair().setEnabled(true); desLigaComponentesForm(false); } } private void desLigaComponentesForm(boolean estadoComponentes) { Component[] componentes = this.cadastroFuncionario.getjPanelDadosFuncionario().getComponents(); for (Component componente : componentes) { if (componente instanceof JTextField) { componente.setEnabled(estadoComponentes); ((JTextField) componente).setText(""); } else if (componente instanceof JCheckBox) { componente.setEnabled(estadoComponentes); ((JCheckBox) componente).setSelected(false); } else if (componente instanceof JFormattedTextField) { componente.setEnabled(estadoComponentes); ((JFormattedTextField) componente).setText(""); } } this.cadastroFuncionario.getjPanelPesquisaFuncionario().getComponents(); for (Component componente : componentes) { if (componente instanceof JTextField) { componente.setEnabled(estadoComponentes); ((JTextField) componente).setText(""); } } } }
true
8624fbc8480b412bf3043c631c0bc32e3705a41a
Java
wtJavaer88/SrtLearnSwing
/src/com/wnc/srtlearn/dao/FavDao.java
UTF-8
3,585
2.25
2
[]
no_license
package com.wnc.srtlearn.dao; import java.sql.SQLException; import java.util.List; import org.apache.commons.lang.StringEscapeUtils; import srt.SrtInfo; import com.wnc.srtlearn.pojo.FavoriteMultiSrt; import com.wnc.srtlearn.pojo.FavoriteSingleSrt; import common.utils.UUIDUtil; import db.DataSource; import db.DbExecMgr; import db.DbField; import db.DbFieldSqlUtil; public class FavDao { public static boolean isExistSingle(SrtInfo mfav, String srtFile) { DbExecMgr.refreshCon(DataSource.BUSINESS); return DbExecMgr .isExistData("SELECT * FROM FAV_MULTI M LEFT JOIN FAV_SINGLE S ON M.UUID=S.P_UUID WHERE SRTFILE='" + srtFile + "' AND S.FROM_TIME='" + mfav.getFromTime().toString() + "' AND S.TO_TIME='" + mfav.getToTime().toString() + "'"); } public static boolean isExistMulti(FavoriteMultiSrt mfav) { DbExecMgr.refreshCon(DataSource.BUSINESS); DbFieldSqlUtil util = new DbFieldSqlUtil("FAV_MULTI", ""); util.addWhereField(new DbField("SRTFILE", mfav.getSrtFile())); util.addWhereField(new DbField("FROM_TIME", mfav.getFromTimeStr())); util.addWhereField(new DbField("TO_TIME", mfav.getToTimeStr())); return DbExecMgr.isExistData(util.getSelectSql()); } public static boolean insertFavMulti(FavoriteMultiSrt mfav, List<FavoriteSingleSrt> sfavs) { DbExecMgr.refreshCon(DataSource.BUSINESS); DbFieldSqlUtil util = new DbFieldSqlUtil("FAV_MULTI", ""); util.addInsertField(new DbField("SRTFILE", mfav.getSrtFile())); String uuid = UUIDUtil.getUUID(); util.addInsertField(new DbField("UUID", uuid)); util.addInsertField(new DbField("FROM_TIME", mfav.getFromTimeStr())); util.addInsertField(new DbField("TO_TIME", mfav.getToTimeStr())); util.addInsertField(new DbField("FAV_TIME", mfav.getFavTimeStr())); util.addInsertField(new DbField("HAS_CHILD", mfav.getHasChild() + "", "NUMBER")); util.addInsertField(new DbField("TAG", mfav.getTag())); try { DbExecMgr.execOnlyOneUpdate(util.getInsertSql()); return insertFavChilds(uuid, sfavs); } catch (SQLException e) { e.printStackTrace(); return false; } } private static boolean insertFavChilds(String p_uuid, List<FavoriteSingleSrt> sfavs) { for (FavoriteSingleSrt sfav : sfavs) { DbExecMgr.refreshCon(DataSource.BUSINESS); DbFieldSqlUtil util = new DbFieldSqlUtil("FAV_SINGLE", ""); util.addInsertField(new DbField("P_UUID", p_uuid)); util.addInsertField(new DbField("FROM_TIME", sfav.getFromTimeStr())); util.addInsertField(new DbField("TO_TIME", sfav.getToTimeStr())); util.addInsertField(new DbField("SINDEX", sfav.getsIndex() + "", "NUMBER")); util.addInsertField(new DbField("ENG", StringEscapeUtils .escapeSql(sfav.getEng()))); util.addInsertField(new DbField("CHS", StringEscapeUtils .escapeSql(sfav.getChs()))); try { DbExecMgr.execOnlyOneUpdate(util.getInsertSql()); } catch (SQLException e) { e.printStackTrace(); return false; } } return true; } }
true
1723144300712829ee295e5e7672e579b74ce32a
Java
lucasrennok/Real_Estate_System
/src/Model/Vendedor.java
UTF-8
417
2.5
2
[ "MIT" ]
permissive
package Model; import java.io.Serializable; public class Vendedor extends Pessoa implements Serializable{ private String contatoPref; public Vendedor(String cpf, String nome, String email, String fone, String contatoPref) { super(cpf, nome, email, fone); this.contatoPref = contatoPref; } public String getContatoPref() { return contatoPref; } }
true
03af363888858576f733c88eaa359808d99e2a4e
Java
workinginit/mywork
/GetJiraInfos/src/main/java/org/vermeg/entities/Jira.java
UTF-8
2,823
2.140625
2
[]
no_license
package org.vermeg.entities; public class Jira { private Long id; private String projectName; private String key; private String summary; private String issueType; private String status; private String priority; private String resolution; private String assigne; private String reporter; private String creationDate; private String updateDate; private String description; public Jira() { super(); } public Jira(Long id, String projectName, String key, String summary, String issueType, String status, String priority, String resolution, String assigne, String reporter, String creationDate, String updateDate, String description) { super(); this.id = id; this.projectName = projectName; this.key = key; this.summary = summary; this.issueType = issueType; this.status = status; this.priority = priority; this.resolution = resolution; this.assigne = assigne; this.reporter = reporter; this.creationDate = creationDate; this.updateDate = updateDate; this.description = description; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getIssueType() { return issueType; } public void setIssueType(String issueType) { this.issueType = issueType; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getPriority() { return priority; } public void setPriority(String priority) { this.priority = priority; } public String getResolution() { return resolution; } public void setResolution(String resolution) { this.resolution = resolution; } public String getAssigne() { return assigne; } public void setAssigne(String assigne) { this.assigne = assigne; } public String getReporter() { return reporter; } public void setReporter(String reporter) { this.reporter = reporter; } public String getCreationDate() { return creationDate; } public void setCreationDate(String creationDate) { this.creationDate = creationDate; } public String getUpdateDate() { return updateDate; } public void setUpdateDate(String updateDate) { this.updateDate = updateDate; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
true
16681a93dc1af21b9ef233d12ead65979037bfa2
Java
qiao-zhi/AllProject
/xm/src/cn/xm/mapper/TTempleateBaseInfoMapper.java
UTF-8
1,293
1.929688
2
[]
no_license
package cn.xm.mapper; import cn.xm.pojo.TTempleateBaseInfo; import cn.xm.pojo.TTempleateBaseInfoExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface TTempleateBaseInfoMapper { int countByExample(TTempleateBaseInfoExample example); int deleteByExample(TTempleateBaseInfoExample example); int deleteByPrimaryKey(String templateid); int insert(TTempleateBaseInfo record); int insertSelective(TTempleateBaseInfo record); List<TTempleateBaseInfo> selectByExampleWithBLOBs(TTempleateBaseInfoExample example); List<TTempleateBaseInfo> selectByExample(TTempleateBaseInfoExample example); TTempleateBaseInfo selectByPrimaryKey(String templateid); int updateByExampleSelective(@Param("record") TTempleateBaseInfo record, @Param("example") TTempleateBaseInfoExample example); int updateByExampleWithBLOBs(@Param("record") TTempleateBaseInfo record, @Param("example") TTempleateBaseInfoExample example); int updateByExample(@Param("record") TTempleateBaseInfo record, @Param("example") TTempleateBaseInfoExample example); int updateByPrimaryKeySelective(TTempleateBaseInfo record); int updateByPrimaryKeyWithBLOBs(TTempleateBaseInfo record); int updateByPrimaryKey(TTempleateBaseInfo record); }
true
1d97179c039177d795311453dc1a485213e7ebc2
Java
shawkattack/JavaDataTimeSeries
/src/test/java/org/jdata/timeseries/processing/sequitur/SequiturTest.java
UTF-8
6,012
2.765625
3
[ "MIT" ]
permissive
package org.jdata.timeseries.processing.sequitur; import org.junit.*; import java.util.Collection; import java.util.Collections; import java.util.List; public class SequiturTest { @Before public void setup() { } @Test public void testSymbolEquals() { Symbol s1 = new TerminalSymbol('a'); Symbol s2 = new TerminalSymbol('a'); Symbol s3 = new NonTerminalSymbol(new Rule(-1)); Assert.assertEquals(s1, s2); Assert.assertNotEquals(s1, s3); Assert.assertNotEquals(s2, s3); } @Test public void testRuleAppend() { Rule r = new Rule(-1); Assert.assertEquals("toString failed", "1 -> ", r.toString()); r.append(new TerminalSymbol('a')); Assert.assertEquals("first append failed", "1 -> a", r.toString()); r.append(new TerminalSymbol('b')); Assert.assertEquals("second append failed", "1 -> ab", r.toString()); r.append(new TerminalSymbol('c')); Assert.assertEquals("final append failed", "1 -> abc", r.toString()); } @Test public void testRuleReferenceCounting() { Rule r = new Rule(-1); Assert.assertEquals("rule initialization failed", 0, r.getRefCount()); r.addReference(); Assert.assertEquals("first increment failed", 1, r.getRefCount()); r.addReference(); Assert.assertEquals("second increment failed", 2, r.getRefCount()); r.removeReference(); Assert.assertEquals("first decrement failed", 1, r.getRefCount()); r.removeReference(); Assert.assertEquals("second decrement failed", 0, r.getRefCount()); } @Test public void testRuleReduce() { Symbol a = new TerminalSymbol('a'); Symbol b = new TerminalSymbol('b'); Symbol c = new TerminalSymbol('c'); Rule r1 = new Rule(-1); r1.append(a); r1.append(b); r1.append(c); Assume.assumeTrue("append failed", "1 -> abc".equals(r1.toString())); Rule r2 = new Rule(-2); r1.reduce(b, r2); Symbol A = a.getNext(); Assert.assertEquals("symbol created with incorrect value", -2, A.getValue()); Assert.assertEquals("first reduce failed", "1 -> a{2}", r1.toString()); Rule r3 = new Rule(-3); r1.reduce(a, r3); Assert.assertEquals("second reduce failed", "1 -> {3}", r1.toString()); } @Test public void testRuleExpand() { Rule r2 = new Rule(-2); Rule r3 = new Rule(-3); Rule r4 = new Rule(-4); Symbol A = new NonTerminalSymbol(r2); Symbol B = new NonTerminalSymbol(r3); Symbol C = new NonTerminalSymbol(r4); Symbol a1 = new TerminalSymbol('a'); Symbol a2 = new TerminalSymbol('a'); Symbol b2 = new TerminalSymbol('b'); Symbol c2 = new TerminalSymbol('c'); Rule r1 = new Rule(-1); r1.append(A); Assume.assumeTrue("append failed", "1 -> {2}".equals(r1.toString())); r2.append(B); r1.expand(A, r2); Assert.assertEquals("first expand failed", "1 -> {3}", r1.toString()); r3.append(a1); r3.append(C); r1.expand(B, r3); Assert.assertEquals("second expand failed", "1 -> a{4}", r1.toString()); r4.append(a2); r4.append(b2); r4.append(c2); r1.expand(C, r4); Assert.assertEquals("third expand failed", "1 -> aabc", r1.toString()); } @Test public void testSequiturAlgorithm() { Sequitur sequitur = new Sequitur(); String nullResult = ruleSetToString(sequitur.generateRuleSet("")); Assert.assertEquals("Null argument failed", "1 -> ,", nullResult); String charResult = ruleSetToString(sequitur.generateRuleSet("a")); Assert.assertEquals("Single char failed", "1 -> a,", charResult); String digramResult = ruleSetToString(sequitur.generateRuleSet("ab")); Assert.assertEquals("Digram failed", "1 -> ab,", digramResult); String trigramResult = ruleSetToString(sequitur.generateRuleSet("abc")); Assert.assertEquals("Normal trigram failed", "1 -> abc,", trigramResult); String doubleTrigramResult = ruleSetToString(sequitur.generateRuleSet("abb")); Assert.assertEquals("Trigram with duplicate failed", "1 -> abb,", doubleTrigramResult); String doubleDigramResult = ruleSetToString(sequitur.generateRuleSet("abab")); Assert.assertEquals("Duplicate digram failed", "1 -> {2}{2},2 -> ab,", doubleDigramResult); String quadrupleCharResult = ruleSetToString(sequitur.generateRuleSet("aaaa")); Assert.assertEquals("Quadruple character failed", "1 -> {2}{2},2 -> aa,", quadrupleCharResult); String separateDoubleDigramResult = ruleSetToString(sequitur.generateRuleSet("abcdbc")); Assert.assertEquals("Non-consecutive double digram failed", "1 -> a{2}d{2},2 -> bc,", separateDoubleDigramResult); String recursiveReplacementResult = ruleSetToString(sequitur.generateRuleSet("abcdbcabc")); Assert.assertEquals("Recursive rule replacement failed", "1 -> {3}d{2}{3},2 -> bc,3 -> a{2},", recursiveReplacementResult); String ruleExpansionResult = ruleSetToString(sequitur.generateRuleSet("abcdbcabcd")); Assert.assertEquals("Rule expansion failed", "1 -> {4}{2}{4},2 -> bc,4 -> a{2}d,", ruleExpansionResult); String recursiveRuleExpansionResult = ruleSetToString(sequitur.generateRuleSet("afbcdbcafbcd")); Assert.assertEquals("Recursive rule expansion failed", "1 -> {5}{2}{5},2 -> bc,5 -> af{2}d,", recursiveRuleExpansionResult); } private String ruleSetToString(List<Rule> rules) { Collections.sort(rules, (Rule r1, Rule r2) -> r2.getId() - r1.getId()); StringBuilder sb = new StringBuilder(); for (Rule r : rules) { sb.append(r.toString()); sb.append(','); } return sb.toString(); } @After public void cleanup() { } }
true
a6010c303577a1fe35ede1c4d6fa612a634ca575
Java
inhobaek-wj/cat-toy-store-backend
/src/main/java/com/jake/cattoystore/application/GreetingService.java
UTF-8
613
2.71875
3
[]
no_license
package com.jake.cattoystore.application; import com.jake.cattoystore.domain.Greeting; import org.springframework.stereotype.Service; @Service public class GreetingService { public String getMessage(String name) { // if (name == null) { // return "Hello"; // } // return "Hello, " + name; // application layer uses Greeting domain model, // so when you need to change business logic, you can change domain model. Greeting greeting = Greeting.builder() .name(name) .build(); return greeting.getMessage(); } }
true
687f81c37d11ae89427584e53820452ec866c7cb
Java
frblazquez/PC
/Practice 3/src/pc/practice3/Part3.java
UTF-8
992
3.3125
3
[]
no_license
package pc.practice3; import pc.practice3.schema.Consumer; import pc.practice3.schema.Producer; import pc.practice3.schema.SeveralProductsWarehouse; import pc.practice3.schema.Warehouse; /** * Producers-Consumers problem with semaphores with bus size with space for * several elements. * * @author Francisco Javier Blázquez Martínez */ public class Part3 { private static final int N_PROD = 10; private static final int N_CONS = 10; private static Warehouse wh = new SeveralProductsWarehouse(); public static void main(String[] args) { // Threads creation and initialization Thread[] producers = new Thread[N_PROD]; Thread[] consumers = new Thread[N_CONS]; for(int i = 0; i < N_PROD; i++) producers[i] = new Thread(new Producer(i, wh)); for(int i = 0; i < N_CONS; i++) consumers[i] = new Thread(new Consumer(i, wh)); // Threads execution start for(int i = 0; i < N_PROD; i++) producers[i].start(); for(int i = 0; i < N_CONS; i++) consumers[i].start(); } }
true
d2dd1f38784e7e9d9a584092a70409d8faf76152
Java
HENRIQUESOUZ/athat
/athatWeb/src/main/java/br/com/athat/web/controller/conta/BaixarParcelaController.java
UTF-8
3,023
2.015625
2
[]
no_license
package br.com.athat.web.controller.conta; import br.com.athat.core.entity.conta.*; import br.com.athat.core.entity.movimentacao.Movimentacao; import org.springframework.beans.factory.annotation.Autowired; import br.com.athat.core.manager.conta.ContaAPagarManager; import br.com.athat.core.manager.conta.ContaAReceberManager; import br.com.athat.core.manager.movimentacao.compra.CompraManager; import br.com.athat.web.utils.AbstractController; public class BaixarParcelaController extends AbstractController { private static final long serialVersionUID = 1L; private Conta conta; private Parcela parcelaABaixar; @Autowired private CompraManager compraManager; @Autowired private ContaAPagarManager contaAPagarManager; @Autowired private ContaAReceberManager contaAReceberManager; private BaixarParcelaController() { } private boolean validateSalvar() { boolean validate = true; return validate; } public void quitar() { for (Parcela parcela : conta.getParcelas()) { if (parcela.getId() == parcelaABaixar.getId()) { parcela.setSituacao(SituacaoContaType.QUITADA); } } } public void desquitar() { for (Parcela parcela : conta.getParcelas()) { if (parcela.getId() == parcelaABaixar.getId()) { parcela.setSituacao(SituacaoContaType.ABERTA); } } } public String salvar() { try { if (validateSalvar()) { if (conta.getTipoConta() == ContaType.PAGAR) { contaAPagarManager.salvar((ContaAPagar) conta, null); } else { contaAReceberManager.salvar((ContaAReceber) conta); } getMessageCadastroSucesso(); } } catch (Exception e) { getMessageInstabilidade(); e.printStackTrace(); } return "/pages/conta/contaAPagar"; } public Conta getConta() { return conta; } public void setConta(Conta conta) { this.conta = conta; } public CompraManager getCompraManager() { return compraManager; } public void setCompraManager(CompraManager compraManager) { this.compraManager = compraManager; } public ContaAPagarManager getContaAPagarManager() { return contaAPagarManager; } public void setContaAPagarManager(ContaAPagarManager contaAPagarManager) { this.contaAPagarManager = contaAPagarManager; } public ContaAReceberManager getContaAReceberManager() { return contaAReceberManager; } public void setContaAReceberManager(ContaAReceberManager contaAReceberManager) { this.contaAReceberManager = contaAReceberManager; } public Parcela getParcelaABaixar() { return parcelaABaixar; } public void setParcelaABaixar(Parcela parcelaABaixar) { this.parcelaABaixar = parcelaABaixar; } }
true
dc222238ba96b5dc9d13242863deb2ac9c680db5
Java
SaladTomatOignon/Confroid
/Confroid storage service/src/main/java/fr/uge/confroid/web/service/confroidstorageservice/services/UserService.java
UTF-8
1,967
2.328125
2
[ "MIT" ]
permissive
package fr.uge.confroid.web.service.confroidstorageservice.services; import fr.uge.confroid.web.service.confroidstorageservice.models.User; import fr.uge.confroid.web.service.confroidstorageservice.repositories.UserRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class UserService implements UserDetailsService { @Autowired private UserRepo repository; @Autowired private AuthenticationManager authenticationManager; @Autowired private PasswordEncoder passwordEncoder; public List<User> findAll() { return (List<User>) repository.findAll(); } public void save(User user) { repository.save(new User(user.getUsername(), passwordEncoder.encode(user.getPassword()))); } public Optional<User> getByUsername(String username) { return repository.findByUsername(username); } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Optional<User> user = repository.findByUsername(username); if (user.isEmpty()) { throw new UsernameNotFoundException("User '" + username + "' not found"); } return user.get(); } public void login(String username, String password) { authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(username, password) ); } }
true
819d0be0b9ea3aa27e56dde8e7be7a996e9cf016
Java
solostyle/jobsearchdemo
/src/com/example/androidcourse_assignment3/Job.java
UTF-8
2,245
2.546875
3
[]
no_license
package com.example.androidcourse_assignment3; import android.os.Parcel; import android.os.Parcelable; public class Job implements Parcelable { public String company; public String title; public String location; public String desc; public String postedTime; public String jobLink; public String simJobsLink; public Job(String company, String title, String location, String desc, String postedTime, String jobLink, String simJobsLink) { this.company = company; this.title = title; this.location = location; this.desc = desc; this.postedTime = postedTime; this.jobLink = jobLink; this.simJobsLink = simJobsLink; } public Job(Parcel source) { company = source.readString(); title = source.readString(); location = source.readString(); desc = source.readString(); postedTime = source.readString(); jobLink = source.readString(); simJobsLink = source.readString(); } public String getCompany() { return this.company; } public String getTitle() { return this.title; } public String getLocation() { return this.location; } public String getDesc() { return this.desc; } public String getPostedTime() { return this.postedTime; } public String getJobLink() { return this.jobLink; } public String getSimJobsLink() { return this.simJobsLink; } // 99.9% of the time you can just ignore this public int describeContents() { return 0; } // write your object's data to the passed-in Parcel public void writeToParcel(Parcel dest, int flags) { dest.writeString(company); dest.writeString(title); dest.writeString(location); dest.writeString(desc); dest.writeString(postedTime); dest.writeString(jobLink); dest.writeString(simJobsLink); } // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods public static final Parcelable.Creator<Job> CREATOR = new Parcelable.Creator<Job>() { public Job createFromParcel(Parcel in) { return new Job(in); } public Job[] newArray(int size) { return new Job[size]; } }; }
true
8a193713723023a6af44a79f001bdc4295bc9f45
Java
rohitdurai/Rohit-Classroom-Training
/src/PackageDemo/src/com/Rohit/logic/AbstractClass_SavingsAccount.java
UTF-8
261
2.234375
2
[]
no_license
package com.Rohit.logic; public class AbstractClass_SavingsAccount extends AbstractClass_Account { public AbstractClass_SavingsAccount(int accountNo, String accountHolder, double balance){ super(accountNo, accountHolder, balance); } }
true
b8aa8129a051769bd318fe62af15bdc24206f772
Java
JetBrains/intellij-community
/java/java-analysis-impl/src/com/siyeh/ig/fixes/ChangeModifierFix.java
UTF-8
1,815
1.804688
2
[ "Apache-2.0" ]
permissive
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.siyeh.ig.fixes; import com.intellij.modcommand.ModPsiUpdater; import com.intellij.modcommand.PsiUpdateModCommandQuickFix; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiModifier; import com.intellij.psi.PsiModifierList; import com.intellij.psi.PsiModifierListOwner; import com.intellij.psi.util.PsiTreeUtil; import com.siyeh.InspectionGadgetsBundle; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; public class ChangeModifierFix extends PsiUpdateModCommandQuickFix { @PsiModifier.ModifierConstant private final String modifierText; public ChangeModifierFix(@NonNls @PsiModifier.ModifierConstant String modifierText) { this.modifierText = modifierText; } @Override @NotNull public String getName() { return PsiModifier.PACKAGE_LOCAL.equals(modifierText) ? InspectionGadgetsBundle.message("change.modifier.package.private.quickfix") : InspectionGadgetsBundle.message("change.modifier.quickfix", modifierText); } @NotNull @Override public String getFamilyName() { return InspectionGadgetsBundle.message("change.modifier.fix.family.name"); } @Override protected void applyFix(@NotNull Project project, @NotNull PsiElement element, @NotNull ModPsiUpdater updater) { final PsiModifierListOwner modifierListOwner = PsiTreeUtil.getParentOfType(element, PsiModifierListOwner.class); if (modifierListOwner == null) { return; } final PsiModifierList modifiers = modifierListOwner.getModifierList(); if (modifiers == null) { return; } modifiers.setModifierProperty(modifierText, true); } }
true
e3410ffe0567540da702590333113b5865641aac
Java
Team980/ThunderScout-Android
/app/src/main/java/com/team980/thunderscout/MainActivity.java
UTF-8
15,852
1.53125
2
[ "MIT" ]
permissive
/* * MIT License * * Copyright (c) 2016 - 2018 Luke Myers (FRC Team 980 ThunderBots) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.team980.thunderscout; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.content.res.AppCompatResources; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.team980.thunderscout.analytics.matches.MatchesFragment; import com.team980.thunderscout.analytics.rankings.RankingsFragment; import com.team980.thunderscout.backend.AccountScope; import com.team980.thunderscout.home.HomeFragment; import com.team980.thunderscout.preferences.AccountSettingsActivity; import com.team980.thunderscout.preferences.SettingsActivity; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener { public static final String INTENT_FLAG_SHOWN_FRAGMENT = "SHOWN_FRAGMENT"; public static final int INTENT_FLAGS_HOME = 0; public static final int INTENT_FLAGS_MATCHES = 1; public static final int INTENT_FLAGS_RANKINGS = 2; public static final String ACTION_REFRESH_DATA_VIEW = "com.team80.thunderscout.ACTION_REFRESH_DATA_VIEW"; public static final int REQUEST_CODE_AUTH = 1; private boolean accountMenuExpanded = false; //runtime state @Override protected void onCreate(Bundle savedInstanceState) { setTheme(R.style.ThunderScout_BaseTheme_NavigationPane); //Disable splash screen super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); navigationView.getHeaderView(0).setOnClickListener(this); updateAccountHeader(); int shownFragment = getIntent().getIntExtra(INTENT_FLAG_SHOWN_FRAGMENT, INTENT_FLAGS_HOME); Fragment fragment; if (savedInstanceState != null) { //Restore the fragment's instance fragment = getSupportFragmentManager().getFragment(savedInstanceState, "mContent"); } else { switch (shownFragment) { case 0: //INTENT_FLAGS_HOME navigationView.setCheckedItem(R.id.nav_home); fragment = new HomeFragment(); break; case 1: //INTENT_FLAGS_MATCHES navigationView.setCheckedItem(R.id.nav_matches); fragment = new MatchesFragment(); break; case 2: //INTENT_FLAGS_RANKINGS navigationView.setCheckedItem(R.id.nav_rankings); fragment = new RankingsFragment(); break; default: //default to INTENT_FLAGS_HOME navigationView.setCheckedItem(R.id.nav_home); fragment = new HomeFragment(); break; } } FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.fragment, fragment); ft.commit(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment); //Save the fragment's instance getSupportFragmentManager().putFragment(outState, "mContent", fragment); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); } @Override protected void onResume() { super.onResume(); updateAccountHeader(); } @Override public void onBackPressed() { DrawerLayout drawer = findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment); if (fragment instanceof BackPressListener) { //Custom interface that supporting fragments use to intercept the back button if (!((BackPressListener) fragment).onBackPressed()) { super.onBackPressed(); //If they return false, continue normal back behavior } } else { super.onBackPressed(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return super.onOptionsItemSelected(item); } @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); //Main navigation menu if (id == R.id.nav_home) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.fragment, new HomeFragment()); ft.commit(); } else if (id == R.id.nav_matches) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.fragment, new MatchesFragment()); ft.commit(); } else if (id == R.id.nav_rankings) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.fragment, new RankingsFragment()); ft.commit(); } //Secondary navigation menu else if (id == R.id.nav_settings) { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); } else if (id == R.id.nav_about) { Intent intent = new Intent(this, AboutActivity.class); startActivity(intent); } //AccountScope navigation menu else if (id == R.id.nav_account_local) { PreferenceManager.getDefaultSharedPreferences(this).edit() .putString(getResources().getString(R.string.pref_current_account_scope), AccountScope.LOCAL.name()).apply(); updateAccountHeader(); contractAccountMenu(); Intent refreshIntent = new Intent().setAction(MainActivity.ACTION_REFRESH_DATA_VIEW); LocalBroadcastManager.getInstance(this).sendBroadcast(refreshIntent); } else if (id == R.id.nav_account_cloud) { FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { PreferenceManager.getDefaultSharedPreferences(this).edit() .putString(getResources().getString(R.string.pref_current_account_scope), AccountScope.CLOUD.name()).apply(); updateAccountHeader(); contractAccountMenu(); Intent refreshIntent = new Intent().setAction(MainActivity.ACTION_REFRESH_DATA_VIEW); LocalBroadcastManager.getInstance(this).sendBroadcast(refreshIntent); } else { contractAccountMenu(); Intent intent = new Intent(this, AccountSettingsActivity.class); startActivityForResult(intent, REQUEST_CODE_AUTH); } } else if (id == R.id.nav_account_settings) { contractAccountMenu(); Intent intent = new Intent(this, AccountSettingsActivity.class); startActivityForResult(intent, REQUEST_CODE_AUTH); } DrawerLayout drawer = findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } @Override public void onClick(View view) { if (accountMenuExpanded) { contractAccountMenu(); } else { expandAccountMenu(); } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == REQUEST_CODE_AUTH) { //yes this is correct recreate(); } } private void updateAccountHeader() { NavigationView navigationView = findViewById(R.id.nav_view); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); AccountScope currentScope = AccountScope.valueOf(sharedPrefs.getString(getResources().getString(R.string.pref_current_account_scope), AccountScope.LOCAL.name())); ImageView image = navigationView.getHeaderView(0).findViewById(R.id.account_image); switch (currentScope) { case LOCAL: image.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.ic_account_circle_72dp)); //TODO better image ((TextView) navigationView.getHeaderView(0).findViewById(R.id.account_name)).setText(sharedPrefs .getString(getResources().getString(R.string.pref_device_name), Build.MANUFACTURER + " " + Build.MODEL)); ((TextView) navigationView.getHeaderView(0).findViewById(R.id.account_id)).setText("Local storage"); break; case CLOUD: FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { if (user.getPhotoUrl() != null) { Glide.with(this).load(user.getPhotoUrl().toString().replace("s96-c/photo.jpg", "s400-c/photo.jpg")).apply(new RequestOptions().circleCrop()).into(image); } else { image.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.ic_cloud_circle_72dp)); } if (user.getDisplayName() != null) { ((TextView) navigationView.getHeaderView(0).findViewById(R.id.account_name)).setText(user.getDisplayName()); } else { ((TextView) navigationView.getHeaderView(0).findViewById(R.id.account_name)).setText("Signed in"); } if (user.getEmail() != null) { ((TextView) navigationView.getHeaderView(0).findViewById(R.id.account_id)).setText(user.getEmail()); } else if (user.getPhoneNumber() != null) { ((TextView) navigationView.getHeaderView(0).findViewById(R.id.account_id)).setText(user.getPhoneNumber()); } else { ((TextView) navigationView.getHeaderView(0).findViewById(R.id.account_id)).setText("No email or phone number specified"); } } else { image.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.ic_cloud_circle_72dp)); ((TextView) navigationView.getHeaderView(0).findViewById(R.id.account_name)).setText("Not signed in"); ((TextView) navigationView.getHeaderView(0).findViewById(R.id.account_id)).setText("ThunderCloud"); } break; } } private void expandAccountMenu() { NavigationView view = findViewById(R.id.nav_view); ImageView dropdown = view.getHeaderView(0).findViewById(R.id.account_dropdown); view.getMenu().clear(); view.inflateMenu(R.menu.drawer_account_menu); view.getMenu().findItem(R.id.nav_account_local).setTitle(PreferenceManager.getDefaultSharedPreferences(this) .getString(getResources().getString(R.string.pref_device_name), Build.MANUFACTURER + " " + Build.MODEL)); FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); if (user != null) { if (user.getDisplayName() != null) { view.getMenu().findItem(R.id.nav_account_cloud).setTitle(user.getDisplayName()); } else if (user.getEmail() != null) { view.getMenu().findItem(R.id.nav_account_cloud).setTitle(user.getEmail()); } else if (user.getPhoneNumber() != null) { view.getMenu().findItem(R.id.nav_account_cloud).setTitle(user.getPhoneNumber()); } else { view.getMenu().findItem(R.id.nav_account_cloud).setTitle("ThunderCloud"); } } else { view.getMenu().findItem(R.id.nav_account_cloud).setTitle("Sign in to ThunderCloud"); view.getMenu().findItem(R.id.nav_account_settings).setEnabled(false); view.getMenu().findItem(R.id.nav_account_settings).setVisible(false); } dropdown.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.ic_arrow_drop_up_24dp)); accountMenuExpanded = true; } private void contractAccountMenu() { NavigationView view = findViewById(R.id.nav_view); ImageView dropdown = view.getHeaderView(0).findViewById(R.id.account_dropdown); view.getMenu().clear(); view.inflateMenu(R.menu.drawer_menu); if (getSupportFragmentManager().findFragmentById(R.id.fragment).getClass() == HomeFragment.class) { view.setCheckedItem(R.id.nav_home); } else if (getSupportFragmentManager().findFragmentById(R.id.fragment).getClass() == MatchesFragment.class) { view.setCheckedItem(R.id.nav_matches); } else if (getSupportFragmentManager().findFragmentById(R.id.fragment).getClass() == RankingsFragment.class) { view.setCheckedItem(R.id.nav_rankings); } dropdown.setImageDrawable(AppCompatResources.getDrawable(this, R.drawable.ic_arrow_drop_down_24dp)); accountMenuExpanded = false; } public interface BackPressListener { /** * @return whether to stop processing the input further */ boolean onBackPressed(); } }
true
94988c768dfed43a61d4d02c49adcbff74471dce
Java
Carole-Anne/Gestion-de-Muldo-Java
/src/Services/Main.java
UTF-8
5,379
2.25
2
[]
no_license
package Services; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import Entities.Muldo; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class Main extends Application { public static Stage primaryStage; public static Service service; @Override public void start(Stage ps) { try { primaryStage = ps; BorderPane root = (BorderPane)FXMLLoader.load(getClass().getResource("./../IHM/PrincipalView.fxml")); Scene scene = new Scene(root,950,500); scene.getStylesheets().add(getClass().getResource("./../IHM/application.css").toExternalForm()); primaryStage.setScene(scene); primaryStage.show(); } catch(Exception e) { e.printStackTrace(); } } public static void main(String[] args) throws SQLException { EntityManagerFactory emf; EntityManager em; try{ emf = CreateEntityManagerFactory.getInstance(); em = emf.createEntityManager(); service = new Service(em); }catch(Exception e){ em = createBD(); service = new Service(em); service.initColor(); service.initMuldo(); service.initProp(); } launch(args); } private static EntityManager createBD() throws SQLException { Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "formation"); Statement statement = connection.createStatement(); statement.execute("CREATE DATABASE muldo"); connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/muldo", "postgres", "formation"); statement = connection.createStatement(); //Table couleur statement.execute("CREATE TABLE public.couleur (" +"id SERIAL NOT NULL," +"nom character varying NOT NULL," +"url character varying(80) NOT NULL," +"urlicon character varying(80) NOT NULL," +"nbfemelle integer NOT NULL DEFAULT 0," +"nbmale integer NOT NULL DEFAULT 0," +"CONSTRAINT couleur_pkey PRIMARY KEY (id)" +") WITH (OIDS = FALSE)" +"TABLESPACE pg_default"); statement.execute("ALTER TABLE public.couleur OWNER to postgres"); //Table groupe statement.execute("CREATE TABLE public.groupe(" +"id SERIAL NOT NULL," +"nom character varying(50) NOT NULL," +"type character varying(50) NOT NULL," +"CONSTRAINT groupe_pkey PRIMARY KEY (id))" +"WITH (OIDS = FALSE) TABLESPACE pg_default"); statement.execute("ALTER TABLE public.couleur OWNER to postgres"); //Table muldo statement.execute("CREATE TABLE public.muldo (" +"id SERIAL NOT NULL," +"idcouleur integer NOT NULL," +"nom character varying(30) NOT NULL," +"nbenfant integer NOT NULL DEFAULT 0," +"sexe integer NOT NULL," +"visible boolean NOT NULL DEFAULT true," +"fecond boolean NOT NULL DEFAULT false," +"nbsaillies integer NOT NULL," +"idmere integer," +"idpere integer," +"nbsailliesused integer NOT NULL DEFAULT 0," +"CONSTRAINT muldo_pkey PRIMARY KEY (id)," +"CONSTRAINT fk_id_idcouleur FOREIGN KEY (idcouleur) " +"REFERENCES public.couleur (id) MATCH SIMPLE " +"ON UPDATE NO ACTION " +"ON DELETE NO ACTION," +"CONSTRAINT fk_id_idmere FOREIGN KEY (idmere) " +"REFERENCES public.muldo (id) MATCH SIMPLE " +"ON UPDATE NO ACTION " +"ON DELETE NO ACTION, " +"CONSTRAINT fk_id_idpere FOREIGN KEY (idpere) " +"REFERENCES public.muldo (id) MATCH SIMPLE " +"ON UPDATE NO ACTION " +"ON DELETE NO ACTION) WITH (OIDS = FALSE) " +"TABLESPACE pg_default"); statement.execute("ALTER TABLE public.muldo OWNER to postgres"); statement.execute("CREATE INDEX fki_fk_id_idcouleur " +"ON public.muldo USING btree (idcouleur) TABLESPACE pg_default"); statement.execute("CREATE INDEX fki_fk_id_idmere " +"ON public.muldo USING btree (idmere) TABLESPACE pg_default"); statement.execute("CREATE INDEX fki_fk_id_idpere " +"ON public.muldo USING btree (idpere) TABLESPACE pg_default"); //Table muldogroupe statement.execute("CREATE TABLE public.muldogroupe (" +"idmuldo integer NOT NULL," +"idgroupe integer NOT NULL," +"CONSTRAINT muldogroupe_pkey PRIMARY KEY (idgroupe, idmuldo)," +"CONSTRAINT fk_id_idgroupe FOREIGN KEY (idgroupe) " +"REFERENCES public.groupe (id) MATCH SIMPLE " +"ON UPDATE NO ACTION " +"ON DELETE NO ACTION, " +"CONSTRAINT fk_id_idmuldo FOREIGN KEY (idmuldo) " +"REFERENCES public.muldo (id) MATCH SIMPLE " +"ON UPDATE NO ACTION ON DELETE NO ACTION) " +"WITH (OIDS = FALSE) TABLESPACE pg_default"); statement.execute("ALTER TABLE public.muldogroupe OWNER to postgres"); statement.execute("CREATE INDEX fki_fk_id_idgroupe ON public.muldogroupe USING btree " +"(idgroupe) TABLESPACE pg_default"); statement.execute("CREATE INDEX fki_fk_id_idmuldo ON public.muldogroupe USING btree " +"(idmuldo) TABLESPACE pg_default"); EntityManagerFactory emf = CreateEntityManagerFactory.getInstance(); EntityManager em = emf.createEntityManager(); return em; } }
true
9a79d8b3b4d63ac33ee76c94e6dd9d9bb1524cdd
Java
dabpessoa/pathcontrol
/src/main/java/br/com/digitoglobal/service/listenercontrol/DataListenerControl.java
UTF-8
4,092
2.84375
3
[]
no_license
package br.com.digitoglobal.service.listenercontrol; import br.com.digitoglobal.service.basiccontrol.DataBasicControl; import java.io.IOException; import java.nio.file.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static java.nio.file.StandardWatchEventKinds.*; /** * Created by diego.pessoa on 02/08/2017. */ public class DataListenerControl extends DataBasicControl { private Path path; private WatchService watchService; private WatchKey watchKey; private List<DataListenerThread> dataListenerThreads; public DataListenerControl(Path path) { this(path, null); } public DataListenerControl(Path path, DataEvent[] dataEvents) { super(path); this.dataListenerThreads = new ArrayList<>(); this.path = path; try { watchService = FileSystems.getDefault().newWatchService(); if (dataEvents == null || dataEvents.length == 0) { watchKey = this.path.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); } else { List<WatchEvent.Kind<Path>> events = Arrays.stream(dataEvents).map(de -> de.toWatchEventKind()).collect(Collectors.toList()); watchKey = this.path.register(watchService, events.toArray(new WatchEvent.Kind[events.size()])); } } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Não foi possível criar uma listener. ERROR: "+e.getMessage()); } } public void registerListener(DataListener dataListener) { DataListenerThread dataListenerThread = new DataListenerThread(watchService, dataListener); dataListenerThreads.add(dataListenerThread); new Thread(dataListenerThread).start(); } public List<DataListener> getListeners() { return dataListenerThreads.parallelStream().map(dlt -> dlt.getDataListener()).collect(Collectors.toList()); } public List<DataListenerThread> getDataListenerThreads() { return dataListenerThreads; } public void close() throws IOException { for (DataListenerThread dataListenerThread : dataListenerThreads) { dataListenerThread.stop(); } watchService.close(); } // // // // // public static void main(String[] args) { // // Path path = new File("C:\\Users\\diego.pessoa\\Desktop\\teste").toPath(); // // // try { // // WatchService watcher = FileSystems.getDefault().newWatchService(); // // WatchKey key = path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); // // while (true) { // // // wait for a key to be available // key = watcher.take(); // // // for (WatchEvent<?> event : key.pollEvents()) { // // get event type // WatchEvent.Kind<?> kind = event.kind(); // // // get file name // @SuppressWarnings("unchecked") // WatchEvent<Path> ev = (WatchEvent<Path>) event; // Path fileName = ev.context(); // // System.out.println(kind.name() + ": " + fileName); // // if (kind == OVERFLOW) { // continue; // } else if (kind == ENTRY_CREATE) { // // // process create event // // } else if (kind == ENTRY_DELETE) { // // // process delete event // // } else if (kind == ENTRY_MODIFY) { // // // process modify event // // } // } // // // IMPORTANT: The key must be reset after processed // boolean valid = key.reset(); // if (!valid) { // break; // } // // } // // } catch (IOException | InterruptedException e) { // System.err.println(e); // } // // } }
true
e73720905d43f0d000ddc120cf9d079b2b912a70
Java
aydinaysenur/java8_functional_programming
/src/functionalInterfaces/ConcreteFunctional.java
UTF-8
552
3.09375
3
[]
no_license
package functionalInterfaces; import java.time.LocalDateTime; public class ConcreteFunctional { public void useGetNameMethod(IFunctionalInterface functionalInterface) { System.out.println(functionalInterface.getName()); } /** * useGetNameMethod methodunu IFunctionalInterface interface'ini implement eden * hicbir class yokken cagiriniz. */ public static void main(String args[]) { ConcreteFunctional concreteFunctional = new ConcreteFunctional(); concreteFunctional.useGetNameMethod(() -> "Aysenur"); } }
true
e2f3c839378c7ec9ba290cdecc9a3d79c01e7d5e
Java
Vardominator/ShiferawResearch
/CellSimFXML_12_29_15/src/cellsimfxml/CellSimFXML.java
UTF-8
1,224
2.375
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 cellsimfxml; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; /** * * @author varderes */ public class CellSimFXML extends Application { @Override public void start(Stage mainStage) throws Exception { // Link FXML file Parent root = FXMLLoader.load(getClass().getResource("design.fxml")); Scene scene = new Scene(root); // Link CSS file scene.getStylesheets().add(CellSimFXML.class.getResource("CascadeStyleSheet.css").toExternalForm()); mainStage.setResizable(false); mainStage.setTitle("Heart Cell Simulator"); mainStage.setScene(scene); mainStage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
true
91b8f2f580df65ffbf96bacaf1483fea84a26e59
Java
EronWright/pulsar
/pulsar-broker/src/test/java/org/apache/pulsar/broker/transaction/TransactionClientReconnectTest.java
UTF-8
6,440
1.578125
2
[ "Apache-2.0", "Zlib", "LicenseRef-scancode-protobuf", "BSD-2-Clause", "LicenseRef-scancode-unknown" ]
permissive
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pulsar.broker.transaction; import com.google.common.collect.Sets; import org.apache.pulsar.broker.TransactionMetadataStoreService; import org.apache.pulsar.client.api.MessageId; import org.apache.pulsar.client.api.PulsarClient; import org.apache.pulsar.client.api.PulsarClientException; import org.apache.pulsar.client.api.transaction.TransactionCoordinatorClientException; import org.apache.pulsar.client.impl.PulsarClientImpl; import org.apache.pulsar.client.impl.transaction.TransactionImpl; import org.apache.pulsar.common.naming.NamespaceName; import org.apache.pulsar.common.naming.TopicName; import org.apache.pulsar.common.policies.data.ClusterData; import org.apache.pulsar.common.policies.data.TenantInfo; import org.apache.pulsar.transaction.coordinator.TransactionCoordinatorID; import org.awaitility.Awaitility; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertTrue; import static org.testng.FileAssert.fail; public class TransactionClientReconnectTest extends TransactionTestBase { private final static String RECONNECT_TOPIC = "persistent://public/txn/txn-client-reconnect-test"; @BeforeMethod(alwaysRun = true) public void setup() throws Exception { setBrokerCount(1); super.internalSetup(); String[] brokerServiceUrlArr = getPulsarServiceList().get(0).getBrokerServiceUrl().split(":"); String webServicePort = brokerServiceUrlArr[brokerServiceUrlArr.length -1]; admin.clusters().createCluster(CLUSTER_NAME, new ClusterData("http://localhost:" + webServicePort)); admin.tenants().createTenant("public", new TenantInfo(Sets.newHashSet(), Sets.newHashSet(CLUSTER_NAME))); admin.namespaces().createNamespace("public/txn", 10); admin.tenants().createTenant(NamespaceName.SYSTEM_NAMESPACE.getTenant(), new TenantInfo(Sets.newHashSet("appid1"), Sets.newHashSet(CLUSTER_NAME))); admin.namespaces().createNamespace(NamespaceName.SYSTEM_NAMESPACE.toString()); admin.topics().createNonPartitionedTopic(RECONNECT_TOPIC); admin.topics().createSubscription(RECONNECT_TOPIC, "test", MessageId.latest); admin.topics().createPartitionedTopic(TopicName.TRANSACTION_COORDINATOR_ASSIGN.toString(), 1); pulsarClient = PulsarClient.builder() .serviceUrl(getPulsarServiceList().get(0).getBrokerServiceUrl()) .statsInterval(0, TimeUnit.SECONDS) .enableTransaction(true) .build(); } @AfterMethod(alwaysRun = true) protected void cleanup() { super.internalCleanup(); } @Test public void testTransactionClientReconnectTest() throws PulsarClientException, ExecutionException, InterruptedException { ((PulsarClientImpl) pulsarClient).getLookup() .getPartitionedTopicMetadata(TopicName.TRANSACTION_COORDINATOR_ASSIGN).get(); Awaitility.await().until(() -> { pulsarClient.newTransaction() .withTransactionTimeout(200, TimeUnit.MILLISECONDS).build().get(); return true; }); TransactionImpl transaction = (TransactionImpl) pulsarClient.newTransaction() .withTransactionTimeout(200, TimeUnit.MILLISECONDS).build().get(); TransactionMetadataStoreService transactionMetadataStoreService = getPulsarServiceList().get(0).getTransactionMetadataStoreService(); transactionMetadataStoreService.removeTransactionMetadataStore(TransactionCoordinatorID.get(0)); // transaction client will reconnect try { pulsarClient.newTransaction() .withTransactionTimeout(200, TimeUnit.MILLISECONDS).build().get(); fail(); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof TransactionCoordinatorClientException.CoordinatorNotFoundException); } try { transaction.registerProducedTopic(RECONNECT_TOPIC).get(); fail(); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof TransactionCoordinatorClientException.MetaStoreHandlerNotReadyException); } try { transaction.registerAckedTopic(RECONNECT_TOPIC, "test").get(); fail(); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof TransactionCoordinatorClientException.MetaStoreHandlerNotReadyException); } try { transaction.commit().get(); fail(); } catch (ExecutionException e) { assertTrue(e.getCause() instanceof TransactionCoordinatorClientException.MetaStoreHandlerNotReadyException); } transactionMetadataStoreService.addTransactionMetadataStore(TransactionCoordinatorID.get(0)); // wait transaction coordinator init success Awaitility.await().until(() -> { pulsarClient.newTransaction() .withTransactionTimeout(200, TimeUnit.MILLISECONDS).build().get(); return true; }); transaction = (TransactionImpl) pulsarClient.newTransaction() .withTransactionTimeout(200, TimeUnit.MILLISECONDS).build().get(); transaction.registerProducedTopic(RECONNECT_TOPIC).get(); transaction.registerAckedTopic(RECONNECT_TOPIC, "test").get(); transaction.commit().get(); } }
true
f26cc5b16392580ea6b8eb054383ff13509cd98c
Java
lynnlee1229/glink
/glink-sql/src/main/java/com/github/tm/glink/sql/udf/extention/output/GL_PointToCSV.java
UTF-8
418
1.992188
2
[]
no_license
package com.github.tm.glink.sql.udf.extention.output; import org.apache.flink.table.functions.ScalarFunction; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.Point; @SuppressWarnings("checkstyle:TypeName") public class GL_PointToCSV extends ScalarFunction { public static String eval(Geometry geom) { Point point = (Point) geom; return point.getX() + "," + point.getY(); } }
true
2e6341e30a3e6a0bf20781ce5f25e6d136837877
Java
mark-micallef/happyclients
/src/main/java/com/mea/happyclients/users/plans/BasicPlan.java
UTF-8
389
2.109375
2
[]
no_license
package com.mea.happyclients.users.plans; public class BasicPlan extends Plan { public BasicPlan() { super(); name = "Basic"; } @Override public int getPriceInEuroCents() { return 995; } @Override public int getNumSmsPerMonth() { return 500; } @Override public int getMaxSenderIDs() { return 1; } }
true
afe883cf85882f91fc7fa3ec9019a3d812f53ac7
Java
Shangbao/TelematicsApp
/app/src/main/java/com/hangon/fragment/music/MusicService.java
UTF-8
8,278
2.390625
2
[ "Apache-2.0" ]
permissive
package com.hangon.fragment.music; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.support.annotation.Nullable; import android.util.Log; import android.widget.SeekBar; import com.hangon.bean.music.Mp3; import com.hangon.bean.music.Music; import com.hangon.common.Constants; import com.hangon.common.MusicUtil; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Created by Chuan on 2016/5/14. */ public class MusicService extends Service implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener { private static MediaPlayer mediaPlayer = new MediaPlayer();//音乐播放器 private int playMode = Constants.SEQUENCE_MODEL;//控制播放模式 private int currIndex = 0;//当前播放的索引 private List<Music> list; private int state = Constants.IDLE; private MyBinder myBinder = new MyBinder(); private int currentPosition; private boolean flag; ExecutorService es = Executors.newSingleThreadExecutor();// 单线程的执行器 private static final int updateProgress = 1; private static final int updateCurrentMusic = 2; private static final int updateDuration = 3; public static final String ACTION_UPDATE_PROGRESS = "com.hangon.fragment.music.UPDATE_PROGRESS"; public static final String ACTION_UPDATE_DURATION = "com.hangon.fragment.music.UPDATE_DURATION"; public static final String ACTION_UPDATE_CURRENT_MUSIC = "com.hangon.fragment.music.UPDATE_CURRENT_MUSIC"; //向MusicFragment传递消息 private Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { //更新进度 case updateProgress: toUpdateProgress(); break; //更新歌曲长度 case updateDuration: toUpdateDuration(); break; //更新歌曲 case updateCurrentMusic: toUpdateCurrentMusic(); break; } } }; // 播放上一曲 private void playPrevious() { if (playMode == Constants.SEQUENCE_MODEL) { if ((currIndex - 1) >= 0) { currIndex--; } else { currIndex = list.size() - 1; } start(currIndex); } else if (playMode == Constants.RANDOM_MODEL) { currIndex = (int) (Math.random() * list.size()); start(currIndex); } else if (playMode == Constants.CIRCULATION_MODEL) { start(currIndex); } } // 播放下一曲 private void playNext() { if (playMode == Constants.SEQUENCE_MODEL) { if ((currIndex + 1) < list.size()) { currIndex++; } else { currIndex = 0; } start(currIndex); } else if (playMode == Constants.RANDOM_MODEL) { currIndex = (int) (Math.random() * list.size()); start(currIndex); } else if (playMode == Constants.CIRCULATION_MODEL) { start(currIndex); } } // 播放与暂停 // 从上一次的播放状态开始播放 private void play(int currIndex) { if (state == Constants.PAUSE) { mediaPlayer.start(); } else { start(currIndex); } state = Constants.PLAY; } // 停止播放 private void stop() { if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); state = Constants.STOP; } } //暂停播放 private void pause() { mediaPlayer.pause(); state = Constants.PAUSE; } //开始播放 private void start(int currIndex) { if (currIndex < list.size()) { Music m = list.get(currIndex); try { mediaPlayer.reset();// 让播放器回到空闲 mediaPlayer.setDataSource(m.getUrl());// 设置文件播放的路径 mediaPlayer.prepare(); mediaPlayer.start();// 开始播放 initSeekBar(); handler.sendEmptyMessage(updateCurrentMusic); handler.sendEmptyMessage(updateDuration); es.execute(new seekBar()); } catch (Exception e) { e.printStackTrace(); } } } // 实现播放进度 class seekBar implements Runnable { public seekBar() { flag = true; } @Override public void run() { while (flag) { if (mediaPlayer.getCurrentPosition() < mediaPlayer .getDuration()) { handler.sendEmptyMessage(updateProgress); } else { flag = false; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } private void initSeekBar() { currentPosition = 0; } private void toUpdateProgress() { if (mediaPlayer != null && mediaPlayer.isPlaying()) { int progress = mediaPlayer.getCurrentPosition(); Intent intent = new Intent(); intent.setAction(ACTION_UPDATE_PROGRESS); intent.putExtra(ACTION_UPDATE_PROGRESS, progress); sendBroadcast(intent); handler.sendEmptyMessageDelayed(updateProgress, 1000); } } private void toUpdateDuration() { if (mediaPlayer != null) { int duration = mediaPlayer.getDuration(); Intent intent = new Intent(); intent.setAction(ACTION_UPDATE_DURATION); intent.putExtra(ACTION_UPDATE_DURATION, duration); sendBroadcast(intent); } } private void toUpdateCurrentMusic() { Intent intent = new Intent(); intent.setAction(ACTION_UPDATE_CURRENT_MUSIC); intent.putExtra(ACTION_UPDATE_CURRENT_MUSIC, currIndex); sendBroadcast(intent); } private void outSetPlayMode(int playMode) { this.playMode = playMode; } @Override public void onCompletion(MediaPlayer mp) { playNext(); } public boolean onError(MediaPlayer mp, int what, int extra) { mediaPlayer.reset(); return false; } public class MyBinder extends Binder { public void toStartActivity() { handler.sendEmptyMessage(updateCurrentMusic); handler.sendEmptyMessage(updateDuration); } public void startPlay(int currIndex) { play(currIndex); } public void stopPlay() { stop(); } public void toNext() { playNext(); } public void toPrevious() { playPrevious(); } public void toPause() { pause(); } public void toStart(int id) { currIndex = id; start(currIndex); } public void changeProgress(int progress) { if (mediaPlayer != null) { currentPosition = progress * 1000; mediaPlayer.seekTo(currentPosition); } } public void setPlayMode(int playMode) { outSetPlayMode(playMode); } } @Nullable @Override public IBinder onBind(Intent intent) { return myBinder; } @Override public void onCreate() { super.onCreate(); list = new ArrayList<Music>(); list = MusicUtil.getMusicData(MusicService.this); Log.e("listsize", list.size() + ""); start(currIndex); mediaPlayer.setOnCompletionListener(this); mediaPlayer.setOnErrorListener(this); } @Override public void onDestroy() { super.onDestroy(); flag = false; mediaPlayer = null; } }
true