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
09d4427831f6ee2c4017259c0ca6659b25e40bde
Java
josome1718daw2/Stratego
/src/com/login/Registre_Func.java
UTF-8
1,141
2.421875
2
[]
no_license
package com.login; import java.sql.*; import java.io.*; import java.util.*; public class Registre_Func { public void registreUsuari( String uname) throws IOException { FileInputStream in = new FileInputStream("C:\\xampp\\htdocs\\Repositorio\\Stratego\\WEB-INF\\database.properties"); Properties props = new Properties(); props.load(in); in.close(); FileOutputStream out = new FileOutputStream("C:\\xampp\\htdocs\\Repositorio\\Stratego\\WEB-INF\\database.properties"); props.setProperty("username", uname); props.store(out, null); out.close(); } public void registrePassword(String pass) throws IOException { FileInputStream in = new FileInputStream("C:\\xampp\\htdocs\\Repositorio\\Stratego\\WEB-INF\\database.properties"); Properties props = new Properties(); props.load(in); in.close(); FileOutputStream out = new FileOutputStream("C:\\xampp\\htdocs\\Repositorio\\Stratego\\WEB-INF\\database.properties"); props.setProperty("password", pass); props.store(out, null); out.close(); } }
true
a342a5ee5da1fa91d7728d3fe137ae2d3c4307d4
Java
jun0811/Doit
/backend/src/main/java/com/ssafy/doit/model/group/GroupHashTag.java
UTF-8
529
1.898438
2
[]
no_license
package com.ssafy.doit.model.group; import lombok.*; import javax.persistence.*; @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor @Builder @Table(name = "`group_has_tag`") public class GroupHashTag { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name = "tag_pk") @NonNull private HashTag hashTag; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name = "group_pk") @NonNull private Group group; }
true
bbef2e10579891ec5b424fb73721eb48f1d2ff3f
Java
pcache/helloscweb
/src/main/java/com/hellosc/helloscweb/mapper/UserInfoMapper.java
UTF-8
241
1.773438
2
[]
no_license
package com.hellosc.helloscweb.mapper; import java.util.List; import org.mybatis.spring.annotation.MapperScan; import com.hellosc.helloscweb.entity.User; @MapperScan public interface UserInfoMapper { public List<User> getUserList(); }
true
1cf632cac94c0e95bc82acbd2865e0be1f136390
Java
kong430/Madcamp1_2
/app/src/main/java/com/example/madcamp1_2_2/SplashActivity.java
UTF-8
5,323
2.265625
2
[]
no_license
package com.example.madcamp1_2_2; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; public class SplashActivity extends AppCompatActivity { // Request code for READ_CONTACTS. It can be any number > 0. public static final int REQUEST_READ_CONTACTS = 79; public static final int REQUEST_WRITE_CONTACTS = 132; private static final int REQUEST_F_LOCATION = 101; Activity mActivity; Context mContext; Handler handler; int permissionCount = 0; @Override protected void onCreate(Bundle savedInstanceStare) { super.onCreate(savedInstanceStare); setContentView(R.layout.activity_splash); mActivity = this; mContext = getApplicationContext(); handler = new Handler(); String[] s = new String[]{"android.permission.ACCESS_FINE_LOCATION", "android.permission.READ_CONTACTS", "android.permission.WRITE_CONTACTS"}; if(hasPermissions(mContext, s)) { handler.postDelayed(new Runnable() { @Override public void run() { Log.d("yjyj", "in postdelay"); Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); finish(); } }, 1000); } checkPermission(Manifest.permission.ACCESS_FINE_LOCATION, REQUEST_F_LOCATION); Log.d("yjyj", "count is" + permissionCount); } public void checkPermission(String permission, int requestCode) { if (ContextCompat.checkSelfPermission(mActivity, permission) != PackageManager.PERMISSION_GRANTED) { // Requesting the permission ActivityCompat.requestPermissions(mActivity, new String[] { permission }, requestCode); } else { permissionCount++; } } public void onRequestPermissionsResult (int requestCode, String permissions[], int[] grantResults) { Log.d("yjyj", "In Splash Activity, onRequestPermissionsResult"); switch (requestCode) { case REQUEST_READ_CONTACTS: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.d("yjyj", "In Splash Activity, case Read"); permissionCount++; checkPermission(Manifest.permission.WRITE_CONTACTS, REQUEST_WRITE_CONTACTS); } else { // permission denied,Disable the // functionality that depends on this permission. } break; } case REQUEST_WRITE_CONTACTS: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { permissionCount++; if(permissionCount >= 3) { handler.postDelayed(new Runnable() { @Override public void run() { Log.d("yjyj", "in postdelay"); Intent intent = new Intent(getApplicationContext(), MainActivity.class); startActivity(intent); finish(); } }, 1000); } Log.d("yjyj", "In Splash Activity, case Write"); } else { // permission denied,Disable the // functionality that depends on this permission. } break; } case REQUEST_F_LOCATION: { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { permissionCount++; checkPermission(Manifest.permission.READ_CONTACTS, REQUEST_READ_CONTACTS); Log.d("yjyj", "In Splash Activity, case Location"); } else { // permission denied,Disable the // functionality that depends on this permission. } break; } } } public static boolean hasPermissions(Context context, String[] permissions) { if (context != null && permissions != null) { for (String permission : permissions) { if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) { return false; } } } return true; } @Override public void onPause() { Log.d("yjyj", "In Splash, onPuase"); super.onPause(); //finish(); } @Override public void onStop() { Log.d("yjyj", "In Splash, onStop"); super.onStop(); } }
true
53f642d8ce669f9bb05f6e8cae2e812ff43a6819
Java
WuJiaXingGit/xiongdi
/xiongdi-houduan/xiongdi-admin/src/main/java/io/xiongdi/modules/oss/service/SysOssService.java
UTF-8
411
1.695313
2
[]
no_license
package io.xiongdi.modules.oss.service; import com.baomidou.mybatisplus.extension.service.IService; import io.xiongdi.common.utils.PageUtils; import io.xiongdi.modules.oss.entity.SysOssEntity; import java.util.Map; /** * 文件上传 service * @author wujiaxing * @date 2019-08-06 */ public interface SysOssService extends IService<SysOssEntity> { PageUtils queryPage(Map<String, Object> params); }
true
da6b87ecfdd2fcdd91318f76f721ce030405d3a1
Java
rffzahra/Global-Movie-Database
/EAD/src/java/com/hibernate/eao/UserPurchaseEao.java
UTF-8
810
1.953125
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.hibernate.eao; import com.hibernate.entity.Movie; import com.hibernate.entity.UserPurchase; import java.util.Date; import java.util.List; public interface UserPurchaseEao { void create(UserPurchase userPurchase); void saveOrUpdate(UserPurchase userPurchase); boolean UserPurchaseIn(String UserPurchName,String movieName,String moviePrice,Date purchaseDate); List<UserPurchase> getPurchaseDetails(String flmNm); List<UserPurchase> getUserPurchaseCheck(String purchaseUserName); // boolean UserPurchaseCheck(String movieName, String purchaseUserName); }
true
e352870540a1ae24efef0bfc7e6ec0b6ac6cf511
Java
anshu0157/AlgorithmAndDataStructure
/AlgorithmAndDatastructure_JAVA/src/d_binarytree/TreeNode.java
UHC
2,478
3.984375
4
[]
no_license
package d_binarytree; //Ʈ ϴ Ŭ public class TreeNode { private int itsKey; // key private Object itsValue; // value private TreeNode nodes[] = new TreeNode[2]; // ڽ ΰ Ƿ ΰ node ´. // public TreeNode(int key, Object value) { itsKey = key; itsValue = value; System.out.println("Start TreMapNode"); } // ڽ select (Է key key 0.. ʾ or ʾ ) public int selectSubNode(int key) { return (key < itsKey)? 0 : 1 ; } // key ˻ؼ ġϸ / ġ ڽij pivot ̵ public Object find(int key) { // ġϴ Ű ã ! if(key == itsKey) return itsValue; // Ű ġ ٽ ڽij ؼ ˻ (=pivot̵) return findSub(selectSubNode(key), key); } public Object findSub(int node, int key) { // شϴ ġ ڽ 尡 null , شϴ ġ ڽij findԼ return nodes[node] == null? null : nodes[node].find(key); } // ߰ : key ߰. public void add(int key, Object value) { // key key ġϸ value (ex.topNode.addù , key topNode key ġϸ , topNode value) if(key == itsKey) itsValue = value; else SubNode(selectSubNode(key), key, value); // case1. SubNode( 0 , key, value) : ο Ű ( key topNode key ۴) - // case2. SubNode( 1 , key, value) : ο Ű ū ( key topNode key ũ) - } private void SubNode(int node, int key, Object value) { // ش ġ node -> ġ ο . add Ϸ! if(nodes[node]==null) nodes[node] = new TreeNode(key, value); // ش ġ ̹ node ִ -> ش ġ add . (, topNode ƴ϶ topNode ڽ ϳ 尡 . pivot ̵) // itsKey topNode Key ڽij Key ǰ? else nodes[node].add(key, value); } }
true
f0afd863f77c643aa4f69f33468dd4b097a2aead
Java
kexiaomeng/designModel
/Facade/src/com/sun/facade/Facade.java
UTF-8
681
2.875
3
[]
no_license
package com.sun.facade; import com.sun.facade.sub.system.SubSystemA; import com.sun.facade.sub.system.SubSystemB; import com.sun.facade.sub.system.SubSystemC; public class Facade { private SubSystemA systemA; private SubSystemB systemB; private SubSystemC systemC; public Facade() { systemA = new SubSystemA(); systemB = new SubSystemB(); systemC = new SubSystemC(); } public void methodA() { systemA.methodA(); systemB.methodA(); systemC.methodA(); } public void methodB() { systemB.methodA(); systemC.methodA(); systemA.methodA(); } public static void main(String[] args) { Facade facade = new Facade(); facade.methodA(); } }
true
4f249a2e72c98f7378b0718d7beaa5ce5560d6fa
Java
zduan001/company
/src/com/company/Main.java
UTF-8
216,701
2.390625
2
[]
no_license
package com.company; import apple.laf.JRSUIUtils; import com.sun.tools.corba.se.idl.constExpr.Negative; import javax.security.auth.callback.CallbackHandler; import java.awt.*; import java.io.PrintWriter; import java.lang.reflect.Array; import java.util.*; import java.util.List; public class Main { public static void main(String[] args) { // Solution279 s279 = new Solution279(); // System.out.println(s279.numSquares(7168)); // Solution250 s250 = new Solution250(); // TreeNode root = new TreeNode(5); // TreeNode left = new TreeNode(1); // TreeNode right = new TreeNode(5); // TreeNode leftleft = new TreeNode(5); // TreeNode leftright = new TreeNode(5); // TreeNode rightright = new TreeNode(5); // root.left = left; // root.right = right; // left.left = leftleft; // left.right = leftright; // right.right = rightright; // System.out.println(s250.countUnivalSubtrees(root)); // List<Integer> l1 = new ArrayList<Integer>(Arrays.asList(1,2)); // List<Integer> l2 = new ArrayList<>(Arrays.asList(3)); // List<Integer> l3 = new ArrayList<>(Arrays.asList(4,5,6)); // List<List<Integer>> list = new ArrayList<>(); // list.add(l1); // list.add(l2); // list.add(l3); // Vector2D v2d = new Vector2D(list); // while(v2d.hasNext()) { // System.out.println(v2d.next()); // } // Solution254 s254 = new Solution254(); // s254.getFactors(12); // Solution259 s259 = new Solution259(); // System.out.println(s259.threeSumSmaller(new int[] {3,1,0,-2},4 )); // Solution261 s261 = new Solution261(); // int[][] edges = new int[][] { // {0,1}, // {1,2}, // {2,3}, // {1,3}, // {1,4}}; // System.out.println(s261.validTree(5, edges)); // Solution263 s263 = new Solution263(); // System.out.println(s263.isUgly(6)); // Solution264 s264 = new Solution264(); // System.out.println(s264.nthUglyNumber(10)); // Solution265 s265 = new Solution265(); // int[][] input = new int[][]{{1,5,3},{2,9,4}}; // System.out.println(s265.minCostII(input)); // Solution267 s267 = new Solution267(); // List<String> res = s267.generatePalindromes("aabb"); // Solution268 s268 = new Solution268(); // int res = s268.missingNumber(new int[] {0,1,3}); // Solution269 s269 = new Solution269(); //// String[] input = new String[] {"wrt", "wrf", "er", "ett", "rftt"}; // String[] input = new String[] {"z", "x"}; // String res = s269.alienOrder(input); // Codec271 s271 = new Codec271(); // String s = s271.encode(new ArrayList<String>(Arrays.asList("", ""))); // List<String> res = s271.decode(s); // Solution274 s274 = new Solution274(); // System.out.println(s274.hIndex(new int[] {3, 0, 6, 1, 5})); // Solution278 s278 = new Solution278(); // System.out.println(s278.firstBadVersion(3)); // Solution277 s277 = new Solution277(); // System.out.println(s277.findCelebrity(2)); // Solution282 s282 = new Solution282(); // System.out.println(s282.addOperators("123", 6)); // Solution286 s286 = new Solution286(); // int[][] input = new int[][] {{0,234}, {234,234}}; // s286.wallsAndGates(input); // ValidWordAbbr s288 = new ValidWordAbbr(new String[] {"deer","door","cake","card"}); // System.out.println(s288.isUnique("dear")); // System.out.println(s288.isUnique("cart")); // System.out.println(s288.isUnique("cane")); // System.out.println(s288.isUnique("make")); // Solution289 s289 = new Solution289(); // int[][] input = new int[][] {{1}}; // s289.gameOfLife(input); // Solution294 s294 = new Solution294(); // System.out.println(s294.canWin("++++")); // TreeNode root = new TreeNode(1); // TreeNode left = new TreeNode(2); // TreeNode leftleft = new TreeNode(4); // TreeNode leftright = new TreeNode(5); // TreeNode right = new TreeNode(3); // root.left = left; // root.right = right; // left.left = leftleft; // left.right = leftright; // Solution298 s298 = new Solution298(); // System.out.println(s298.longestConsecutive(root)); // MedianFinder s295 = new MedianFinder(); // s295.addNum(6); // System.out.println(s295.findMedian()); // s295.addNum(10); // System.out.println(s295.findMedian()); // s295.addNum(2); // System.out.println(s295.findMedian()); // s295.addNum(6); // System.out.println(s295.findMedian()); // s295.addNum(5); // System.out.println(s295.findMedian()); // s295.addNum(0); // System.out.println(s295.findMedian()); // s295.addNum(6); // System.out.println(s295.findMedian()); // s295.addNum(3); // System.out.println(s295.findMedian()); // s295.addNum(1); // System.out.println(s295.findMedian()); // s295.addNum(0); // System.out.println(s295.findMedian()); // s295.addNum(0); // System.out.println(s295.findMedian()); // Solution296 s296 = new Solution296(); // int[][] input = new int[][]{{0,2,1},{1,0,2},{0,1,0}}; // System.out.println(s296.minTotalDistance(input)); // Solution291 s291 = new Solution291(); // System.out.println(s291.wordPatternMatch("d", "e")); // int[][] input = new int[][] { // {3,0,1,4,2}, // {5,6,3,2,1}, // {1,2,0,1,5}, // {4,1,0,1,7}, // {1,0,3,0,5} // }; // // NumMatrix s304 = new NumMatrix(input); // // System.out.println(s304.sumRegion(2,1,4,3)); // Solution306 s306 = new Solution306(); // System.out.println(s306.isAdditiveNumber("0235813")); // Graph g = new Graph(2); // int [] input = new int[]{0,9,5,7,3}; // NumArray307 s307 = new NumArray307(input); // System.out.println(s307.sumRange(4,4)); //// s307.update(1,2); // System.out.println(s307.sumRange(2,4)); // Solution309 s309 = new Solution309(); // int[] input = new int[] {2,1,4}; // System.out.println(s309.maxProfit(input)); // Solution310 s310 = new Solution310(); // int[][] edges = new int[][] {{0, 3}, {1, 3}, {2, 3}, {4, 3}, {5, 4}}; // List<Integer> res = s310.findMinHeightTrees(6, edges); // Solution313 s313 = new Solution313(); // System.out.println(s313.nthSuperUglyNumber(12, new int[]{2,7,13,19})); // Solution301 s301 = new Solution301(); // List<String> res = s301.removeInvalidParentheses("()())()"); // Solution334 s334 = new Solution334(); // System.out.println(s334.increasingTriplet(new int[] {2,1,5,0,3})); // Solution305II s305 = new Solution305II(); // List<Integer> res = s305.numIslands2(3,3, new int[][]{{0,1},{1,2},{2,1},{1,0},{0,2},{0,0},{1,1}}); // int[][] input = new int[][] { // {3,0,1,4,2}, // {5,6,3,2,1}, // {1,2,0,1,5}, // {4,1,0,1,7}, // {1,0,3,0,5} // }; // int[][] input = new int[][] {{1}}; // // NumMatrix308 s308 = new NumMatrix308(input); // // System.out.println(s308.sumRegion(0,0,0,0)); // s308.update(0, 0, -1); // System.out.println(s308.sumRegion(0,0,0,0)); // Solution319 s319 = new Solution319(); // System.out.println(s319.bulbSwitch(3)); // Solution320 s320 = new Solution320(); // List<String> res = s320.generateAbbreviations("word"); // Solution315 s315 = new Solution315(); // List<Integer> res = s315.countSmaller(new int[] {26,78,27,100,33,67,90,23,66,5,38,7,35,23,52,22,83,51,98,69,81,32,78,28,94,13,2,97,3,76,99,51,9,21,84,66,65,36,100,41}); // Solution324 s324 = new Solution324(); // int[] input = new int[] {1,3,2,2,3,1}; // s324.wiggleSort(input); // Solution325 s325 = new Solution325(); // System.out.println(s325.maxSubArrayLen(new int[] {1, -1,5,-2,3}, 3)); // Solution331 s331 = new Solution331(); // System.out.println(s331.isValidSerialization("9,3,4,#,#,1,#,#,#,2,#,6,#,#")); // Solution347 s347 = new Solution347(); // List<Integer> res = s347.topKFrequent(new int[] {1}, 1); // x x1 = new x(1); // x x2 = new x(2); // List<NestedInteger> l1 = new ArrayList<NestedInteger>(Arrays.asList(x1, x2)); // x x3 = new x(3); // x x4 = new x(4); // x x5 = new x(5); // List<NestedInteger> l2 = new ArrayList<>(Arrays.asList(x4, x5)); // x ll1 = new x(l1); // x ll2 = new x(l2); // // List<NestedInteger> input = new ArrayList<NestedInteger>(Arrays.asList(ll1, x3, ll2)); // // List<NestedInteger> input2 = new ArrayList<>(); // List<NestedInteger> input3 = new ArrayList<NestedInteger>(Arrays.asList(new x(input2))); // NestedIterator s341 = new NestedIterator(input3); // System.out.println(s341.hasNext()); // System.out.println(s341.next()); // System.out.println(s341.next()); // System.out.println(s341.next()); // System.out.println(s341.next()); // System.out.println(s341.next()); // System.out.println(s341.next()); // Solution367 s367 = new Solution367(); // System.out.println(s367.isPerfectSquare(1)); // SummaryRanges s352 = new SummaryRanges(); // s352.addNum(1); // s352.addNum(3); // s352.addNum(7); // s352.addNum(2); // s352.addNum(6); // s352.addNum(7); // s352.addNum(6); // // // Solution375 s375 = new Solution375(); // System.out.println(s375.getMoneyAmount(1)); // SolutionBFS301 s301 = new SolutionBFS301(); // List<String> res = s301.removeInvalidParentheses("()())()"); // Solution394II s394 = new Solution394II(); // System.out.println(s394.decodeString("2[abc]xyc3[z]")); // Solution393 s393 = new Solution393(); // System.out.println(s393.validUtf8(new int[] {255})); // Solution395 s395 = new Solution395(); // System.out.println(s395.longestSubstring("aaabb", 3)); // Solution399 s399 = new Solution399(); // double[] res = s399.calcEquation( // new String[][] {{"x1","x2"},{"x2","x3"},{"x3","x4"},{"x4","x5"}}, // new double[] {3.0, 4.0, 5.0, 6.0}, // new String[][] {{"x1","x5"},{"x5","x2"},{"x2","x4"},{"x2","x2"},{"x2","x9"},{"x9","x9"}} // ); // Solution402 s402 = new Solution402(); // System.out.println(s402.removeKdigits("1432219", 3)); // Solution403 s403 = new Solution403(); // System.out.println(s403.canCross(new int[] {0,1,2,3,4,8,9,11})); // Solution406 s406 = new Solution406(); // System.out.println(s406.reconstructQueue( // new int[][] {{7,0},{4,4},{7,1},{5,0},{6,1},{5,2}})); // Solution363 s363 = new Solution363(); // System.out.println(s363.maxSumSubmatrix( // new int[][] {{1,0,1},{0,-2,3}}, // 2)); // Solution410 s410 = new Solution410(); // System.out.println(s410.splitArray(new int[]{7,2,5,10,8}, 2)); // Solution413 s413 = new Solution413(); // System.out.println(s413.numberOfArithmeticSlices( // new int[] {1,2,3,8,9,10})); // Solution416 s416 = new Solution416(); // s416.canPartition(new int[]{3,3,3,4,5}); // Solution418 s418 = new Solution418(); // System.out.println(s418.wordsTyping( // new String[] {"a", "bcd", "e"}, // 3, // 6 // )); // Solution425 s425 = new Solution425(); // List<List<String>> res = // s425.wordSquares(new String[] {"abat","baba","atan","atal"}); // Solution424 s424 = new Solution424(); // System.out.println(s424.characterReplacement("AABABBA", 1)); // Solution439 s439 = new Solution439(); // System.out.println(s439.parseTernary("F?1:T?4:5")); // Solution441 s441 = new Solution441(); // System.out.println(s441.arrangeCoins(6)); // Solution447 s447 = new Solution447(); // System.out.println(s447.numberOfBoomerangs( // new int[][] {{0,0}, {1,0}, {2,0}} // )); // Solution459 s459 = new Solution459(); // System.out.println(s459.repeatedSubstringPattern("abcabcabcabc")); // Solution464 s464 = new Solution464(); // System.out.println(s464.canIWin(10, 11)); // Solution468 s468 = new Solution468(); // System.out.println(s468.validIPAddress("172.16.254.1.")); // System.out.println(s468.validIPAddress("2001:0db8:85a3:0:0:8A2E:0370:7334:")); // System.out.println(s468.validIPAddress("256.256.256.256")); // Solution471 s471 = new Solution471(); // System.out.println(s471.makesquare(new int[] {1,1,2,2,2})); // Solution474I s474 = new Solution474I(); // System.out.println(s474.findMaxForm( // new String[] {"10", "0001", "111001", "1", "0"}, // 5, // 3 // )); // Solution475 s475 = new Solution475(); // System.out.println(s475.findRadius(new int[]{1,1,1,1,1,1,999,999,999,999,999}, new int[]{499,500,501})); // Solution476 s476 = new Solution476(); // System.out.println(s476.findComplement(5)); // Solution477 s477 = new Solution477(); // System.out.println(s477.totalHammingDistance(new int[]{4,14,2})); // Solution482 s482 = new Solution482(); // System.out.println(s482.licenseKeyFormatting("2-4A0r7-4k", 3)); // Solution484 s484 = new Solution484(); // int[] res = s484.findPermutation("IDIIDD"); // Solution486 s486 = new Solution486(); // System.out.println(s486.PredictTheWinner(new int[]{1,1,1})); // Solution487 s487 = new Solution487(); // System.out.println(s487.findMaxConsecutiveOnes(new int[]{1,0,1,1,0,1})); // Solution490 s490 = new Solution490(); // int[][] maze = new int[][]{ // {0,0,1,0,0}, // {0,0,0,0,0}, // {0,0,0,1,0}, // {1,1,0,1,1}, // {0,0,0,0,0} // }; // int[] start = new int[]{0,4}; // int[] end = new int[]{4,4}; // System.out.println(s490.hasPath(maze, start, end)); // Solution494 s494 = new Solution494(); // System.out.println(s494.findTargetSumWays(new int[]{1,1,1,1,1}, 3)); // Solution496 s496 = new Solution496(); // int[] res = s496.nextGreaterElement( // new int[] {4,1,2}, // new int[] {1,3,4,2} // ); // Solution497 s497 = new Solution497(); // int[] res = s497.findDiagonalOrder(new int[][] {{1,2,3},{4,5,6},{7,8,9}}); // TreeNode root = new TreeNode(1); // TreeNode right = new TreeNode(2); // TreeNode rightLeft = new TreeNode(2); // root.right = right; // right.left = rightLeft; // Solution501 s501 = new Solution501(); // System.out.println(s501.findMode(root)); // Solution505 s505 = new Solution505(); // int[][] maze = new int[][]{ // {0,0,1,0,0}, // {0,0,0,0,0}, // {0,0,0,1,0}, // {1,1,0,1,1}, // {0,0,0,0,0} // }; // int[] start = new int[]{0,4}; // int[] end = new int[]{4,4}; // System.out.println(s505.shortestDistance(maze, start, end)); // Solution508 s508 = new Solution508(); // TreeNode root = new TreeNode(5); // TreeNode left = new TreeNode(2); // TreeNode right = new TreeNode(-5); // root.left = left; // root.right = right; // int[] res = s508.findFrequentTreeSum(root); // Solution516 s516 = new Solution516(); // System.out.println(s516.longestPalindromeSubseq("bbbab")); // Solution518I s518 = new Solution518I(); // System.out.println(s518.change(5, new int[] {1,2,5})); // Solution520 s520 = new Solution520(); // System.out.println(s520.detectCapitalUse("ggg")); // // Solution523 s523 = new Solution523(); // System.out.println(s523.checkSubarraySum(new int[]{23,2,4,6,7}, 6)); // Solution536 s536 = new Solution536(); // TreeNode res = s536.str2tree("4(2(3))(6(5))"); // Codec535 s535 = new Codec535(); // String url = "https://leetcode.com/problems/design-tinyurl"; // String shortUrl = s535.encode(url); // String convertedUrl = s535.decode(shortUrl); // System.out.println(url.equals(convertedUrl)); // Solution538 s538 = new Solution538(); // TreeNode root = new TreeNode(5); // TreeNode left = new TreeNode(2); // TreeNode right = new TreeNode(13); // root.left = left; // root.right = right; // TreeNode res = s538.convertBST(root); // Solution545 s545 = new Solution545(); // TreeNode root = new TreeNode(1); // TreeNode right = new TreeNode(2); // TreeNode rightleft = new TreeNode(3); // TreeNode rightright = new TreeNode(4); // root.left = right; // right.right = rightleft; //// right.right = rightright; // List<Integer> res = s545.boundaryOfBinaryTree(root); // Solution548 s548 = new Solution548(); // System.out.println(s548.splitArray(new int[]{1,2,1,2,1,2,1})); // Solution557 s557 = new Solution557(); // System.out.println(s557.reverseWords("Let's take LeetCode contest")); // Solution560 s560 = new Solution560(); // System.out.println(s560.subarraySum(new int[]{1,1,1}, 2)); // Solution567 s567 = new Solution567(); // System.out.println(s567.checkInclusion("ab", "eidbaooo")); // Solution576 s576 = new Solution576(); // System.out.println(s576.findPaths(8,7,16,1,5)); // Solution581 s581 = new Solution581(); // System.out.println(s581.findUnsortedSubarray(new int[]{2,1})); // Solution621 s621 = new Solution621(); // System.out.println(s621.leastInterval(new char[]{'A','A','A','B','B','B'}, 2)); // Solution625 s625 = new Solution625(); // System.out.println(s625.smallestFactorization(9765625)); // Solution630 s630 = new Solution630(); // // System.out.println(s630.scheduleCourse(new int[][]{{5,5},{4,6},{2,6}})); // Solution632 s632 = new Solution632(); // List<List<Integer>> input = new ArrayList<>(); // input.add(new ArrayList<>(Arrays.asList(4,10,15,24,26))); // input.add(new ArrayList<>(Arrays.asList(0,9,12,20))); // input.add(new ArrayList<>(Arrays.asList(5,18,22,30))); // // int[] res = s632.smallestRange(input); // LogSystem635 s635 = new LogSystem635(); // s635.put(1, "2017:01:01:23:59:59"); // s635.put(2, "2017:01:01:22:59:59"); // s635.put(3, "2016:01:01:00:00:00"); // List<Integer> res1 = s635.retrieve("2016:01:01:01:01:01","2017:01:01:23:00:00","Year"); // List<Integer> res2 = s635.retrieve("2016:01:01:01:01:01","2017:01:01:23:00:00","Hour"); // Solution636 s636 = new Solution636(); // int[] arr = s636.exclusiveTime(2, Arrays.asList("0:start:0","0:start:2","0:end:5","1:start:6","1:end:6","0:end:7")); // Solution638 s638 = new Solution638(); // List<Integer> price = Arrays.asList(2,5); // List<Integer> needs = Arrays.asList(3,2); // List<Integer> sep1 = Arrays.asList(3,0,5); // List<Integer> sep2 = Arrays.asList(1,2,10); // List<List<Integer>> specials = new ArrayList<>(); // specials.add(sep1); // specials.add(sep2); // System.out.println(s638.shoppingOffers(price, specials, needs)); // Solution640 s640 = new Solution640(); // System.out.println(s640.solveEquation("-x=1")); // Solution653 s653 = new Solution653(); // TreeNode root = new TreeNode(5); // TreeNode left = new TreeNode(3); // TreeNode right = new TreeNode(6); // TreeNode leftleft = new TreeNode(2); // TreeNode leftright = new TreeNode(4); // TreeNode rightright = new TreeNode(7); // root.left = left; // root.right = right; // left.left = leftleft; // left.right = leftright; // right.right = right; // System.out.println(s653.findTarget(root, 9)); // Solution656 s656 = new Solution656(); // List<Integer> res = s656.cheapestJump(new int[]{1,2,4,-1,2}, 2); // Solution658 s658 = new Solution658(); // List<Integer> res = s658.findClosestElements( // new int[]{0,0,1,2,3,3,4,7,7,8},3,5 // ); // Solution660 s660 = new Solution660(); // System.out.println(s660.newInteger(10)); // TreeNode root = new TreeNode(5); // TreeNode left = new TreeNode(3); // TreeNode right = new TreeNode(6); // TreeNode leftleft = new TreeNode(2); // TreeNode leftright = new TreeNode(4); // TreeNode rightright = new TreeNode(7); // root.left = left; // root.right = right; // left.left = leftleft; // left.right = leftright; // right.right = rightright; // Solution662 s662 = new Solution662(); // System.out.println(s662.widthOfBinaryTree(root)); // TreeNode root = new TreeNode(0); // root.left = new TreeNode(-1); // root.right = new TreeNode(1); // Solution663 s663 = new Solution663(); // System.out.println(s663.checkEqualTree(root)); // Solution665 s665 = new Solution665(); // System.out.println(s665.checkPossibility(new int[]{2,3,3,2,4})); // TreeNode root = new TreeNode(2); // TreeNode left = new TreeNode(2); // TreeNode right = new TreeNode(5); // root.left = left; // root.right = right; // Solution671 s671 = new Solution671(); // System.out.println(s671.findSecondMinimumValue(root)); // Solution673 s673 = new Solution673(); // System.out.println(s673.findNumberOfLIS(new int[]{1,2,4,3,5,4,7,2})); // MyCalendarTwo c2 = new MyCalendarTwo(); // System.out.println(c2.book(10,20)); // System.out.println(c2.book(50,60)); // System.out.println(c2.book(10,40)); // System.out.println(c2.book(5,15)); // Solution726 s726 = new Solution726(); // System.out.println(s726.countOfAtoms("K4(ON(SO3)2)2")); // Solution699 s699 = new Solution699(); // int input[][] = { {1,2}, {2,3}, {6,1}}; // List<Integer> res = s699.fallingSquares(input); // Solution719 s719 = new Solution719(); // int[] input = new int[] {1,6,1}; // System.out.println(s719.smallestDistancePair(input, 1)); // MapSum mapSum = new MapSum(); // mapSum.insert("aa", 3); // mapSum.sum("a"); // mapSum.insert("aa", 2); // System.out.println(mapSum.sum("aa")); // Solution680 s680 = new Solution680(); // System.out.println(s680.validPalindrome("abc")); // Solution681 s681 = new Solution681(); // System.out.println(s681.nextClosestTime("19:34")); // Solution685 s685 = new Solution685(); // int input[][] = {{2,1},{3,1},{4,2},{1,4}}; // int[] res = s685.findRedundantDirectedConnection(input); // Solution688 s688 = new Solution688(); // System.out.println(s688.knightProbability(3,2,0,0)); // Solution001 s001 = new Solution001(); // int[] res = s001.twoSum(new int[]{3,2,4}, 6); // Solution689 s689 = new Solution689(); // int[] res = s689.maxSumOfThreeSubarrays(new int[]{1,2,1,2,6,7,5,1}, 2); // Solution692 s692 = new Solution692(); // List<String> res = s692.topKFrequent(new String[]{"the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"}, 4); // Solution696 s696 = new Solution696(); // System.out.println(s696.countBinarySubstrings("00110")); // Solution697 s697 = new Solution697(); // System.out.println(s697.findShortestSubArray(new int[] {1,2,2,3,1})); // Solutionfinddup s = new Solutionfinddup(); // try { // s.groupFiles(""); // } catch (Exception ex) { // // } // Solution291_I s291 = new Solution291_I(); // System.out.println(s291.wordPatternMatch("d", "ef")); // Solution_Merge sm = new Solution_Merge(); // ArrayList<Solution_Merge.Interval> a = new ArrayList<>(); // ArrayList<Solution_Merge.Interval> b = new ArrayList<>(); // a.add(new Solution_Merge.Interval(0,2)); // a.add(new Solution_Merge.Interval(5,10)); // a.add(new Solution_Merge.Interval(16,20)); // a.add(new Solution_Merge.Interval(25,26)); // a.add(new Solution_Merge.Interval(28,30)); // b.add(new Solution_Merge.Interval(1,5)); // b.add(new Solution_Merge.Interval(11,12)); // b.add(new Solution_Merge.Interval(14,18)); // b.add(new Solution_Merge.Interval(20,23)); // List<Solution_Merge.Interval> res = sm.and(a,b); // Solution140 s140 = new Solution140(); // List<String> dict = Arrays.asList("cat", "cats", "and", "sand", "dog"); // List<String> res = s140.wordBreak("catsanddog", dict); // Solution10 s10 = new Solution10(); // System.out.println(s10.isMatch("ab", ".*d")); // Solution30 s30 = new Solution30(); // List<Integer> res = s30.findSubstring("wordgoodgoodgoodbestword", // new String[]{"word","good","best","good"}); // Solution31 s31 = new Solution31(); // int[] input = new int[]{3,2,1}; // s31.nextPermutation(input); // Solution32 s32 = new Solution32(); // int res = s32.longestValidParentheses(")()())"); // Solution41 s41 = new Solution41(); // System.out.println(s41.firstMissingPositive(new int[] {-1,4,2,1,9,10})); // Solution68 s68 = new Solution68(); // List<String> res = s68.fullJustify(new String[]{"a"}, 2); // Solution76 s76 = new Solution76(); // System.out.println(s76.minWindow("a", "a")); // Solution84 s84 = new Solution84(); // System.out.println(s84.largestRectangleArea(new int[] {2,1,5,6,2,3})); // Solution87 s87 = new Solution87(); // System.out.println(s87.isScramble("ab", "ba")); // Solution132 s132 = new Solution132(); // System.out.println(s132.minCut("aab")); // // Permutation p = new Permutation(); // List<String> l = p.findPerumation("banana"); // SubString sub = new SubString(); // System.out.println(sub.lastSub("banana")); // RoyalName rn = new RoyalName(); // List<String> res = rn.sort(Arrays.asList("Louis IX", "John II", "Louis VIII", "John V")); // Queens q = new Queens(); // System.out.println(q.countOfAttack(new int[] {4,5,1,3,7,8,2,6})); // S11 s11 = new S11(); // System.out.println(s11.numberOfInterestring(87,88)); // // lines l = new lines(); // List<String> input = new ArrayList<>(); // input.add("Hello World"); // input.add("CodeEval"); // input.add("Quick Fox"); // input.add("A"); // input.add("San Francisco"); // List<String> res = l.findLine(input); // count c = new count(); //// System.out.println(c.countLine("40 40 40 40 29 29 29 29 29 29 29 29 57 57 92 92 92 92 92 86 86 86 86 86 86 86 86 86 86")); // System.out.println(c.countLine("7")); // Kanpsack_x k = new Kanpsack_x(); // int[] w = new int[]{1,3,4,5}; // int[] v = new int[]{1,4,5,7}; // System.out.println(k.max(w,v,7)); // LongestCommonSubSequenc l = new LongestCommonSubSequenc(); // System.out.println(l.find("abcdef", "acbcf")); // MatrixMultiple mm = new MatrixMultiple(); // System.out.println(mm.find(new int[]{2,3,6,4,5})); // OptimalBST_II ob = new OptimalBST_II(); // System.out.println(ob.find(new int[]{34,30,50,5}));//, new int[]{34,30,50,5})); // CoinChange cc = new CoinChange(); // System.out.println(cc.minCountOfCoins(new int[]{7,2,3,6}, 13)); // LongestPalindromicSubSequence_II lps = new LongestPalindromicSubSequence_II(); // System.out.println(lps.find("agbdba")); // PalindromeSplit ps = new PalindromeSplit(); // System.out.println(ps.find("abcbm")); // NoBST nb = new NoBST(); // System.out.println(nb.find(2)); //// System.out.println(nb.findII(2)); // InOrder io = new InOrder(); // TreeNode root = new TreeNode(1); // root.left = new TreeNode(2); // root.left.right = new TreeNode(3); // List<Integer> list = io.traversal(root); // PhoneDirectory pd = new PhoneDirectory(3); // System.out.println(pd.get()); // System.out.println(pd.get()); // System.out.println(pd.check(2)); // CanDrive cd = new CanDrive(); // CanDrive.Interval i1 = new CanDrive.Interval(0,4); // CanDrive.Interval i2 = new CanDrive.Interval(5,9); // CanDrive.Interval i3 = new CanDrive.Interval(10,14); // CanDrive.Interval i4 = new CanDrive.Interval(15,19); // CanDrive.Interval i5 = new CanDrive.Interval(20,24); // List<CanDrive.Interval> log = new ArrayList<>(); // log.add(i1); // log.add(i2); // log.add(i3); // log.add(i4); // log.add(i5); // //// CanDrive.Interval i1 = new CanDrive.Interval(0,12); //// CanDrive.Interval i2 = new CanDrive.Interval(13,19); //// List<CanDrive.Interval> log = new ArrayList<>(); //// log.add(i1); //// log.add(i2); // System.out.println(cd.canDrive(log, 24)); // printDiagnal pd = new printDiagnal(); // int[][] input = new int[][]{{1,2,3}, {4,5,6}, {7,8,9}}; // List<List<Integer>> res = pd.print(input); // Solution_X x = new Solution_X(); // System.out.println(x.findTheFirstLarg(new int[] {1,3}, 2)); // Solution224 s224 = new Solution224(); // System.out.println(s224.calculate("(1+(4+5+2)-3)+(6+8)")); // Solution22 s22 = new Solution22(); // try { // s22.work("/Users/davidduan/Untitled.txt"); // } catch (Exception e) { // e.printStackTrace(); // } // LowerMedian lm = new LowerMedian(); // System.out.println(lm.find(10)); // System.out.println(lm.find(6)); // System.out.println(lm.find(12)); // System.out.println(lm.find(8)); // Solution301_x s301 = new Solution301_x(); // List<String> res = s301.removeInvalidParentheses("()())()"); // Solution439_X s439 = new Solution439_X(); // System.out.println(s439.parseTernary("(T?(T?F:5):3)")); // Solution269_II s269 = new Solution269_II(); // String res = s269.alienOrder(new String[]{"ab", "adc"}); // Solution34 s34 = new Solution34(); // int[] res = s34.searchRange(new int[]{1}, 18); // LRUCache lru = new LRUCache(2); // lru.put(1,1); // lru.put(2,2); // System.out.println(lru.get(1)); // Solution127 s127 = new Solution127(); // List<String> input = Arrays.asList("hot","dot","dog","lot","log","cog"); // System.out.println(s127.ladderLength("hit", "cog", input)); // Solution10_III s10 = new Solution10_III(); // System.out.println(s10.isMatch("aa", "aa")); // Solution40 s40 = new Solution40(); // List<List<Integer>> res = s40.combinationSum2(new int[]{10,1,2,7,6,1,5}, 8); // Solution755 s755 = new Solution755(); // System.out.println(s755.reachNumber(3)); // Solution126 s126 = new Solution126(); // List<List<String>> res = s126.findLadders("hit", "cog", Arrays.asList("hot","dot","dog","lot","log","cog")); // try { // PrintWriter writer = new PrintWriter("/Users/davidduan/the-file-name.txt", "UTF-8"); // writer.println("The first line"); // writer.println("The second line"); // writer.close(); // } catch (Exception ex) { // // } // Solution735 s735 = new Solution735(); // int[] res = s735.asteroidCollision(new int[]{10,2,-5}); // Crawler crawler = new Crawler(); // crawler.craw(); // SolutionTest st = new SolutionTest(); // System.out.println(st.sumOfDiv(10)); // Solution230 s230 = new Solution230(); // TreeNode root = new TreeNode(2); // TreeNode left = new TreeNode(1); // root.left = left; // System.out.println(s230.kthSmallest(root, 1)); // Solution739 s739 = new Solution739(); // int[] res = s739.dailyTemperatures(new int[]{73, 74, 75, 71, 69, 72, 76, 73}); // Solution315_II s315 = new Solution315_II(); // List<Integer> res = s315.countSmaller(new int[]{5,2,6,1}); // Solution_snap4 snap4 = new Solution_snap4(); // System.out.println(snap4.findMAX(new int[]{1,2,3,4})); // TreeNode root = new TreeNode(2); // TreeNode left = new TreeNode(1); // TreeNode right = new TreeNode(4); // TreeNode rightleft = new TreeNode(3); // root.left = left; // root.right = right; // right.left = rightleft; // LeftIterator it = new LeftIterator(root); // while(it.hasNext()) { // System.out.println(it.getNext().val); // } // p1_AmicableNuber p1 = new p1_AmicableNuber(); //// Set<List<Integer>>res = p1.findAll(new int[] {220, 284}); // Set<int[]> res = p1.find(1000); // p3 s = new p3(); // System.out.println(s.find(new int[] {1,2,5,8})); // p4 s = new p4(); // System.out.println(s.findMax(new int[] {1,2,3,4})); // p8_html_parser s = new p8_html_parser(); // String[][] input = new String[][] { // {"html","open"}, // {"user","open"}, // {"id","open"}, // {"aa","text"}, // {"id","close"}, // {"meta","open"}, // {"bb","text"}, // {"meta","close"}, // {"user","close"}, // {"html","close"}}; // p8_html_parser.TreeNode res = s.buildTree(input); // p12_UglyNumber s = new p12_UglyNumber(); // System.out.println(s.findnthII(7)); // p29_332 s = new p29_332(); // List<String> res = s.findItinerary(new String[][]{{"MUC","LHR"},{"JFK","MUC"},{"SFO","SJC"},{"LHR","SFO"}}); // p7_hungarianAlgorithm s = new p7_hungarianAlgorithm(); // System.out.println(s.findCost(new int[][]{{40,60,15}, {25,30,45},{55,30,25}})); // px_rotationArray s = new px_rotationArray(); // System.out.println(s.searchII(new int[]{1,3}, 3)); // px_WordLadderII s = new px_WordLadderII(); // List<String> input = new ArrayList<>(); // input.add("hot"); // input.add("dot"); // input.add("dog"); // input.add("lot"); // input.add("log"); // input.add("cog"); // List<List<String>> res = s.findLadders("hit", "cog", input); // p17_Solution s = new p17_Solution(); // TreeNode res = s.buildTree(new int[]{1,2}, new int[]{2,1}); // p6_Solution s = new p6_Solution(); // s.takeIPRange(new String[] {"7.0.0.0/8", "10.3.0.0/16", "6.7.8.134/32"}); // System.out.println(s.isBadIp("7.3.4.5")); // System.out.println(s.isBadIp("6.7.8.0")); // System.out.println(s.isBadIp("6.7.8.134")); // InMemeoryDB inDb = new InMemeoryDB(); // try { // inDb.process(); // System.out.println(inDb.getNumOfValue(1)); // System.out.println(inDb.getNumOfValue(11)); // } catch (Exception ex) { // System.out.println(ex.getMessage()); // } // Solution_FindRange s = new Solution_FindRange(); // int[] res = s.find(new int[] {1,2,5,8,9,16,19}, 2, 20); // Solution297_ub_hard_3 s = new Solution297_ub_hard_3(); // TreeNode res = s.deserialize("1,2,3,null,null,4,5"); // Solution_516_ub_11 s = new Solution_516_ub_11(); // System.out.println(s.longestPalindromeSubseq("bbbb")); // // Solution_207_ub21 s = new Solution_207_ub21(); // System.out.println(s.canFinish(2, new int[][]{{0,1}, {1,0}})); // Solution139 s = new Solution139(); // System.out.println(s.wordBreak("leetcode", Arrays.asList("leet", "code"))); // Solution_33 s = new Solution_33(); // System.out.println(s.search(new int[]{1,3,5},1)); // Solution114 s = new Solution114(); // TreeNode root = new TreeNode(5); // TreeNode left = new TreeNode(3); // TreeNode right = new TreeNode(6); // TreeNode leftleft = new TreeNode(2); // TreeNode leftright = new TreeNode(4); // TreeNode rightright = new TreeNode(7); // root.left = left; // root.right = right; // left.left = leftleft; // left.right = leftright; // right.right = rightright; // s.flatten(root); // Solution779 s = new Solution779(); // System.out.println(s.kthGrammar(3,4)); // Solution_781 s = new Solution_781(); // System.out.println(s.numRabbits(new int[]{1,0,1,0,0})); // Solution780 s = new Solution780(); // System.out.println(s.reachingPoints(9,10,9,19)); // Solution777 s = new Solution777(); // s.canTransform("X", "L"); // Solution785 s = new Solution785(); // int[][] input = new int[][]{{1,2,3}, {0,2}, {0,1,3}, {0,2}}; // System.out.println(s.isBipartite(input)); // Solution784 s = new Solution784(); // List<String> res = s.letterCasePermutation("a1b2"); // Pasico p = new Pasico(); // p.print(6); // Solution788 s = new Solution788(); // System.out.println(s.rotatedDigits(10)); // Solution787_BellmanFord s = new Solution787_BellmanFord(); // int[][] flights = new int[][]{{0, 1, 100}, {1, 2, 100}, {0, 2, 500}}; // // int cheapestPrice = s.findCheapestPrice(3, flights, 0, 2, 1); Solution737 s = new Solution737(); System.out.println(s.areSentencesSimilarTwo(new String[]{"great","acting","skills"}, new String[]{"fine","drama","talent"}, new String[][] {{"great","good"}, {"fine","good"}, {"drama","acting"}, {"skills","talent"}})); } } class Solution001_X { public int[] twoSum(int[] nums, int target) { Arrays.sort(nums); int l = 0; int r = nums.length-1; while(l < r) { int res = nums[l] + nums[r]; if (res == target) { return new int[] {l,r}; } if (res > target) { r--; } else { l++; } } return new int[]{l,r}; } } // 10/6/17 class Solution279 { public int numSquares(int n) { int[] dp = new int[n+1]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; for(int j = 1; j<=n ; j++) { int min = Integer.MAX_VALUE; int k = 1; while(j - k*k >= 0) { min = Math.min(min, dp[j-k*k] + 1); k++; } dp[j] = min; } return dp[n]; } } class Solution246 { public boolean isStrobogrammatic(String num) { Map<Character, Character> map = new HashMap<>(); map.put('6', '9'); map.put('9', '6'); map.put('8', '8'); map.put('1', '1'); map.put('0', '0'); for (int i = 0; i < num.length(); i++) { if (!map.keySet().contains(num.charAt(i)) || num.charAt(num.length()-1-i) != map.get(num.charAt(i))) { return false; } } return true; } } class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } class Solution250 { public int countUnivalSubtrees(TreeNode root) { if (root == null) return 0; int[] res = dfs(root); return res[0]; } private int[] dfs(TreeNode root) { if (root.left == null && root.right == null) { return new int[] {1, 1}; } if (root.left != null && root.right == null) { int[] leftRe = dfs(root.left); if (root.left.val == root.val && leftRe[1] == 1) { return new int[] { leftRe[0]+1, 1}; } else { return new int[] {leftRe[0], 0}; } } else if (root.right != null && root.left == null) { int[] rightRe = dfs(root.right); if (root.right.val == root.val && rightRe[1] == 1) { return new int[] {rightRe[0]+1, 1}; } else { return new int[] {rightRe[0], 0}; } } else { int[] leftRe = dfs(root.left); int[] rightRe = dfs(root.right); if (root.left.val == root.val && root.right.val == root.val) { return new int[] {leftRe[0] + rightRe[0] + 1, 1}; } else { return new int[] {leftRe[0] + rightRe[0], 0}; } } } } //251 class Vector2D implements Iterator<Integer> { List<List<Integer>> mVec2d; int i = 0; int j = 0; public Vector2D(List<List<Integer>> vec2d) { mVec2d = vec2d; } @Override public Integer next() { if (hasNext()) { Integer res = mVec2d.get(i).get(j); j++; return res; } return Integer.MAX_VALUE; } @Override public boolean hasNext() { while(i != mVec2d.size() && j == mVec2d.get(i).size()) { if (j == mVec2d.get(i).size()) { i++; j= 0; } } return i != mVec2d.size(); } } class Solution252 { class Interval { int start; int end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; } } public boolean canAttendMeetings(Interval[] intervals) { Comparator<Interval> cmp = new Comparator<Interval>() { @Override public int compare(Interval o1, Interval o2) { return o1.start - o2.start; } }; List<Interval> list = Arrays.asList(intervals); Collections.sort(list, cmp); for (int i = 1; i< list.size(); i++) { if (list.get(i).start >= list.get(i-1).start && list.get(i).start < list.get(i).end) { return false; } } return true; } } class Solution253 { class Point { public int time; public int start; Point(int t, int s) { time = t; start = s; } } public int minMeetingRooms(Solution252.Interval[] intervals) { List<Point> p = new ArrayList<>(); for (int i = 0; i < intervals.length; i++) { p.add(new Point(intervals[i].start, 1)); p.add(new Point(intervals[i].end, -1)); } Comparator<Point> cmp = new Comparator<Point>() { @Override public int compare(Point o1, Point o2) { if (o1.time == o2.time) { return o1.start - o2.start; } return o1.time - o2.time; } }; Collections.sort(p, cmp); int count = 0; int res = 0; for (int i = 0; i< p.size(); i++) { if (p.get(i).start < 0) { count --; } else { count ++; } res = Math.max(count, res); } return res; } } class Solution254 { public List<List<Integer>> getFactors(int n) { List<List<Integer>> res = new ArrayList<List<Integer>>(); dfs(res, new ArrayList<>(), n, 2); return res; } private void dfs(List<List<Integer>> res, List<Integer> item, int n, int start) { if (n <=1) { if (item.size() > 1) { res.add(new ArrayList<>(item)); } } for (int i = start; i<= n; i++) { if (n%i == 0) { item.add(i); dfs(res, item, n/i, i); item.remove(item.size()-1); } } } } class Solution255 { public boolean verifyPreorder(int[] preorder) { if (preorder.length == 0) return true; Stack<Integer> s = new Stack<>(); int low = Integer.MIN_VALUE; for (int p : preorder) { if (p < low) { return false; } while(!s.empty() && p > s.peek()) { low = s.pop(); } s.push(p); } return true; } } //10/7/17 class Solution256 { public int minCost(int[][] costs) { int m = costs.length; if (m == 0) return 0; int n = costs[0].length; if (n == 0) return 0; int[][] res = new int[m][n]; res[0][0] = costs[0][0]; res[0][1] = costs[0][1]; res[0][2] = costs[0][2]; for (int i = 1; i< m; i++) { res[i][0] = Math.min(res[i-1][1], res[i-1][2]) + costs[i][0]; res[i][1] = Math.min(res[i-1][0], res[i-1][2]) + costs[i][1]; res[i][2] = Math.min(res[i-1][0], res[i-1][1]) + costs[i][2]; } return Math.min(Math.min(res[m-1][0], res[m-1][1]), res[m-1][2]); } } class Solution257 { public List<String> binaryTreePaths(TreeNode root) { Stack<TreeNode> s = new Stack<>(); List<String> res = new ArrayList<>(); if (root == null) return res; s.push(root); TreeNode pre = null; while(!s.isEmpty()) { TreeNode tmp = s.peek(); if((tmp.left != pre && tmp.left !=null) && tmp.right == null || tmp.right != pre) { s.push(tmp.left); pre = null; } else if (tmp.right != pre && tmp.right !=null) { s.push(tmp.right); pre = null; } else { if (s.peek().left == null && s.peek().right == null) { helper(res, s); } s.pop(); pre = tmp; } } return res; } private void helper(List<String> res, Stack<TreeNode> s) { Stack<TreeNode> tmp = new Stack<>(); while(!s.isEmpty()) { tmp.push(s.pop()); } StringBuilder sb = new StringBuilder(); while(!tmp.isEmpty()) { TreeNode top = tmp.pop(); sb.append(String.valueOf(top.val)); if (!tmp.isEmpty()) { sb.append("->"); } s.push(top); } res.add(sb.toString()); return; } } class Solution257_II { public List<String> binaryTreePaths(TreeNode root) { List<String> res = new ArrayList<>(); List<TreeNode> track = new ArrayList<>(); if (root == null) {return res;} help(res, track, root); return res; } private void help(List<String> res, List<TreeNode> track, TreeNode root) { if (root.left == null && root.right == null) { StringBuilder sb = new StringBuilder(); for (TreeNode n : track) { sb.append(String.valueOf(n.val)); sb.append("->"); } sb.append(root.val); res.add(sb.toString()); return; } track.add(root); if (root.left != null) { help(res, track, root.left); } if (root.right != null) { help(res, track, root.right); } track.remove(track.size()-1); } } class Solution258 { public int addDigits(int num) { while(num > 9) { int res = 0; while(num>0){ res += num%10; num =num/10; } num = res; } return num; } } class Solution259 { public int threeSumSmaller(int[] nums, int target) { int res = 0; Arrays.sort(nums); for (int i = 0; i< nums.length-2; i++) { int j = i+1; int k = nums.length-1; while(j<k) { if (nums[i] + nums[j] + nums[k] < target) { res += k -j; j++; } else { k--; } } } return res; } } class Solution260 { public int[] singleNumber(int[] nums) { int[] res = new int[2]; if (nums.length < 2) {return res;} Set<Integer> set = new HashSet<>(); for (int n : nums) { if (set.contains(n)) { set.remove(n); } else { set.add(n); } } Object[] tmp = set.toArray(); res[0] = (int)tmp[0]; res[1] = (int)tmp[1]; return res; } } class Solution261 { public boolean validTree(int n, int[][] edges) { Map<Integer, List<Integer>> g = new HashMap<>(); for (int i = 0; i < n; i++) { g.put(i, new ArrayList<>()); for (int j = 0; j < edges.length; j++) { if (edges[j][0] == i) { g.get(i).add(edges[j][1]); } else if (edges[j][1] == i) { g.get(i).add(edges[j][0]); } } } List<Integer> track = new ArrayList<>(); Set<Integer> visited = new HashSet<>(); track.add(0); visited.add(0); if (!gfs(g, track, visited, -1, 0)) { return false; } track.remove(0); if (visited.size() != n) { return false; } return true; } private boolean gfs(Map<Integer, List<Integer>> g, List<Integer> track, Set<Integer> visited, int parent, int node) { for(int k : g.get(node)) { if (k!= parent) { if (track.contains(k)) { return false; } track.add(k); visited.add(k); if (!gfs(g, track, visited, node, k)) { return false; } track.remove(track.size()-1); } } return true; } } class Solution261_I { public boolean validTree(int n, int[][] edges) { int[] track = new int[n]; Arrays.fill(track, -1); for (int i = 0; i < edges.length; i++) { int x = find(track, edges[i][0]); int y = find(track, edges[i][1]); if (x == y) return false; track[x] = y; } return edges.length == n-1; } private int find(int[] tracker, int i) { if (tracker[i] == -1) { return i; } return find(tracker, tracker[i]); } } class Solution263 { public boolean isUgly(int num) { if (num <= 0) return false; while(num%2 == 0) { num /=2; } while(num%3 == 0) { num /= 3; } while(num%5 == 0) { num /= 5; } return num == 1; } } class Solution264 { public int nthUglyNumber(int n) { int[] res = new int[n]; res[0] = 1; int i2 = 0; int i3 = 0; int i5 = 0; for (int i = 1; i < n; i++) { int m2 = res[i2] * 2; int m3 = res[i3] * 3; int m5 = res[i5] * 5; int mn = Math.min(m2, Math.min(m3, m5)); if (mn == m2) i2++; if (mn == m3) i3++; if (mn == m5) i5++; res[i] = mn; } return res[n-1]; } } class Solution265 { public int minCostII(int[][] costs) { int m = costs.length; if (m == 0) return 0; int n = costs[0].length; if (n ==0) return 0; int res[][] = new int[m][n]; for (int j = 0;j< n; j++) { res[0][j] =costs[0][j]; } for (int i = 1; i < m; i++) { for (int j = 0; j < n ; j++) { int count = Integer.MAX_VALUE; for (int k = 0; k < n ;k ++) { if (j != k) { count = Math.min(count, res[i-1][k]+costs[i][j]); } } res[i][j] = count; } } int resVal = Integer.MAX_VALUE; for (int j = 0; j< n; j++) { resVal = Math.min(resVal, res[m-1][j]); } return resVal; } } class Solution266 { public boolean canPermutePalindrome(String s) { Set<Character> set = new HashSet<>(); for (int i = 0; i< s.length(); i++) { char c = s.charAt(i); if (set.contains(c)) { set.remove(c); } else { set.add(c); } } return set.size() <= 1; } } class Solution267 { public List<String> generatePalindromes(String s) { Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i< s.length(); i++) { char c = s.charAt(i); if (map.containsKey(c)) { map.put(c, map.get(c)+1); } else { map.put(c, 1); } } List<Character> list = new ArrayList<>(); String mid = ""; int countOfOdd = 0; for (Map.Entry<Character, Integer> entry : map.entrySet()){ for (int i = 0;i< entry.getValue()/2; i++) { list.add(entry.getKey()); } if (entry.getValue()%2 != 0) { mid += entry.getKey(); countOfOdd++; } } List<String> res = new ArrayList<>(); if (countOfOdd > 1) { return res; } boolean[] visisted = new boolean[list.size()]; helper(res, list, visisted, mid, new StringBuilder()); return res; } private void helper( List<String> res, List<Character> list, boolean[] visited, String mid, StringBuilder sb) { if (sb.length() == list.size()) { res.add(sb.toString() + mid + sb.reverse().toString()); sb.reverse(); return; } for (int i = 0; i < list.size(); i++) { if (i>0 && list.get(i) == list.get(i-1) && !visited[i-1]) { continue; } if (!visited[i]) { visited[i] = true; sb.append(list.get(i)); helper(res, list, visited, mid, sb); visited[i] = false; sb.deleteCharAt(sb.length()-1); } } } } class Solution268 { public int missingNumber(int[] nums) { long sum = 0; for (int i : nums) { sum += i; } long target = (nums.length + 0)* (nums.length+1) / 2; return (int)(target - sum); } } class Solution269 { public String alienOrder(String[] words) { List<Set<Character>> order = new ArrayList<Set<Character>>(26); for (int i = 0;i< 26; i++) { order.add(null); } for (int i = 0; i < words.length-1; i++) { int min = Math.min(words[i].length(), words[i+1].length()); for (int j = 0; j < min; j++) { if (order.get(words[i+1].charAt(j)-'a') == null) { order.set(words[i+1].charAt(j)-'a', new HashSet<>()); } if (words[i].charAt(j) != words[i+1].charAt(j)) { order.get(words[i+1].charAt(j) - 'a').add(words[i].charAt(j)); } } } boolean[] visited = new boolean[26]; boolean[] visiting = new boolean[26]; StringBuilder res = new StringBuilder(); for (int i = 0; i < 26; i++) { if (order.get(i) != null) { if (!dfs(res, order, visited, visiting, i)) { return ""; } } } return res.toString(); } private boolean dfs(StringBuilder res, List<Set<Character>> order, boolean[] visited, boolean[] visiting, int start) { if (visited[start]) { return true;} if (visiting[start]) {return false;} visiting[start] = true; if (order.get(start) != null) { for (char c : order.get(start)) { if (!dfs(res, order, visited, visiting, c - 'a')) { return false; } } } visiting[start] = false; visited[start] = true; res.append((char)('a' + start)); return true; } } class Solution270 { public int closestValue(TreeNode root, double target) { return (int)closestValueL(root, target); } public long closestValueL(TreeNode root, double target) { if (root == null) { return Long.MAX_VALUE; } long left = closestValueL(root.left, target); long right = closestValueL(root.right, target); long res = 0; if (Math.abs(left - target) < Math.abs(right - target)) { res = left; } else { res = right; } if (Math.abs(res-target) > Math.abs(root.val - target)) { res = root.val; } return res; } } class Codec271 { // Encodes a list of strings to a single string. public String encode(List<String> strs) { if (strs == null || strs.size() == 0) return null; StringBuilder sb = new StringBuilder(); for (String s: strs) { sb.append(s.length()).append("/").append(s); } return sb.toString(); } // Decodes a single string to a list of strings. public List<String> decode(String s) { List<String> res = new ArrayList<>(); int i = 0; while(i < s.length()) { int j = s.indexOf('/', i); int length = Integer.parseInt(s.substring(i, j)); res.add(s.substring(j+1, j+1+length)); i = j+length+ 1; } return res; } } class Solution272 { public List<Integer> closestKValues(TreeNode root, double target, int k) { Comparator<Integer> cmp = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { if (Math.abs((long) o1 - target) - Math.abs((long) o2 - target) < 0) { return -1; } else { return 1; } } }; PriorityQueue<Integer> pq = new PriorityQueue<>(); closestValueL(root, pq, k, target); List<Integer> res = new ArrayList<>(); for(Integer i : pq) { res.add(i); } return res; } public void closestValueL(TreeNode root, PriorityQueue<Integer> pq, int k, double target) { if (root == null) { return; } if (pq.size() < k) { pq.add(root.val); } else { int pqval = pq.peek(); if (Math.abs(root.val - target) < Math.abs(pqval - target)){ pq.remove(); pq.add(root.val); } } closestValueL(root.left, pq, k, target); closestValueL(root.right, pq, k, target); } } class Solution273 { private final String[] belowTen = new String[] {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}; private final String[] belowTwenty = new String[] {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; private final String[] belowHundred = new String[] {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; public String numberToWords(int num) { if (num == 0) { return "Zero"; } return parse2dig(num); } private String parse2dig(int input) { String res = new String(); if (input < 10) {res = belowTen[input];} else if (input < 20) {res = belowTwenty[input];} else if (input < 100) {res = belowHundred[input/10] + " " + belowTen[input%10];} else if (input < 1000) { res = belowTen[input/100] + " Hundred " + parse2dig(input%100);} else if (input < 1000000) { res = parse2dig(input/1000) + " Thousand " + parse2dig(input %1000); } else if (input < 1000000000) { res = parse2dig(input/1000000) + " Million " + parse2dig(input %1000000); } else { res = parse2dig(input / 1000000000) + " Billion " + parse2dig(input % 1000000000); } return res.trim(); } } class Solution274_275 { public int hIndex(int[] citations) { int m = citations.length; Arrays.sort(citations); int citation = 0; for (int i = 0; i < m; i++) { if (citations[m-1-i] >= i+1) { citation = i+1; } else { break; } } return citation; } } class Solution276 { public int numWays(int n, int k) { if (n == 1) return k; int same = k; int diff = k * (k-1); int i = 1; while(i< n) { int tmp = diff; diff = (same+ diff) * (k-1); same = tmp; } return same+diff; } } class Solution278 { //extends VersionControl { public int firstBadVersion(int n) { int l = 1; int r =n; while(l<r) { int mid = l + (r-l)/2; if (isBadVersion(mid)) { r = mid - 1; } else { l = mid; } } return l; } private boolean isBadVersion(int n) { return n>=2; } } //10/8/17 class Solution280 { public void wiggleSort(int[] nums) { Arrays.sort(nums); for (int i = 2; i < nums.length-1; i = i+2) { int tmp = nums[i]; nums[i] = nums[i+1]; nums[i+1] = tmp; } } } class Solution277 {//extends Relation { public int findCelebrity(int n) { int a = 0; for (int i = 0; i < n; i++) { if (a != i && knows(a, i)) { a = i; } } for (int i = 0; i< n; i++) { if (i != a && (knows(a,i) || !knows(i,a))) return -1; } return a; } boolean knows(int a, int b) { if (a == 0 && b ==1) return true; if (a == 1 && b ==0) return false; return false; } } class ZigzagIterator { //281 int i = 0; int indexes[]; List<List<Integer>> t; int m; public ZigzagIterator(List<Integer> v1, List<Integer> v2) { t = new ArrayList<>(); t.add(v1); t.add(v2); m = t.size(); indexes = new int[m]; } public int next() { if (hasNext()) { int res = t.get(i).get(indexes[i]); indexes[i]++; i = (i+1) %m; return res; } return -1; } public boolean hasNext() { int count = 0; while(indexes[i] >= t.get(i).size()) { if (count >= m) { return false;} i = (i+1)%m; count ++; } return true; } } class Solution282 { public List<String> addOperators(String num, int target) { List<String> res = new ArrayList<>(); if (num == null || num.length() == 0) return res; dfs(res, "", num, target, 0,0,0); return res; } private void dfs(List<String> res, String path, String num, int target, int pos, long eval, long multed) { if (pos == num.length()) { if (target == eval) { res.add(path); } } for(int i = pos; i < num.length(); i++) { if (i != pos && num.charAt(pos) == '0') break; long cur = Long.parseLong(num.substring(pos, i+1)); if (pos == 0) { dfs(res, path + cur, num, target, i+1, cur, cur); } else { dfs(res, path + "+" + cur, num, target, i+1, eval+cur, cur); dfs(res, path + "-" + cur, num, target, i+1, eval-cur, -cur); dfs(res, path + "*" + cur, num, target, i+1, eval- multed + multed * cur, multed * cur); } } } } class Solution284 { public void moveZeroes(int[] nums) { int i = 0; int j = 0; while(i< nums.length && nums[i] != 0) { i++;j++; } while (j < nums.length) { while(j< nums.length && nums[j] == 0) {j++;} if (j<nums.length) { nums[i++]= nums[j]; nums[j] = 0; j++; } } } } class PeekingIterator implements Iterator<Integer> { private Integer next; private Iterator<Integer> mIterator; public PeekingIterator(Iterator<Integer> iterator) { mIterator = iterator; next = null; } // Returns the next element in the iteration without advancing the iterator. public Integer peek() { if (next == null) { if (hasNext()) { next = mIterator.next(); } } return next; } // hasNext() and next() should behave the same as in the Iterator interface. // Override them if needed. @Override public Integer next() { Integer res = peek(); next = null; return res; } @Override public boolean hasNext() { if (next != null) { return true; } return mIterator.hasNext(); } } class Solution285 { public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { if (root == null || p == null) return null; TreeNode next = null; if (p.right != null) { next = p.right; while(next.left != null) { next = next.left; } return next; } while(root != null && root != p) { if (root.val > p.val) { next = root; root = root.left; } else { root = root.right; } } if (root == null) return null; return next; } } class Solution286 { class Point{ int x,y; public Point(int a, int b) { x = a; y = b; } } public void wallsAndGates(int[][] rooms) { int m = rooms.length; if (m == 0) return; int n = rooms[0].length; if (n == 0) return; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (rooms[i][j] == 0) { bfs(rooms, i, j); } } } } private void bfs(int[][] rooms, int i, int j) { Queue<Point> p = new LinkedList<>(); int m = rooms.length; int n = rooms[0].length; p.add(new Point(i,j)); p.add(null); int dist = 0; while(!p.isEmpty()) { Point tmp = p.poll(); if (tmp == null) { if (!p.isEmpty()) { p.add(null); } dist++; continue; } int x = tmp.x; int y = tmp.y; if (rooms[x][y] > dist) { rooms[x][y] = dist; } if (x-1>=0 && rooms[x-1][y] > dist+1) { p.add(new Point(x-1, y)); } if (x+1<m && rooms[x+1][y] > dist+1) { p.add(new Point(x+1, y)); } if (y-1>=0 && rooms[x][y-1] > dist+1) { p.add(new Point(x, y-1)); } if (y+1<n && rooms[x][y+1] > dist+1) { p.add(new Point(x, y+1)); } } } } class Solution287 { // this question need redo... still not quite under stand the logic public int findDuplicate(int[] nums) { if (nums.length > 1) { int slow = nums[0]; int fast = nums[nums[0]]; while (slow != fast) { slow = nums[slow]; fast = nums[nums[fast]]; } fast = 0; while (fast != slow) { fast = nums[fast]; slow = nums[slow]; } return slow; } return -1; } } class ValidWordAbbr { //288 Map<String, Integer> map = new HashMap<>(); Set<String> dict = new HashSet<>(); public ValidWordAbbr(String[] dictionary) { for (String s : dictionary) { if(!dict.contains(s)) { String abb = abb(s); map.put(abb, map.getOrDefault(abb, 0) + 1); dict.add(s); } } } public boolean isUnique(String word) { String abb = abb(word); if (dict.contains(word)) { return map.getOrDefault(abb, 0) == 1; } return map.getOrDefault(abb, 0) == 0; } private String abb(String s) { if (s.length() <=2) return s; StringBuilder sb = new StringBuilder(); int length = s.length()-2; sb.append(s.charAt(0)); if (length > 0) { sb.append(String.valueOf(length)); } sb.append(s.charAt(s.length()-1)); return sb.toString(); } } class Solution289 { public void gameOfLife(int[][] board) { int m = board.length; if (m == 0) return; int n = board[0].length; if (n == 0) return; int[][] nextgen = new int[m][n]; for (int i = 0; i< m; i++) { for (int j = 0; j < n ; j++) { int neib = findNeighbor(board, i, j); if (neib < 2) {nextgen[i][j] = 0;} else if (neib == 2) {nextgen[i][j] = board[i][j];} else if (neib == 3) {nextgen[i][j] = 1;} else {nextgen[i][j] = 0;} } } for (int i = 0; i < m; i++) { for (int j = 0; j< n; j++) { board[i][j] = nextgen[i][j]; } } } private int findNeighbor(int[][] board, int i, int j) { int m = board.length; int n = board[0].length; int res = 0; for (int x = i-1; x<=i+1; x++) { for (int y = j-1; y<=j+1; y++ ) { if (x >=0 && x < m && y>=0 && y < n && !(x ==i && y == j)) { res += board[x][y] == 1 ? 1 : 0; } } } return res; } } class Solution290 { public boolean wordPattern(String pattern, String str) { if (pattern.length() == 0) return false; String[] tokens = str.split(" "); if (tokens.length != pattern.length()) {return false;} Map<Character, String> map = new HashMap<>(); for (int i= 0; i<pattern.length(); i++) { if (!map.containsKey(pattern.charAt(i))) { map.put(pattern.charAt(i), tokens[i]); } else { if (!map.get(pattern.charAt(i)).equals(tokens[i])) { return false; } } } Map<String, Character> m2 = new HashMap<>(); for (int i = 0; i < pattern.length();i++) { if(!m2.containsKey(tokens[i])) { m2.put(tokens[i], pattern.charAt(i)); } else { if (!m2.get(tokens[i]).equals(pattern.charAt(i))) { return false; } } } return true; } } class Solution292 { public boolean canWinNim(int n) { if (n<4) return true; return n%4 != 0; } } class Solution293 { public List<String> generatePossibleNextMoves(String s) { List<String> res = new ArrayList<>(); if (s.length() == 0) return res; char[] chars = s.toCharArray(); for (int i = 0; i< chars.length -1; i = i+2) { if (chars[i] == '+' && chars[i+1] == '+'){ chars[i] = '-'; chars[i + 1] = '-'; res.add(String.valueOf(chars)); chars[i] = '+'; chars[i + 1] = '+'; } } return res; } } class Solution294 { public boolean canWin(String s) { for (int i= 0; i< s.length()-1; i++) { if (s.charAt(i) == '+' && s.charAt(i+1) == '+') { if (!canWin(s.substring(0,i) +"--" + s.substring(i+2))) { return true; } } } return false; } } class Solution299 { public String getHint(String secret, String guess) { Map<Character, Integer> gMap = new HashMap<>(); int bull = 0; for (int i = 0;i< secret.length(); i++) { if (secret.charAt(i) == guess.charAt(i)) { bull++; continue; } int gl = 0; if (gMap.containsKey(guess.charAt(i))) { gl = gMap.get(guess.charAt(i)); } gl++; gMap.put(guess.charAt(i), gl); } int cow = 0; for (int i = 0; i< secret.length(); i++) { if(secret.charAt(i) == guess.charAt(i)) { continue; } int gl = gMap.getOrDefault(secret.charAt(i), 0); if (gl == 0) {continue;}; if (gl > 0) { cow ++; gl--; gMap.put(secret.charAt(i), gl); } } StringBuilder res = new StringBuilder(); res.append(String.valueOf(bull)); res.append("A"); res.append(String.valueOf(cow)); res.append("B"); return res.toString(); } } class Solution300 { public int lengthOfLIS(int[] nums) { int m = nums.length; if (m == 0) return 0; int[] dp = new int[m]; dp[0] = 1; for (int i = 1; i< nums.length;i++) { int tmp = 1; for (int j = 0; j< i;j++) { if (nums[i] > nums[j]) { tmp = Math.max(dp[j]+1, tmp); } } dp[i] = tmp; } int res = 0; for (int i = 0;i<dp.length;i++) { res = Math.max(res, dp[i]); } return res; } } class Solution298 { public int longestConsecutive(TreeNode root) { if (root == null) return 0; List<Integer> t = new ArrayList<>(); return longest(root, t); } public int longest(TreeNode root, List<Integer> tracker) { if (root == null) { return calculate(tracker); } tracker.add(root.val); int left = longest(root.left, tracker); int right = longest(root.right, tracker); tracker.remove(tracker.size()-1); return Math.max(left, right); } private int calculate(List<Integer> t) { int res = 0; int tmp = 1; for (int i = 1;i< t.size();i++) { if (t.get(i)-t.get(i-1) ==1) { tmp++; } else { tmp = 1; } res = Math.max(res, tmp); } res = Math.max(res, tmp); return res; } } // 10/9/17 class MedianFinder { // 295 PriorityQueue<Integer> maxHeap; PriorityQueue<Integer> minHeap; /** initialize your data structure here. */ public MedianFinder() { Comparator<Integer> minCmp = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1 - o2; } }; Comparator<Integer> maxCamp = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } }; minHeap = new PriorityQueue<>(minCmp); maxHeap = new PriorityQueue<>(maxCamp); } public void addNum(int num) { int minSize = minHeap.size(); int maxSize = maxHeap.size(); if (minSize == 0 && maxSize == 0) { minHeap.add(num); return; } if (maxSize == 0) { if (num < minHeap.peek()) { maxHeap.add(num); } else { maxHeap.add(minHeap.poll()); minHeap.add(num); } return; } int minHeapValue = minHeap.peek(); int maxHeapValue = maxHeap.peek(); if (num >= maxHeapValue) { minHeap.add(num); minSize++; } else if (num <= minHeapValue) { maxHeap.add(num); maxSize++; } if (minSize - maxSize > 1) { maxHeap.add(minHeap.poll()); } else if (maxSize - minSize > 1) { minHeap.add(maxHeap.poll()); } } public double findMedian() { int minSize = minHeap.size(); int maxSize = maxHeap.size(); if (minSize == 0 && maxSize == 0) { return 0; } if (minSize == 0 && maxSize != 0) { return maxHeap.peek(); } if (maxSize == 0 && minSize != 0) { return minHeap.peek(); } if (minSize > maxSize) { return minHeap.peek(); } else if (maxSize > minSize) { return maxHeap.peek(); } else { int a = minHeap.peek(); int b = maxHeap.peek(); return ((double)a + (double)b)/2.0; } } } class Solution296 { public int minTotalDistance(int[][] grid) { int m = grid.length; if (m == 0) return 0; int n = grid[0].length; if (n == 0) return 0; boolean[][] home = new boolean[m][n]; for (int i = 0; i< m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 1) { grid[i][j] = -1; } else if (grid[i][j] == 2) { grid[i][j] = -2; } } } for (int i = 0; i < m; i++) { for (int j = 0; j< n; j++) { if (grid[i][j] != -1) { continue; } clearHome(home); Queue<int[]> q = new LinkedList<>(); q.add(new int[]{i,j}); q.add(null); int dist = 0; while(!q.isEmpty()) { int[] tmp = q.poll(); if (tmp == null) { if (!q.isEmpty()) { q.add(null); } else { if (dist == 0) return -1; } dist++; continue; } int x = tmp[0]; int y = tmp[1]; grid[x][y] += dist; if (x-1>=0 && !home[x-1][y] && grid[x-1][y] >= 0) { q.add(new int[]{x-1, y}); home[x-1][y] = true; } if (x+1<m && !home[x+1][y] && grid[x+1][y] >= 0) { q.add(new int[]{x+1, y}); home[x+1][y] = true; } if (y-1>=0 && !home[x][y-1] && grid[x][y-1] >= 0) { q.add(new int[] {x, y-1}); home[x][y-1] = true; } if (y+1<n && !home[x][y+1] && grid[x][y+1] >= 0) { q.add(new int[] {x, y+1}); home[x][y+1] = true; } } if (dist == 0) return -1; } } int mindis = Integer.MAX_VALUE; for (int i = 0; i< m; i++) { for (int j = 0; j< n; j++) { if (grid[i][j] <= 0 ) { continue; } mindis = Math.min(mindis, grid[i][j]); } } return mindis == Integer.MAX_VALUE ? -1 : mindis; } private void clearHome(boolean[][] home) { int m = home.length; int n = home[0].length; for (int i = 0; i< m; i++) { for (int j = 0; j< n; j++) { home[i][j] = false; } } } } //10/10/17 class Codec { //297 // Encodes a tree to a single string. public String serialize(TreeNode root) { StringBuilder sb = new StringBuilder(); build(sb, root); sb.deleteCharAt(sb.length()-1); return sb.toString(); } private void build(StringBuilder sb, TreeNode root) { if (root == null) { sb.append("null"); sb.append(","); return; } sb.append(String.valueOf(root.val)); sb.append(","); build(sb, root.left);; build(sb, root.right); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { Deque<String> d = new LinkedList<>(Arrays.asList(data.split(","))); return create(d); } private TreeNode create(Deque<String> d) { String s = d.pollFirst(); if (s.equals("null")) { return null; } TreeNode root = new TreeNode(Integer.parseInt(s)); root.left = create(d); root.right = create(d); return root; } } class Solution291 { Map<Character, String> map = new HashMap<>(); Set<String> set = new HashSet<>(); public boolean wordPatternMatch(String pattern, String str) { if (pattern.isEmpty()) return str.isEmpty(); if (map.containsKey(pattern.charAt(0))) { String value = map.get(pattern.charAt(0)); if (str.length() < value.length() || !str.substring(0, value.length()).equals(value)){ return false; } if (wordPatternMatch(pattern.substring(1), str.substring(value.length()))) { return true; } } else { for (int i = 1; i<= str.length(); i++) { if (set.contains(str.substring(0, i))) { continue; } map.put(pattern.charAt(0), str.substring(0, i)); set.add(str.substring(0, i)); if (wordPatternMatch(pattern.substring(1), str.substring(i))) { return true; } set.remove(str.substring(0,i)); map.remove(pattern.charAt(0)); } } return false; } } class Solution302 { class Point { int x, y; public Point(int a, int b) {x = a; y = b;} } public int minArea(char[][] image, int x, int y) { int m = image.length; if (m == 0) return 0; int n = image[0].length; if (n == 0) return 0; int left = Integer.MAX_VALUE; int right = Integer.MIN_VALUE; int top = Integer.MAX_VALUE; int bottom = Integer.MIN_VALUE; Queue<Point> q = new LinkedList<>(); q.add(new Point(x,y)); image[x][y] = '0'; while(!q.isEmpty()) { Point cur = q.poll(); int i = cur.x; int j = cur.y; left = Math.min(left, i); right = Math.max(right, i); top = Math.min(j, top); bottom = Math.max(j, bottom); if (i-1 >= 0 && image[i-1][j] == '1') { q.add(new Point(i-1, j)); image[i-1][j] = '0'; } if (i+1 < m && image[i+1][j] == '1') { q.add(new Point(i+1, j)); image[i+1][j] = '0'; } if (j-1 >= 0 && image[i][j-1] == '1') { q.add(new Point(i, j-1)); image[i][j-1] = '0'; } if (j+1 < n && image[i][j+1] == '1') { q.add(new Point(i, j+1)); image[i][j+1] = '0'; } } return (right-left+1) * (bottom - top+1); } } class NumArray { //303 int[] sum; public NumArray(int[] nums) { int m = nums.length; if (m == 0) return; sum = new int[m]; sum[0] = nums[0]; for (int i = 1; i< m; i++) { sum[i] = nums[i] + sum[i-1]; } } public int sumRange(int i, int j) { if (i == 0) { return sum[j]; } else { return sum[j] - sum[i-1]; } } } class NumMatrix { //304 int[][] sum; public NumMatrix(int[][] matrix) { int m = matrix.length; if (m == 0) {return;} int n = matrix[0].length; if (n == 0) {return;} sum = new int[m][n]; sum[0] = matrix[0]; for (int i = 1; i< m ; i++) { sum[i][0] = sum[i-1][0] + matrix[i][0]; } for (int j = 1; j < n; j++) { sum[0][j] = sum[0][j-1] + matrix[0][j]; } for(int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { sum[i][j] = sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] + matrix[i][j]; } } } public int sumRegion(int row1, int col1, int row2, int col2) { int left = col1 == 0 ? 0 : sum[row2][col1-1]; int top = row1 == 0 ? 0 : sum[row1-1][col2]; int topleft = (col1 == 0 || row1 == 0) ? 0 : sum[row1-1][col1-1]; return sum[row2][col2] - left - top + topleft; } } class Solution306 { public boolean isAdditiveNumber(String num) { if (num.length() == 0) return false; for(int i = 1; i < num.length()-1; i++) { if (i > 1 && num.charAt(0) == '0') continue; if (isAdditive(-1, -1, Long.parseLong(num.substring(0, i)), num, i)) { return true; } } return false; } private boolean isAdditive(long num0, long num1, long num2, String num, int index) { if (index == num.length()) { if (num0 + num1 == num2) { return true; } return false; } for (int i = index + 1; i<= num.length();i++) { if (i - index > 1 && num.charAt(i) == '0') return false; long tmp = Long.parseLong(num.substring(index, i)); if (num1 != -1 && ((num1 + num2 )!= tmp)) { continue; } if (isAdditive(num1, num2, tmp, num, i)) { return true; } } return false; } } // 10/11/17 class NumArray307 { class SegSumTreeNode{ public int l, r, sum; public SegSumTreeNode left, right; public SegSumTreeNode(int a, int b, int s) { l = a; r = b; sum = s; } } private SegSumTreeNode root; public NumArray307(int[] nums) { root = buildTree(nums, 0, nums.length - 1); } private SegSumTreeNode buildTree(int nums[], int l, int r) { if (l > r) { return null; } if (l == r) { SegSumTreeNode root = new SegSumTreeNode(l, r, nums[l]); return root; } int mid = l + (r-l) / 2; SegSumTreeNode left = buildTree(nums, l, mid); SegSumTreeNode right = buildTree(nums, mid+1, r); SegSumTreeNode root = new SegSumTreeNode(l, r, left.sum + right.sum); root.left = left; root.right = right; return root; } public void update(int i, int val) { update(root, i, val); } private void update(SegSumTreeNode tmp, int i, int val) { if (tmp.l == tmp.r && tmp.l == i) { tmp.sum = val; return; } if (tmp.left != null && (tmp.left.l <= i && tmp.left.r >= i)) { update(tmp.left, i, val); } else if (tmp.right != null && (tmp.right.l <= i && tmp.right.r >= i)) { update(tmp.right, i, val); } tmp.sum = tmp.left.sum + tmp.right.sum; } // assum i and j are always validate public int sumRange(int i, int j) { return findSum(root, i, j); } private int findSum(SegSumTreeNode root, int i, int j) { if (root.l == i && root.r == j) { return root.sum; } if (root.left != null && j <= root.left.r) { return findSum(root.left, i, j); } if (root.right != null && i >= root.right.l) { return findSum(root.right, i, j); } int leftSum = 0; if (root.left != null && i <= root.left.r) { leftSum = findSum(root.left, i, root.left.r); } int rightSum = 0; if (root.right != null && j >= root.right.l) { rightSum = findSum(root.right, root.right.l, j); } return leftSum + rightSum; } } class Solution309 { public int maxProfit(int[] prices) { int n = prices.length; int[] out = new int[n]; int[] in = new int[n]; int[] coolDown = new int[n]; coolDown[0] = Integer.MIN_VALUE; out[0] = 0; in[0] = - prices[0]; for (int i = 1; i < n; i++) { in[i] = Math.max(in[i-1], out[i-1] - prices[i]); out[i] = Math.max(out[i-1], coolDown[i-1]); coolDown[i] = in[i-1] + prices[i]; } int res = 0; for (int i = 0; i< n ;i ++) { res = Math.max(in[i], res); } res = Math.max(in[n-1] + prices[n-1], res); res = Math.max(res, out[n-1]); res = Math.max(res, coolDown[n-1]); return res; } } class Solution310 { public List<Integer> findMinHeightTrees(int n, int[][] edges) { Map<Integer, Integer> map = new HashMap<>(); Queue<Integer> q = new LinkedList<>(); Set<Integer> s = new HashSet<>(); int[] h = new int[n]; for (int i = 0; i< n; i++) { q.clear(); s.clear(); q.add(i); q.add(null); s.add(i); int height = 0; while(!q.isEmpty()) { Integer tmp = q.poll(); if (tmp == null) { if (!q.isEmpty()) { q.add(null); } height++; continue; } for(int[] edge : edges) { int node = getOtherNode(edge, tmp); if (node != -1 && !s.contains(node)) { q.add(node); s.add(node); } } } h[i] = height; } int minh = Integer.MAX_VALUE; for (int i : h) { minh = Math.min(i, minh); } List<Integer> l = new ArrayList<>(); for (int i = 0; i < n; i++) { if (h[i] == minh) { l.add(i); } } return l; } private int getOtherNode(int[] edge, int i) { if (edge[0] == i) { return edge[1]; } else if (edge[1] == i) { return edge[0]; } else { return -1; } } } class Solution313 { public int nthSuperUglyNumber(int n, int[] primes) { int[] res = new int[n]; res[0] = 1; int m = primes.length; int[] dp = new int[m]; for (int i = 0;i< m; i++) { dp[i] = 0; } for (int i = 1; i<n; i++) { int tmp = Integer.MAX_VALUE; for(int j = 0; j< m; j++) { tmp = Math.min(tmp, res[dp[j]] * primes[j]); } res[i] = tmp; for (int j = 0;j< m; j++) { if (res[dp[j]] * primes[j] == tmp) { dp[j]++; } } } return res[n-1]; } } class Solution314 { public List<List<Integer>> verticalOrder(TreeNode root) { Map<Integer, List<Integer>> map = new HashMap<>(); visit(root, 0, map); List<Integer> keys = new ArrayList<>(map.keySet()); Collections.sort(keys); List<List<Integer>> res = new ArrayList<>(); for(Integer i : keys) { res.add(map.get(i)); } return res; } private void visit(TreeNode root, int index, Map<Integer, List<Integer>> map) { if(root == null) return; List<Integer> res = new ArrayList<>(); if (map.keySet().contains(index)) { res = map.get(index); } res.add(root.val); map.put(index, res); visit(root.left, index-1, map); visit(root.right, index+1, map); } } // 10/12/17 class Solution301 { public List<String> removeInvalidParentheses(String s) { List<String> ans = new ArrayList<>(); remove(s, ans, 0, 0, new char[]{'(', ')'}); return ans; } public void remove(String s, List<String> ans, int last_i, int last_j, char[] par) { for (int stack = 0, i = last_i; i < s.length(); ++i) { if (s.charAt(i) == par[0]) stack++; if (s.charAt(i) == par[1]) stack--; if (stack >= 0) continue; for (int j = last_j; j <= i; ++j) if (s.charAt(j) == par[1] && (j == last_j || s.charAt(j - 1) != par[1])) remove(s.substring(0, j) + s.substring(j + 1, s.length()), ans, i, j, par); return; } String reversed = new StringBuilder(s).reverse().toString(); if (par[0] == '(') // finished left to right remove(reversed, ans, 0, 0, new char[]{')', '('}); else // finished right to left ans.add(reversed); } } // 10/13/17 class Solution334 { public boolean increasingTriplet(int[] nums) { int s = Integer.MAX_VALUE; int m = Integer.MAX_VALUE; for(int i = 0; i< nums.length; i++) { if (nums[i] < s) { // m = s; s =nums[i]; } else if (nums[i] < m) { m = nums[i]; } else { return true; } } return false; } } class Solution305 { public List<Integer> numIslands2(int m, int n, int[][] positions) { int[] t = new int[m*n]; for (int i = 0; i < m*n; i++) { t[i] = -1; } List<Integer> res = new ArrayList<>(); int k = positions.length; for (int i = 0; i < k; i++) { int x = positions[i][0]; int y = positions[i][1]; int top = x == 0 ? -1 : t[(x-1)*n + y]; int left = y == 0 ? -1 : t[x*n + y - 1]; int bottom = x == m -1 ? -1 : t[(x+1)*n + y]; int right = y == n - 1 ? -1 : t[x*n + y + 1]; int target = Math.max(top, left); target = Math.max(bottom, target); target = Math.max(right, target); if (target != -1) { for (int j = 0; j < m*n; j++) { if (top != -1 && t[j] == top) { t[j] = target;} if (left != -1 && t[j] == left) { t[j] = target;} if (right != -1 && t[j] == right) { t[j] = target;} if (bottom != -1 && t[j] == bottom) { t[j] = target;} } t[x*n + y] = target; } else { t[x*n + y] = i; } Set<Integer> s = new HashSet<>(); for (int l = 0; l <= m*n; l++) { if (t[l] > -1) { s.add(t[l]); } } res.add(s.size()); } return res; } } class Solution305II { public List<Integer> numIslands2(int m, int n, int[][] positions) { int[] t = new int[m*n]; for (int i = 0; i < m*n; i++) { t[i] = -1; } List<Integer> res = new ArrayList<>(); int k = positions.length; int count = 0; for (int i = 0; i < k; i++) { int x = positions[i][0]; int y = positions[i][1]; int top = x == 0 ? -1 : find(t, (x-1)*n + y); int left = y == 0 ? -1 : find(t, x*n + y - 1); int bottom = x == m -1 ? -1 : find(t, (x+1)*n + y); int right = y == n - 1 ? -1 : find(t, x*n + y + 1); Set<Integer> p = new HashSet<>(); p.add(top); p.add(left); p.add(bottom); p.add(right); List<Integer> l = new ArrayList<>(p); Collections.sort(l);; Collections.reverse(l); int target = Integer.MIN_VALUE; for (int index : l) { target = Math.max(target, index); } if (target != -1) { for (int index : l) { if (index != -1 && index != target) { t[index] = target; count --; } } t[x*n + y] = target; } else { t[x*n + y] = x*n +y; count++; } res.add(count); } return res; } int find(int[] t, int i) { if (t[i] == -1) { return -1; } while(t[i] != i) { i = t[i]; } return i; } void join(int[] t, int i, int j) { t[j] = t[i]; } } class NumMatrix308 { int[][] sum; int[][] original; public NumMatrix308(int[][] matrix) { int m = matrix.length; if (m == 0) {return;} int n = matrix[0].length; if (n == 0) {return;} sum = new int[m][n]; original = new int[m][n]; for (int i = 0; i< m; i++) { for (int j = 0; j < n; j++) { original[i][j] =matrix[i][j]; } } sum[0] = matrix[0]; for (int i = 1; i< m ; i++) { sum[i][0] = sum[i-1][0] + matrix[i][0]; } for (int j = 1; j < n; j++) { sum[0][j] = sum[0][j-1] + matrix[0][j]; } for(int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { sum[i][j] = sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] + matrix[i][j]; } } } public void update(int row, int col, int val) { int m = original.length; int n = original[0].length; int originalVal = original[row][col]; int delta = val - originalVal; original[row][col] = val; for (int i = row; i< m; i++) { for (int j = col; j< n; j++) { sum[i][j] += delta; } } } public int sumRegion(int row1, int col1, int row2, int col2) { int left = col1 == 0 ? 0 : sum[row2][col1-1]; int top = row1 == 0 ? 0 : sum[row1-1][col2]; int topleft = (col1 == 0 || row1 == 0) ? 0 : sum[row1-1][col1-1]; return sum[row2][col2] - left - top + topleft; } } class Solution318 { public int maxProduct(String[] words) { Map<String, int[]> map = new HashMap<>(); for (String s : words) { map.put(s, new int[] {mask(s), s.length()}); } int res = 0; for (int i = 0; i < words.length; i++) { for (int j = i + 1; j <words.length; j++) { int[] val1 = map.get(words[i]); int[] val2 = map.get(words[j]); if ((val1[0] & val2[0]) == 0) { res = Math.max(res, val1[1] * val2[1]); } } } return res; } private int mask(String s) { int mask = 0; for (int i = 0; i < s.length(); i++) { mask = mask | (1 << (s.charAt(i) - 'a')); } return mask; } } class Solution319 { public int bulbSwitch(int n) { boolean[] t = new boolean[n]; for (int i = 1; i<=n; i++) { for (int j = 0; j<n; j++) { if ((j+1)%i ==0) { t[j] = !t[j]; } } } int res = 0; for (int i = 0; i < n; i++) { res += t[i]? 1 : 0; } return res; } } class Solution320 { public List<String> generateAbbreviations(String word) { List<String> res = new ArrayList<>(); gen(res, word, 0, "", 0); return res; } private void gen(List<String> ret, String word, int pos, String cur, int count){ if(pos==word.length()){ if(count > 0) cur += count; ret.add(cur); } else{ gen(ret, word, pos + 1, cur, count + 1); gen(ret, word, pos+1, cur + (count>0 ? count : "") + word.charAt(pos), 0); } } } class Solution315 { // this is still over time. class SegmentTreeNode{ int l, r, count; SegmentTreeNode left, right; public SegmentTreeNode(int a, int b) {l = a; r = b;} } public List<Integer> countSmaller(int[] nums) { int m = nums.length; List<Integer> res = new ArrayList<>(); if (m == 0) return res; int s = Integer.MAX_VALUE; int l = Integer.MIN_VALUE; for (int i : nums) { s = Math.min(s, i); l = Math.max(l, i); } SegmentTreeNode root = build(s, l); for (int i = m-1; i>=0; i--) { res.add(query(root, s, nums[i]-1)); update(root, nums[i]); } Collections.reverse(res); return res; } private SegmentTreeNode build(int l, int r) { if (l > r) return null; if (l == r) { return new SegmentTreeNode(l,r); } int mid = l + (r-l)/2; SegmentTreeNode left = build(l, mid); SegmentTreeNode right = build(mid+1, r); SegmentTreeNode root = new SegmentTreeNode(l, r); root.left = left; root.right = right; return root; } private void update(SegmentTreeNode root, int t) { if (root.l == root.r && root.l == t) { root.count++; return; } if (root.left != null && t<= root.left.r) { update(root.left, t); } else if (root.right != null && t >= root.right.l) { update(root.right, t); } root.count = (root.left == null ? 0 : root.left.count) + (root.right == null ? 0 : root.right.count); } private int query(SegmentTreeNode root, int s, int l) { if (root == null) return 0; if (l < s) return 0; if (s == l && root.l == root.r && s == root.l) { return root.count; } int count1 = 0; if (root.left != null) { if (l <= root.left.r) { count1 = query(root.left, s, l); } else { count1 = query(root.left, s, root.left.r); } } int count2 = 0; if (root.right != null) { if (s >= root.right.l) { count2 = query(root.right, s, l); } else { count2 = query(root.right, root.right.l, l); } } return count1 + count2; } } class Solution315_II { class TreeNode_X { int val; int sum; int dup; TreeNode_X left; TreeNode_X right; public TreeNode_X(int v) { val = v; dup = 1; } } public List<Integer> countSmaller(int[] nums) { int m = nums.length; Integer[] res = new Integer[m]; TreeNode_X root = null; for (int i = m-1; i >= 0; i--) { root = build(nums[i], res, root, i, 0); } return Arrays.asList(res); } private TreeNode_X build(int num, Integer[] res, TreeNode_X root, int index, int preSum) { if (root == null) { res[index] = preSum; return new TreeNode_X(num); } else if (root.val == num) { root.dup++; res[index] = preSum + root.sum; return root; } else if (num < root.val) { root.sum++; root.left = build(num, res, root.left, index, preSum); return root; } else { root.right = build(num, res, root.right, index, preSum + root.sum + root.dup); return root; } } } class Solution322 { public int coinChange(int[] coins, int amount) { int[] dp = new int[amount+1]; Arrays.fill(dp, -1); dp[0] = 0; for (int i = 1; i <= amount; i++) { int minCount = Integer.MAX_VALUE; for (int j = 0; j < coins.length; j++) { if (i - coins[j] >= 0) { minCount = Math.min(minCount, dp[i - coins[j]] + 1); } if (minCount != Integer.MAX_VALUE) { dp[i] = minCount; } } } return dp[amount]; } } class Solution323 { public int countComponents(int n, int[][] edges) { boolean[] visited = new boolean[n]; int count = 0; for (int i = 0; i < n; i++) { if (!visited[i]) { count ++; dfs(visited, i, edges); } } return count; } private void dfs(boolean[] visited, int node, int[][] edges) { for (int i = 0; i< edges.length; i++) { int otherNode = otherNode(edges[i], node); if (otherNode != -1 && !visited[otherNode]) { visited[otherNode] = true; dfs(visited, otherNode, edges); } } } private int otherNode(int[] edge, int node) { if (edge[0] == node) { return edge[1]; } else if (edge[1] == node) { return edge[0]; } return -1; } } class Solution324 { public void wiggleSort(int[] nums) { Arrays.sort(nums); int i = 1; int j = i +2; while(i +1 < nums.length && j < nums.length) { while(j < nums.length && nums[j] <= nums[i+1]) { if (i+1 == j) { break;} j++; } int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; j++; i = i+2; } } } class Solution325 { public int maxSubArrayLen(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); map.put(0,-1); int sum = 0; int res = 0; for (int i = 0; i< nums.length; i++) { sum += nums[i]; if (map.getOrDefault(sum, null) == null) { map.put(sum, i); } Integer pre = map.getOrDefault(sum-k, null); if (pre != null) { res = Math.max(i - pre, res); } } return res; } } class Solution { public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public ListNode oddEvenList(ListNode head) { if (head == null) return null; ListNode dummy1 = new ListNode(0); ListNode dummy2 = new ListNode(0); dummy1.next = head; dummy2.next = head.next; ListNode run1 = head; ListNode run2 = head.next; while(run1 != null && run2 != null) { if (run1.next != null) { run1.next = run1.next.next; run1 = run1.next; } if (run2.next != null) { run2.next = run2.next.next; run2 = run2.next; } } run1 = dummy1; while(run1.next != null) { run1 = run1.next; } run1.next = dummy2.next; return dummy1.next; } } class Solution331 { class StackNode{ String s; int count; public StackNode(String a, int b) { s = a; count = b; } } public boolean isValidSerialization(String preorder) { String[] tokens = preorder.split(","); if (tokens.length == 1 && tokens[0].equals("#")) return true; Stack<StackNode> dp = new Stack<>(); for (int i = 0; i < tokens.length; i++) { String s = tokens[i]; if (!s.equals("#")) { dp.push(new StackNode(s, 1)); } else { if (dp.isEmpty()) { return false; } while(!dp.isEmpty() && dp.peek().count == 2) { dp.pop(); } if (!dp.isEmpty()) { dp.peek().count++; } else { if (i != tokens.length-1) { return false; } } } } return dp.isEmpty(); } } //10/14/17 class Solution347 { public List<Integer> topKFrequent(int[] nums, int k) { int m = nums.length; List<Integer> res = new ArrayList<>(); if (m == 0 || k ==0) return res; List<Integer>[] buckets = new List[m+1]; Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i< m;i ++) { map.put(nums[i], map.getOrDefault(nums[i], 0) +1); } for (Integer i : map.keySet()) { Integer val = map.get(i); if (buckets[val] == null) { buckets[val]= new ArrayList<>(); } buckets[val].add(i); } for (int i = m; i>=0; i--) { if (res.size() >= k ) {break;} if (buckets[i] == null) {continue;} if (k - res.size() >= buckets[i].size()) { res.addAll(buckets[i]); } else { int count = k - res.size(); for (int j = 0; j <= count; j++) { res.add(buckets[i].get(j)); } } } return res; } } // need redo this one. class Solution336 { public List<List<Integer>> palindromePairs(String[] words) { Map<String, Integer> map = new HashMap<>(); List<List<Integer>> res = new ArrayList<>(); for (int i = 0; i < words.length; i++) { map.put(words[i], i); } for (int i = 0; i < words.length; i++) { StringBuilder sb = new StringBuilder(words[i]); sb.reverse(); String tmp = sb.toString(); if (map.keySet().contains(tmp)) { res.add(new ArrayList<>(Arrays.asList(i, map.get(tmp)))); } // if (map.keySet()) { // res.add(new ArrayList<>(Arrays.asList(i, map.get(tmp.substring(1))))); // } } return res; } } class Solution337 { Map<TreeNode, Integer> map = new HashMap<>(); public int rob(TreeNode root) { if (root == null) return 0; if (map.containsKey(root)) { return map.get(root); } int result1 = root.val + (root.left == null ? 0 : rob(root.left.left) + rob(root.left.right)) + (root.right == null ? 0 : rob(root.right.left) + rob(root.right.right)); int result2 = rob(root.left) + rob(root.right); int res = Math.max(result1, result2); map.put(root, res); return res; } } class Solution338 { public int[] countBits(int num) { int[] t = new int[num+1]; t[0] = 0; for (int i = 1; i<= num; i++) { t[i] = t[i/2] + i%2; } return t; } } interface NestedInteger { // @return true if this NestedInteger holds a single integer, rather than a nested list. public boolean isInteger(); // @return the single integer that this NestedInteger holds, if it holds a single integer // Return null if this NestedInteger holds a nested list public Integer getInteger(); // @return the nested list that this NestedInteger holds, if it holds a nested list // Return null if this NestedInteger holds a single integer public List<NestedInteger> getList(); } class Solution339 { public int depthSum(List<NestedInteger> nestedList) { int res = 0; for (NestedInteger n : nestedList){ res += cal(1, n); } return res; } private int cal(int level, NestedInteger nint) { if(nint.isInteger()) { return level * nint.getInteger(); } else { int res = 0; List<NestedInteger> list = nint.getList(); for (NestedInteger n : list){ res += cal(level+1, n); } return res; } } } class x implements NestedInteger { Integer val; List<NestedInteger> list; public x(int v) { val = v; } public x(List<NestedInteger> l) { list = l; } @Override public boolean isInteger() { return val != null; } @Override public Integer getInteger() { return val; } @Override public List<NestedInteger> getList() { return list; } } class NestedIterator implements Iterator<Integer> { //341 Stack<NestedInteger> s; public NestedIterator(List<NestedInteger> nestedList) { s = new Stack<>(); for (int i = nestedList.size() -1; i >=0; i--) { s.push(nestedList.get(i)); } } @Override public Integer next() { if (hasNext()) { return s.pop().getInteger(); } return null; } @Override public boolean hasNext() { if (s.isEmpty()) return false; if (s.peek().isInteger()) return true; while(!s.isEmpty() && !s.peek().isInteger()) { List<NestedInteger> list = s.pop().getList(); for (int i = list.size() - 1; i >= 0; i--) { s.push(list.get(i)); } } return !s.isEmpty(); } } class Solution344 { public String reverseString(String s) { StringBuilder sb = new StringBuilder(s); sb.reverse(); return sb.toString(); } } class Solution345 { public String reverseVowels(String s) { char[] ch = s.toCharArray(); int l = 0; int r = ch.length-1; while(l < r) { while(l < ch.length && !isVowel(ch[l])) l++; while(r >= 0 && !isVowel(ch[r])) r--; if (l < r) { char tmp = ch[r]; ch[r] = ch[l]; ch[l] = tmp; l++; r--; } } return String.valueOf(ch); } private boolean isVowel(char c) { return c == 'a' || c == 'A' || c == 'e' || c == 'E' || c == 'i' || c == 'I' || c == 'o' || c == 'O' || c == 'u' || c == 'U'; } } class MovingAverage346 { /** Initialize your data structure here. */ int msize; Queue<Integer> q; long total = 0; public MovingAverage346(int size) { msize = size; q = new LinkedList<>(); total = 0; } public double next(int val) { if (q.size() == msize) { total -= q.poll(); } q.add(val); total += val; return (double)total / q.size(); } } class MovingAverage346II { /** Initialize your data structure here. */ int[] t; int count; long total = 0; int index = 0; public MovingAverage346II(int size) { t = new int[size]; count = 0; total = 0; } public double next(int val) { if (count < t.length) count++; total -= t[index]; total += val; t[index] = val; index = (index+1)%t.length; return (double) total/count; } } class HitCounter { //362 int[] hits; int[] timeStamp; /** Initialize your data structure here. */ public HitCounter() { hits = new int[300]; timeStamp = new int[300]; } /** Record a hit. @param timestamp - The current timestamp (in seconds granularity). */ public void hit(int timestamp) { int index = timestamp % 300; if (timeStamp[index] != timestamp) { timeStamp[index] = timestamp; hits[index] = 1; } else { hits[index]++; } } /** Return the number of hits in the past 5 minutes. @param timestamp - The current timestamp (in seconds granularity). */ public int getHits(int timestamp) { int total = 0; for (int i = 0; i < 300; i++) { if (timestamp - timeStamp[(timestamp+i)%300] < 300) { total += hits[(timestamp+i)%300]; } } return total; } } class Solution349 { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> s = new HashSet<>(); for (int a : nums1) { s.add(a); } Set<Integer> res = new HashSet<>(); for (int a : nums2) { if (s.contains(a)) { res.add(a); } } int[] b = new int[res.size()]; int i = 0; for (Integer x : res) { b[i++] = x; } return b; } } class Solution350 { public int[] intersect(int[] nums1, int[] nums2) { Map<Integer, Integer> map = new HashMap<>(); for (int i : nums2) { map.put(i, map.getOrDefault(i, 0) + 1); } List<Integer> res = new ArrayList<>(); for (int i : nums1) { int count = map.getOrDefault(i, 0); if (count > 0) { res.add(i); map.put(i, count-1); } } int[] b = new int[res.size()]; int i = 0; for (Integer x : res) { b[i++] = x; } return b; } } class Solution367 { public boolean isPerfectSquare(int num) { int i = 0; int j = num; while(i <= j) { int mid = i + (j-i) /2; if (mid * mid == num) { return true; } else if (mid* mid > num) { j = mid-1; } else { i = mid+1; } } return false; } } class Solution376 { public int wiggleMaxLength(int[] nums) { int m = nums.length; int[] up = new int[m]; int[] down = new int[m]; up[0] = 1; down[0] = 1; for (int i = 1 ; i < m; i++) { int uplength = 0; int downlength = 0; for (int j = i-1; j>=0; j++) { if (nums[i] > nums[j]) { uplength = Math.max(uplength, down[j] + 1); } else if (nums[i] < nums[j]) { downlength = Math.max(downlength, up[j] + 1); } } up[i] = uplength; down[i] = downlength; } int res = Integer.MIN_VALUE; for (int i = 0; i< m; i++) { res = Math.max(res, up[i]); res = Math.max(res, down[i]); } return res; } } //352 class SummaryRanges { class Interval { int start; int end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; } } List<Interval> intervals; Map<Integer, Interval> starts; Map<Integer, Interval> ends; /** Initialize your data structure here. */ public SummaryRanges() { intervals = new ArrayList<>(); starts = new HashMap<>(); ends = new HashMap<>(); } public void addNum(int val) { Interval pre = ends.getOrDefault(val-1, null); Interval after = starts.getOrDefault(val+1, null); Interval replacement = null; if (pre != null && after != null) { intervals.remove(pre); intervals.remove(after); ends.remove(after.end); ends.remove(pre.end); starts.remove(pre.start); starts.remove(after.end); replacement = new Interval(pre.start, after.end); } else if (pre != null) { intervals.remove(pre); ends.remove(pre.end); starts.remove(pre.start); replacement = new Interval(pre.start, val); } else if (after != null) { intervals.remove(after); ends.remove(after.end); starts.remove(after.start); replacement = new Interval(val, after.end); } else if (ends.keySet().contains(val) || starts.keySet().contains(val)) { return; } else { replacement = new Interval(val, val); merge(getIntervals(), replacement); return; } intervals.add(replacement); ends.put(replacement.end, replacement); starts.put(replacement.start, replacement); } private void merge(List<Interval> intervals, Interval a) { for (int i = 0; i < intervals.size(); i++) { Interval tmp = intervals.get(i); if (tmp.start < a.start && a.end < tmp.end) { return; } } ends.put(a.end , a); starts.put(a.start, a); intervals.add(a); } public List<Interval> getIntervals() { Collections.sort(intervals, (Interval i1, Interval i2) -> i1.start - i2.start); return intervals; } } // 10/15/17 class SummaryRangesII { class Interval { int start; int end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; } } TreeMap<Integer, Interval> map; /** Initialize your data structure here. */ public SummaryRangesII() { map = new TreeMap<>(); } public void addNum(int val) { if (map.containsKey(val)) return; Integer lower = map.lowerKey(val); Integer higher = map.higherKey(val); if (lower != null && higher != null && map.get(lower).end + 1 == val && map.get(higher).start == val +1) { map.get(lower).end = map.get(higher).end; map.remove(higher); } else if (lower != null && map.get(lower).end + 1 >= val) { map.get(lower).end = Math.max(val, map.get(lower).end); } else if (higher != null && map.get(higher).start -1 == val) { map.put(val, new Interval(val, map.get(higher).end)); map.remove(higher); } else { map.put(val, new Interval(val, val)); } } public List<Interval> getIntervals() { return new ArrayList<>(map.values()); } } class Solution354 { public int maxEnvelopes(int[][] envelopes) { Comparator<int[]> cmp = new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { if (o1[0] == o2[0]) { return o1[1] - o2[1]; } return o1[0] - o2[0]; } }; Arrays.sort(envelopes, cmp); int m = envelopes.length; int[] dp = new int[m]; Arrays.fill(dp, 1); for (int i = 1; i< m; i++) { for (int j = i - 1; j >= 0; j--) { if (envelopes[i][0] > envelopes[j][0] && envelopes[i][1] > envelopes[j][1]) { dp[i] = Math.max(dp[i], dp[j]+1); } } } int res = 0; for (int i = 0; i< m; i++) { res = Math.max(res, dp[i]); } return res; } } class Solution375 { public int getMoneyAmount(int n) { int[][] dp = new int[n][n]; int res = get(dp, 0, n-1); return res; } private int get(int[][] dp, int i, int j) { if (i >= j) return 0; if (dp[i][j] != 0) return dp[i][j]; if (i == j-1) { dp[i][j] = i+1; return dp[i][j]; } if (i == j -2) { dp[i][j] = (i+1+ j+1)/2; return dp[i][j]; } int res = Integer.MAX_VALUE; for (int k = i; k <= j; k++) { res = Math.min(res, Math.max(get(dp, i, k-1),get(dp, k+1, j)) + k + 1); } dp[i][j] = res; return res; } } class Solution377 { public int combinationSum4(int[] nums, int target) { Map<Integer, Integer> dp = new HashMap<>(); List<Integer> tr = new ArrayList<>(); List<List<Integer>> res = new ArrayList<>(); dfs(nums, res, tr, 0, target); return res.size(); } private void dfs(int[] nums, List<List<Integer>> res, List<Integer> tr, int sum, int target) { if (sum > target) { return;} if (sum == target) { res.add(new ArrayList<>(tr)); return; } for (int i = 0; i< nums.length; i++) { tr.add(nums[i]); dfs(nums, res, tr, sum+nums[i], target); tr.remove(tr.size()-1); } } } class Solution377II { public int combinationSum4(int[] nums, int target) { int[] dp = new int[target+1]; Arrays.fill(dp, -1); dp[0] = 1; dfs(nums, dp, target); return dp[target-1]; } private int dfs(int[] nums, int[] dp, int target) { if (dp[target] != -1) { return dp[target]; } int res = 0; for (int i = 0; i< nums.length; i++) { if (target >= nums[i]) { res += dfs(nums, dp, target-nums[i]); } } dp[target] = res; return res; } } class Solution378 { public int kthSmallest(int[][] matrix, int k) { Comparator<int[]> cmp = new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[0] - o2[0]; } }; PriorityQueue<int[]> pq = new PriorityQueue<>(cmp); int m = matrix.length; if (m == 0) return 0; int n = matrix.length; if (n == 0) return 0; for (int i = 0; i< n; i++) { pq.add(new int[] {matrix[0][i], 0, i}); } for (int i = 0; i< k-1; i++) { int[] tmp = pq.poll(); if (tmp != null && tmp[1] < m-1) { pq.add(new int[] {matrix[tmp[1] + 1][tmp[2]], tmp[1]+1, tmp[2]}); } } return pq.peek()[0]; } } class Solution373 { public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) { PriorityQueue<int[]> pq = new PriorityQueue<>( (a,b) -> (a[0] + a[1]) - (b[0] + b[1])); List<int[]> res = new ArrayList<>(); if (nums1.length == 0 || nums2.length == 0 || k == 0) { return res; } for (int i = 0; i< nums1.length && i < k; i++) { pq.add(new int[] {nums1[i], nums2[0], 0}); } while(k-- > 0 && !pq.isEmpty()) { int[] tmp = pq.poll(); res.add(new int[] {tmp[0], tmp[1]}); if (tmp[2]+1 < nums2.length) { pq.add(new int[]{tmp[0], nums2[tmp[2] + 1], tmp[2] + 1}); } } return res; } } class RandomizedSet { // 380 Map<Integer, Integer> map; List<Integer> list; /** Initialize your data structure here. */ public RandomizedSet() { map = new HashMap<>(); list = new ArrayList<>(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { if (map.keySet().contains(val)) {return false;} list.add(val); map.put(val, list.size()-1); return true; } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { int index = map.getOrDefault(val, -1); if (index == -1) return false; if (index == list.size()-1) { map.remove(val); list.remove(list.size()-1); } else { list.set(index, list.get(list.size()-1)); map.put(list.get(index), index); list.remove(list.size()-1); } return true; } /** Get a random element from the set. */ public int getRandom() { int index = (int)(Math.random() * (list.size()-1)); return list.get(index); } } class Solution382 { class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } ListNode mhead; Random random; /** @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. */ public Solution382(ListNode head) { mhead = head; random = new Random(); } /** Returns a random node's value. */ public int getRandom() { int res = 0; ListNode tmp = mhead; int i = 0; while(tmp != null) { int ran = random.nextInt(i+1); if (i == ran) { res = tmp.val; } i++; tmp = tmp.next; } return res; } } class Solution383 { public boolean canConstruct(String ransomNote, String magazine) { Map<Character, Integer> mag = new HashMap<>(); Map<Character, Integer> note = new HashMap<>(); for (int i = 0; i< magazine.length(); i++) { mag.put(magazine.charAt(i), mag.getOrDefault(magazine.charAt(i), 0) + 1); } for (int i = 0; i < ransomNote.length(); i++) { note.put(ransomNote.charAt(i), note.getOrDefault(ransomNote.charAt(i), 0) + 1); } for (char c : note.keySet()) { if (note.getOrDefault(c, 0) > mag.getOrDefault(c, 0)){ return false; } } return true; } } // 10/16/17 class SolutionBFS301 { public List<String> removeInvalidParentheses(String s) { List<String> res = new ArrayList<>(); Set<String> set = new HashSet<>(); Queue<String> q = new LinkedList<>(); q.add(s); boolean found = false; while (!q.isEmpty()) { String tmp = q.poll(); if (isValid(tmp)) { res.add(tmp); found = true; continue; } if (found) continue; for (int i = 0; i < tmp.length(); i++) { if (tmp.charAt(i) != '(' && tmp.charAt(i) != ')') continue; String cur = tmp.substring(0, i) + tmp.substring(i+1, tmp.length()); if (set.contains(cur)) { continue;} q.add(cur); set.add(cur); } } return res; } private boolean isValid(String s) { int count = 0; for (int i = 0; i< s.length(); i++) { char c = s.charAt(i); if (c == '(') { count++; } else if (c == ')') { count --; if(count < 0) { return false; } } } return count == 0; } } class Solution384 { int[] tmp; int[] copy; public Solution384(int[] nums) { int m = nums.length; tmp = new int[m]; for (int i = 0; i< m; i++) { tmp[i] = nums[i]; } copy = nums; } /** Resets the array to its original configuration and return it. */ public int[] reset() { for (int i = 0; i< tmp.length; i++) { tmp[i] = copy[i]; } return copy; } /** Returns a random shuffling of the array. */ public int[] shuffle() { Random random = new Random(); for (int i = 0; i < tmp.length; i++) { int j = random.nextInt(i+1); int t = tmp[j]; tmp[j] = tmp[i]; tmp[i] = t; } return tmp; } } class Solution386 { public List<Integer> lexicalOrder(int n) { List<Integer> res = new ArrayList<>(); for (int i = 1; i<=9; i++) { DFS(res, i, n); } return res; } private void DFS(List<Integer> res, int i, int n) { if (i > n) { return;} res.add(i); for(int j = 0; j <10;j++) { DFS(res, i*10 + j, n); } } } class Solution387 { public int firstUniqChar(String s) { int[] map = new int[26]; Arrays.fill(map, -1); for (int i = 0; i< s.length(); i++) { if (map[s.charAt(i) - 'a'] == -1 && map[s.charAt(i) - 'a'] != Integer.MAX_VALUE) { map[s.charAt(i) - 'a'] = i; } else { map[s.charAt(i) - 'a'] = Integer.MAX_VALUE; } } int res = Integer.MAX_VALUE; for (int i = 0; i< map.length; i++) { if (map[i] != -1) { res = Math.min(res, map[i]); } } return res == Integer.MAX_VALUE ? -1 : res; } } class Solution389 { public char findTheDifference(String s, String t) { int[] maps = new int[26]; int[] mapt = new int[26]; for (int i = 0 ; i< s.length(); i++) { maps[s.charAt(i) - 'a']++; } for (int i = 0; i< t.length(); i++) { mapt[t.charAt(i) - 'a']++; } for (int i = 0 ;i< 26; i++) { if (mapt[i] - maps[i] == 1) { return (char)('a' + i); } } return 'a'; } } // 10/17/17 class Solution394 { public String decodeString(String s) { return dfs(s); } private String dfs(String s) { if (s.indexOf('[') == -1) { return s; } StringBuilder sb = new StringBuilder(); int pre = 0; int i = pre; while(i != s.length()) { int startIndex = s.indexOf('[', i); if (startIndex == -1) { sb.append(s.substring(pre, s.length())); break; } int l; for (l = pre; l < s.length(); l ++) { if (Character.isDigit(s.charAt(l))) { break; } } sb.append(s.substring(pre, l)); pre = l; int count = 1; i = startIndex + 1; int num = Integer.parseInt(s.substring(pre, startIndex)); while (i != s.length() && count != 0) { if (s.charAt(i) == '[') count++; else if (s.charAt(i) == ']') count--; i++; } String tmp = dfs(s.substring(startIndex+1, i-1)); for (int k = 0; k < num; k++) { sb.append(tmp); } pre = i; } return sb.toString(); } } class Solution394II { public String decodeString(String s) { return dfs(s, 0).tmp; } class Val { int index; String tmp; public Val(int a, String b) { index = a; tmp = b; } } private Val dfs(String s, Integer i) { StringBuilder sb = new StringBuilder(); int n = 0; while(i < s.length() && s.charAt(i) != ']') { if (!Character.isDigit(s.charAt(i))) { sb.append(s.charAt(i++)); } else if (Character.isDigit(s.charAt(i))) { n = 0; while(Character.isDigit(s.charAt(i))) { n = n * 10 + (s.charAt(i++) - '0'); } i++; Val val = dfs(s, i); String tmp = val.tmp; i = val.index; i++; while(n-- >0) { sb.append(tmp); } } } return new Val(i, sb.toString()); } } class Solution395 { public int longestSubstring(String s, int k) { if (s.length() < k) return 0; int[] freq = new int[26]; for(int i = 0; i< s.length(); i++) { freq[s.charAt(i)-'a'] ++; } int minFreq = Integer.MAX_VALUE; char c= 'a'; for (int i = 0; i< 26; i++) { if (freq[i] != 0 && freq[i] < minFreq) { minFreq = freq[i]; c = (char)('a'+ i); } } if (minFreq >= k) { return s.length();} int res = Integer.MIN_VALUE; String[] subs = s.split(String.valueOf(c)); for (int i = 0; i< subs.length; i++) { res = Math.max(res, longestSubstring(subs[i], k)); } return res; } } class Solution351 { boolean[] visied = new boolean[9]; public int numberOfPatterns(int m, int n) { int res = 0; for (int k = m ; k < n; k++) { Arrays.fill(visied, false); res += cal(-1, k); } return res; } public int cal(int from, int len) { if (len == 0) { return 1; } int sum = 0; for (int i = 0; i< 9; i++) { if (isValid(from, i)) { visied[i] = true; sum += cal(i, len-1); visied[i] = false; } } return sum; } private boolean isValid(int from, int to) { if (visied[to]) return false; if (from == -1) return true; if ((from+to)%2 == 1) return true; int mid = (from + to)/2; if (mid == 4) { return visied[mid]; } // not same line and same column. if (from % 3 != to % 3 && from / 3 != to / 3) { return true; } return visied[mid]; } } class Solution393 { public boolean validUtf8(int[] data) { int threeCount = 30; // 11110 int twoCount = 14; // 1110 int oneCount = 6; // 110; int nocount = 2; // 10 int zero = 0; int expect = 0; for(int i = 0; i< data.length; i++) { int tmp = data[i]; if (tmp >> 3 == threeCount) { if (expect != 0) { return false;} expect = 3; continue; } if (tmp >> 4 == twoCount) { if (expect != 0) { return false;} expect = 2; continue; } if (tmp >> 5 == oneCount) { if (expect != 0) { return false;} expect = 1; continue; } if (tmp >> 6 == nocount) { if (expect == 0) {return false;} expect--; continue; } if (tmp >> 7 == zero) { if (expect != 0) {return false;} continue; } return false; } return expect == 0; } } class Solution397 { public int integerReplacement(int n) { int steps = 0; while (n != 1) { if(n%2 == 0) { n = n / 2; } else if (n == 3 || ((n >>> 1) & 1) == 0) { // if n is end with 'xxxxxx01' we should just -1, other wise should +1 // to reduce the count of 1 in the n. n = n -1; } else { n = n + 1; } steps++; } return steps; } } class Solution399 { // this is actual a graph problem class edge { String key; double ratio; public edge(String a, double d) { key = a; ratio = d; } } public double[] calcEquation(String[][] equations, double[] values, String[][] queries) { int m = values.length; if (equations.length != m) { return new double[0];} Map<String, List<edge>> map = new HashMap<>(); for (int i = 0; i< m; i++) { edge p = new edge(equations[i][1], values[i]); List<edge> lp = map.getOrDefault(equations[i][0], new ArrayList<edge>()); lp.add(p); map.put(equations[i][0], lp); p = new edge(equations[i][0], 1.0 / values[i]); lp = map.getOrDefault(equations[i][1], new ArrayList<edge>()); lp.add(p); map.put(equations[i][1], lp); } int n = queries.length; double[] res = new double[n]; Set<String> visited = new HashSet<>(); for (int i = 0; i< n; i++) { visited.clear(); visited.add(queries[i][0]); res[i] = solve(map, visited, queries[i][0], queries[i][1]); visited.remove(queries[i][0]); } return res; } private double solve(Map<String, List<edge>> map, Set<String> visited, String a, String b) { if (map.keySet().contains(a) && a.equals(b)) return 1.0; List<edge> list = map.getOrDefault(a, null); if (list == null) {return -1.0d;} for (edge p : list) { if (p.key.equals(b)) { return p.ratio; } if (visited.contains(p.key)) { continue;} visited.add(p.key); double res = solve(map, visited, p.key, b); if (res != -1.0) { return p.ratio * res; } visited.remove(p.key); } return -1.0; } } // 10/18/17 class SnakeGame { class BoardPoint { int x, y; public BoardPoint(int a, int b) {x = a; y = b;} @Override public boolean equals(Object b) { if (b == this) {return true;} if (!(b instanceof BoardPoint)) {return false;} if(this.x == ((BoardPoint)b).x && this.y == ((BoardPoint)b).y) {return true;} return false; } } private LinkedList<BoardPoint> snakeBody; private Set<BoardPoint> foods; private int h; private int w; private int score = 0; /** Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */ public SnakeGame(int width, int height, int[][] food) { snakeBody = new LinkedList<>(); snakeBody.add(new BoardPoint(0,0)); h = height; w = width; foods = new HashSet<>(); for (int i = 0; i < food.length; i++) { foods.add(new BoardPoint(food[i][0], food[i][1])); } score = 0; } /** Moves the snake. @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down @return The game's score after the move. Return -1 if game over. Game over when snake crosses the screen boundary or bites its body. */ public int move(String direction) { BoardPoint head = snakeBody.getFirst(); BoardPoint nextPoint = null; if (direction.equals("U")) { nextPoint = new BoardPoint(head.x - 1, head.y); if (nextPoint.x < 0) return -1; } else if (direction.equals("L")) { nextPoint = new BoardPoint(head.x, head.y -1); if (nextPoint.y < 0) return -1; } else if (direction.equals("D")) { nextPoint = new BoardPoint(head.x+1, head.y); if (nextPoint.x >= h) return -1; } else if (direction.equals("R")) { nextPoint = new BoardPoint(head.x, head.y + 1); if (nextPoint.y >= w) return -1; } if (nextPoint == null) {return -1;} for (int i = 0; i< snakeBody.size()-1; i++) { BoardPoint p = snakeBody.get(i); if (nextPoint.x == p.x && nextPoint.y == p.y) { return -1; } } if (foods.contains(nextPoint)){ score ++; foods.remove(nextPoint); snakeBody.addFirst(nextPoint); } else { snakeBody.addFirst(nextPoint); snakeBody.removeLast(); } return score; } } class Solution385 { class NestedInteger { // Constructor initializes an empty nested list. public NestedInteger() {} // Constructor initializes a single integer. public NestedInteger(int value){} // @return true if this NestedInteger holds a single integer, rather than a nested list. public boolean isInteger(){return true;} // @return the single integer that this NestedInteger holds, if it holds a single integer // Return null if this NestedInteger holds a nested list public Integer getInteger() {return null;} // Set this NestedInteger to hold a single integer. public void setInteger(int value) {return;} // Set this NestedInteger to hold a nested list and adds a nested integer to it. public void add(NestedInteger ni) {} // @return the nested list that this NestedInteger holds, if it holds a nested list // Return null if this NestedInteger holds a single integer public List<NestedInteger> getList() {return null;} } public NestedInteger deserialize(String s) { if (s.isEmpty()) { return null; } if (s.charAt(0) != '[') { return new NestedInteger(Integer.valueOf(s)); } Stack<NestedInteger> stack = new Stack<>(); NestedInteger curr = null; int l = 0; int r = 0; while(r < s.length()) { char ch = s.charAt(r); if (ch == '[') { if (curr != null) { stack.push(curr); } curr = new NestedInteger(); l = r + 1; } else if (ch == ']') { String num = s.substring(l,r); if (!num.isEmpty()) { curr.add(new NestedInteger(Integer.valueOf(num))); } if (!stack.isEmpty()) { NestedInteger pop = stack.pop(); pop.add(curr); curr = pop; } l = r + 1; } else if (ch == ',') { if (s.charAt(r-1) != ']') { String num = s.substring(l, r); curr.add(new NestedInteger(Integer.valueOf(num))); } l = r + 1; } r++; } return curr; } } class Solution398 { int[] num; Random rand; public Solution398(int[] nums) { num = nums; rand = new Random(); } public int pick(int target) { int count= 0; int res = -1; for (int i = 0; i< num.length; i++) { if (num[i] == target) { count++; if (rand.nextInt(count) == 0) { res = i; } } } return res; } } class Solution402 { public String removeKdigits(String num, int k) { if (num.length() == 0) { return "0"; } Stack<Character> stack = new Stack<>(); int i = 0; while(i < num.length()) { while(k>0 && !stack.isEmpty() && stack.peek() > num.charAt(i)) { stack.pop(); k--; } stack.push(num.charAt(i)); i++; } while(k >0 && !stack.isEmpty()){ stack.pop(); k--; } StringBuilder sb = new StringBuilder(); while(!stack.isEmpty()) { sb.append(stack.pop()); } sb.reverse(); while(sb.charAt(0) == '0') { sb.deleteCharAt(0); } return sb.length() == 0 ? "0" : sb.toString(); } } class Solution403 { public boolean canCross(int[] stones) { int m = stones.length; if (m < 1) return true; Set<Integer>[] jumps = new Set[m]; for (int i = 0; i < m; i++) { jumps[i] = new HashSet<>(); } if (stones[1] == 1) { jumps[1].add(1); } for(int i = 1; i< m; i++) { Set<Integer> steps = jumps[i]; for (Integer h : steps) { for (int j = i+ 1; j< m; j++) { if ( (stones[j] - stones[i]) == h) { jumps[j].add(h); } else if ((stones[j] - stones[i]) == (h -1)) { jumps[j].add(h-1); } else if ((stones[j] - stones[i]) == (h+1)) { jumps[j].add(h+1); } } } } return jumps[m-1].size() > 0; } } class Solution404 { public int sumOfLeftLeaves(TreeNode root) { return rec(root, false); } private int rec(TreeNode root, boolean isLeft) { if (root == null) return 0; int leftVal = rec(root.left, true); int rightVal = rec(root.right, false); int rootVal = (root.left == null && root.right == null && isLeft) ? root.val : 0; return leftVal + rightVal + rootVal; } } class Solution405 { public String toHex(int num) { char[] map = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; if (num == 0) return "0"; StringBuilder sb = new StringBuilder(); while(num > 0) { sb.append(map[num & 15]); num = num >>> 4; } return sb.reverse().toString(); } } class Solution406 { public int[][] reconstructQueue(int[][] people) { TreeMap<Integer, List<Integer>> map = new TreeMap<>(); int m = people.length; for(int i = 0; i< m; i++) { int h = people[i][0]; int location = people[i][1]; List<Integer> locations = map.getOrDefault(h, new ArrayList<>()); locations.add(location); map.put(h, locations); } for (Integer key : map.keySet()) { List<Integer> locations = map.get(key); Collections.sort(locations); map.put(key, locations); } int[][] res = new int[m][]; boolean[] taken = new boolean[m]; int height = map.firstKey(); while(!map.isEmpty()) { List<Integer> locations = map.get(height); for (int i = 0; i< locations.size(); i++) { int l = locations.get(i); int index = findNthNoneTaken(taken, l-i); res[index] = new int[] {height, l}; taken[index] = true; } map.remove(height); if (map.isEmpty()) {break;} height = map.higherKey(height); } return res; } private int findNthNoneTaken(boolean[] taken, int n) { for(int i = 0; i< taken.length; i++) { if (n == 0) { while(taken[i]) { i++; } return i; } if (!taken[i]) {n--;} } return 0; } } // 10/19/17 class Solution407 { class Cell { int x, y, h; public Cell(int a, int b, int c) {x = a; y = b; h = c;} } public int trapRainWater(int[][] heightMap) { if (heightMap == null || heightMap.length == 0 || heightMap[0].length == 0) { return 0; } PriorityQueue<Cell> q = new PriorityQueue<>(new Comparator<Cell>() { @Override public int compare(Cell o1, Cell o2) { return o1.h - o2.h; } }); int m = heightMap.length; int n = heightMap[0].length; boolean[][] visited = new boolean[m][n]; // first and last row; for (int i = 0; i < m ; i++) { q.add(new Cell(i, 0, heightMap[i][0])); q.add(new Cell(i, n-1, heightMap[i][n-1])); visited[i][0] = true; visited[i][n-1] = true; } // first and last col for (int j = 1; j < n-1; j++) { q.add(new Cell(0, j, heightMap[0][j])); q.add(new Cell(m-1, j, heightMap[m-1][j])); visited[0][j] = true; visited[m-1][j] = true; } int[] xd = new int[] {0, 0, -1, 1}; int[] yd = new int[] {-1, 1, 0, 0}; int res = 0; while(!q.isEmpty()) { Cell cur = q.poll(); for (int i = 0; i < 4; i++) { int x = cur.x + xd[i]; int y = cur.y + yd[i]; if (x >=0 && x < m && y >=0 && y < n && !visited[x][y]) { res += Math.max(0, cur.h - heightMap[x][y]); visited[x][y] = true; q.add(new Cell(x, y, Math.max(cur.h, heightMap[x][y]))); } } } return res; } } class Solution408 { public boolean validWordAbbreviation(String word, String abbr) { int i = 0; int j = 0; while(i<word.length() && j < abbr.length()) { if (abbr.charAt(j) == '0') return false; if(Character.isDigit(abbr.charAt(j))) { int len = 0; while(j < abbr.length() && Character.isDigit(abbr.charAt(j))) { len = len * 10 + (abbr.charAt(j) - '0'); j++; } i += len; } if (i >= word.length() || j >= abbr.length()) {break;} if (word.charAt(i) != abbr.charAt(j)) {return false;} } return i == word.length() && j == abbr.length(); } } class Solution363 { public int maxSumSubmatrix(int[][] matrix, int k) { if (matrix.length == 0) return 0; int m = matrix.length; int n = matrix[0].length; int res = Integer.MIN_VALUE; for(int left = 0; left < n; left ++) { int[] sums = new int[m]; for (int right = left; right < n; right++) { for (int i = 0; i< m; i++) { sums[i] += matrix[i][right]; } } // TreeSet TreeSet<Integer> set = new TreeSet<>(); set.add(0); int currSum = 0; for (int sum: sums) { currSum += sum; Integer num = set.ceiling(currSum-k); if (num != null) {res = Math.max(res, currSum- num);} set.add(currSum); } } return res; } class Res { int start, end, sum; public Res(int a, int b, int c) {start = a; end = b; sum = c;} } private Res Kadane(int[] nums) { int m = nums.length; int maxSum = 0; int maxLeft = 0; int maxRight = 0; int j = 0; int sum = 0; int i = 0; while(j< m) { sum += nums[j]; if (sum > maxSum) { maxLeft = i; maxRight = j; maxSum = sum; } else if (sum < 0) { i = j +1; sum = 0; } j++; } if (maxSum > 0) { return new Res(maxLeft, maxRight, maxSum); } else { return null; } } } // 10/20/17 class Solution410 { public int splitArray(int[] nums, int m) { int max = 0; long sum = 0; for (int num : nums) { max = Math.max(num, max); sum += num; } if (m == 1) return (int)sum; //binary search long l = max; long r = sum; while (l <= r) { long mid = (l + r)/ 2; if (valid(nums, mid, m)) { r = mid - 1; } else { l = mid + 1; } } return (int)l; } public boolean valid(int[] nums, long target, int m) { int count = 1; long total = 0; for (int num : nums) { total += num; if (total > target) { total = num; count++; if (count > m) { return false; } } } return true; } } class Solution413 { public int numberOfArithmeticSlices(int[] A) { int diff = Integer.MAX_VALUE; int count = 0; int m = A.length; int res = 0; if (m < 3) return 0; for (int i = 1; i < m ; i++) { if (diff == Integer.MAX_VALUE) { count = 2; diff = A[i] - A[i-1]; } else if (A[i] - A[i-1] == diff) { count++; continue; } else { for (int j = 3; j <= count; j++) { res += (count - j + 1); } count = 2; diff = A[i] - A[i-1]; } } for (int j = 3; j <= count; j++) { res += (count - j + 1); } return res; } } class Solution414 { public int thirdMax(int[] nums) { if (nums.length == 0) return 0; long[] maxArray = new long[3]; Arrays.fill(maxArray, Long.MIN_VALUE); for (int i = 0; i < nums.length; i++) { if (nums[i] > maxArray[2]) { maxArray[0] = maxArray[1]; maxArray[1] = maxArray[2]; maxArray[2] = nums[i]; } else if (nums[i] > maxArray[1]) { if (nums[i] == maxArray[2]) continue; maxArray[0] = maxArray[1]; maxArray[1] = nums[i]; } else if (nums[i] > maxArray[0]) { if (nums[i] == maxArray[1]) continue; maxArray[0] = nums[i]; } } if (maxArray[0] != Long.MIN_VALUE) { return (int)maxArray[0]; } else { return (int)maxArray[2]; } } } class Solution415 { public String addStrings(String num1, String num2) { int carry = 0; List<Integer> res = new ArrayList<>(); int m = num1.length()-1; int n = num2.length()-1; while(m>=0 && n>=0) { int a = num1.charAt(m) - '0'; int b = num2.charAt(n) - '0'; res.add((a+b+carry)%10); carry = (a+b+carry)/10; m--; n--; } while(m>=0) { int a = num1.charAt(m) - '0'; res.add((a+carry)%10); carry = (a+carry) /10; m--; } while(n>=0) { int b = num2.charAt(n) - '0'; res.add((b+carry)%10); carry = (b+carry) /10; n--; } if (carry>0) { res.add(carry); } StringBuilder sb = new StringBuilder(); for (int i : res) { sb.append(String.valueOf(i)); } return sb.reverse().toString(); } } class Solution416 { public boolean canPartition(int[] nums) { int sum = 0; for(int i : nums) { sum += i; } if (sum%2 != 0) { return false; } return knapsack(nums, sum/2); } private boolean knapsack(int[]nums, int target) { int m = nums.length; int[][] dp = new int[m][target+1]; for (int i = 0; i < m; i++) { for (int j = 0; j<=target; j++) { if (j - nums[i] >=0) { dp [i][j] = Math.max( nums[i] + (((i-1) >=0 && target-nums[i]>=0) ? dp[i-1][j-nums[i]] : 0), (i-1) >= 0 ? dp[i-1][j] : 0); } else { dp[i][j] = (i > 0) ? dp[i-1][j] : 0; } } } return dp[m-1][target] == target; } } class Solution417 { public List<int[]> pacificAtlantic(int[][] matrix) { List<int[]> res = new ArrayList<>(); int m = matrix.length; if (m == 0) return res; int n = matrix[0].length; if (n == 0) return res; for(int i = 0; i< m; i++) { for (int j = 0; j<n; j++) { if (BFS(i,j, matrix)) { res.add(new int[]{i,j}); } } } return res; } public boolean BFS(int i, int j, int[][] matrix) { int m = matrix.length; int n = matrix[0].length; boolean[][] visited = new boolean[m][n]; Arrays.fill(visited, false); Queue<int[]> q = new LinkedList<>(); q.add(new int[]{i,j}); visited[i][j] = true; int[] xd = new int[]{0,0,-1,1}; int[] yd = new int[]{-1,1,0,0}; boolean touched[] = new boolean[4]; boolean touchedP =false; boolean touchedA = false; while(!q.isEmpty()) { int[] tmp = q.poll(); if(tmp[0] == 0) {touched[0] = true;} if(tmp[0] == m-1) {touched[1] = true;} if(tmp[1] == 0) {touched[2] = true;} if(tmp[1] == n-1) {touched[3] = true;} for(int k = 0; k < 4; k++) { int x = xd[k]+tmp[0]; int y = yd[k]+tmp[1]; if (x>=0 && x<m && y>=0 && y<n && matrix[x][y] <= matrix[tmp[0]][tmp[1]] && !visited[x][y]) { q.add(new int[]{x,y}); visited[x][y] = true; } } touchedP = touched[0] || touched[2] || touchedP; touchedA = touched[1] || touched[3] || touchedA; if (touchedP && touchedA) return true; } return false; } } // 10/21/17 class Solution418 { public int wordsTyping(String[] sentence, int rows, int cols) { int res = 0; int index = 0; int m = sentence.length; if (m == 0) return res; for (int i = 0 ; i< rows ; i++) { if (res != 0 && m == 0) { res = res * (m /i); return res; } int l = 0; boolean firstword = true; StringBuilder sb = new StringBuilder(); while ((l + sentence[index].length() + (firstword ? 0: 1)) <= cols) { sb.append(' '); sb.append(sentence[index]); l += sentence[index].length() + (firstword ? 0: 1); index++; firstword = false; if (index == m) { index = 0; res++; } } } return res; } } class Solution419 { public int countBattleships(char[][] board) { int m = board.length; if (m == 0) return 0; int n = board[0].length; int res = 0; for (int i = 0; i< m; i++) { for (int j = 0; j<n; j++) { if (board[i][j] == '.') continue; if (i-1>=0 && board[i-1][j] == 'X') continue; if (j-1>=0 && board[i][j-1] == 'X') continue; res ++; } } return res; } } class Solution422 { public boolean validWordSquare(List<String> words) { if (words.size() != words.get(0).length()) return false; for (int i = 0; i< words.size(); i++) { for (int j = 0; j < words.get(i).length(); j++) { if (j >= words.size()) return false; if (words.get(j).length() < i+1) {return false;} if (words.get(i).charAt(j) != words.get(j).charAt(i)){ return false; } } } return true; } } class Solution425 { public List<List<String>> wordSquares(String[] words) { List<List<String>> res = new ArrayList<>(); List<String> tmp = new ArrayList<>(); find(words, res, tmp); return res; } private void find(String[] words, List<List<String>> res, List<String> input) { if (input.size() > 0 && input.size() == input.get(0).length()) { if ( verify(input)) {res.add(new ArrayList<>(input));} return; } else { for (int i = 0; i < words.length; i++) { // if (!input.contains(words[i])) { input.add(words[i]); find(words, res, input); input.remove(input.size() - 1); // } } } } private boolean verify(List<String> words) { for (int i = 0; i< words.size(); i++) { for (int j = 0; j < words.get(i).length(); j++) { if (j >= words.size()) return false; if (words.get(j).length() < i+1) {return false;} if (words.get(i).charAt(j) != words.get(j).charAt(i)){ return false; } } } return true; } } class Solution424 { public int characterReplacement(String s, int k) { int l = 0; int maxCount = 0; int[] count = new int[26]; int res = 0; for (int i = 0; i< s.length(); i++) { maxCount = Math.max(maxCount, ++count[s.charAt(i) - 'A']); while(i - l - maxCount + 1 > k) { count[l]--; l++; } res = Math.max(i - l + 1, res); } return res; } } //10/22/17 class AllOne { class Bucket{ int val; Set<String> strSet; Bucket prev; Bucket next; public Bucket(int a) {val = a; strSet = new HashSet<>();} } private Map<String, Bucket> strMap; // private Map<Integer, Bucket> intMap; private Bucket minHead, maxHead; /** Initialize your data structure here. */ public AllOne() { minHead = new Bucket(-1); maxHead = new Bucket(-1); minHead.next = maxHead; maxHead.prev = minHead; } /** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */ public void inc(String key) { Bucket b = strMap.getOrDefault(key, null); if (b == null) { if (minHead.next.val != 1) { createdBucket(minHead, minHead.next, 1); } minHead.next.strSet.add(key); strMap.put(key, minHead.next); } else { int originalCount = b.val; if (b.next.val != originalCount+1) { createdBucket(b, b.next, originalCount+1); } b.strSet.remove(key); b.next.strSet.add(key); strMap.put(key, b.next); } } private Bucket createdBucket(Bucket prev, Bucket next, int newVal) { Bucket tmp = new Bucket(newVal); tmp.next = prev.next; tmp.prev = next.prev; prev.next = tmp; next.prev = tmp; return tmp; } private void removeBucket(Bucket b) { if (b == null) return; b.prev.next = b.next; b.next.prev = b.prev; } /** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */ public void dec(String key) { Bucket b = strMap.getOrDefault(key, null); if (b == null) {return;} // key was never exist int originalCount = b.val; if (originalCount == 1) { b.strSet.remove(key); strMap.remove(key); } if (b.prev.val != originalCount -1) { createdBucket(b.prev, b, originalCount-1); } b.strSet.remove(key); b.prev.strSet.add(key); strMap.put(key, b.prev); if (b.strSet.isEmpty()) { removeBucket(b); } } /** Returns one of the keys with maximal value. */ public String getMaxKey() { if (maxHead.prev.val == -1) return ""; return maxHead.prev.strSet.toArray()[0].toString(); } /** Returns one of the keys with Minimal value. */ public String getMinKey() { if (minHead.next.val == -1) return ""; return minHead.next.strSet.toArray()[0].toString(); } } class Solution433 { public int minMutation(String start, String end, String[] bank) { int m = bank.length; boolean[] visited = new boolean[m]; Queue<String> s = new LinkedList<>(); s.add(start); s.add(null); int steps = 0; while(!s.isEmpty()) { String tmp = s.poll(); if (tmp == null) { if (!s.isEmpty()) { s.add(null); } steps++; continue; } if (end.equals(tmp)) {return steps;} for (int i = 0; i< bank.length; i++) { if (!visited[i] && onDistance(tmp, bank[i])) { visited[i] = true; s.add(bank[i]); } } } return -1; } private boolean onDistance(String s1, String s2){ if (Math.abs(s1.length() - s2.length()) > 1) return false; int diff = 0; for (int i = 0; i< s1.length(); i++) { if (s1.charAt(i) != s2.charAt(i)) { diff ++; } if (diff > 1) return false; } return true; } } class Solution434 { public int countSegments(String s) { int k = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i-1) == ' ')) k++; } return k; } } class Solution435 { public int eraseOverlapIntervals( Solution252.Interval[] intervals) { int m = intervals.length; if (m < 1) return 0; Arrays.sort(intervals, new Comparator<Solution252.Interval>() { @Override public int compare(Solution252.Interval o1, Solution252.Interval o2) { return o1.end - o2.end; } }); int res = 0; Solution252.Interval end = intervals[0]; for (int i = 1; i < m; i++) { if (intervals[i].start < end.end) { res++; } else { end = intervals[i]; } } return res; } } class Solution436 { public int[] findRightInterval(Solution252.Interval[] intervals) { TreeMap<Solution252.Interval, Integer> map = new TreeMap<>( new Comparator<Solution252.Interval>() { @Override public int compare(Solution252.Interval o1, Solution252.Interval o2) { return o1.start - o2.start; } }); int m = intervals.length; int[] right = new int[m]; for (int i = 0; i<m; i++) { map.put(intervals[i], i); } for (int i = 0; i < m; i++) { Solution252.Interval rightKey = map.ceilingKey(intervals[i]); while(rightKey != null && rightKey.start < intervals[i].end) { rightKey = map.higherKey(rightKey); } if (rightKey != null) { right[i] = map.get(rightKey); } else { right[i] = -1; } } return right; } } class Solution437 { int totalCount = 0; public int pathSum(TreeNode root, int sum) { List<Integer> res = new ArrayList<>(); pathCount(res, root, sum); return totalCount; } private void pathCount(List<Integer> res, TreeNode root, int sum) { if (root == null) return; else { res.add( res.size() ==0 ? root.val : res.get(res.size()-1) + root.val); if (res.get(res.size()-1) == sum) totalCount++; for (int i = 0;i < res.size()-1; i++) { if (res.get(res.size()-1) - res.get(i) == sum) { totalCount ++; } } pathCount(res, root.left, sum); pathCount(res, root.right, sum); res.remove(res.size()-1); } } } class Solution438 { public List<Integer> findAnagrams(String s, String p) { List<Integer> res = new ArrayList<>(); int[] key = new int[26]; int[] window = new int[26]; for (int i = 0; i<p.length(); i++) { key[p.charAt(i)-'a']++; } int l = 0; int r = 0; while (r < s.length()) { while(r-l+1 <= p.length() && r < s.length()) { window[s.charAt(r) - 'a']++; r++; } if (sameAnagram(key, window)) { res.add(l); } window[s.charAt(l) - 'a']--; l++; } return res; } boolean sameAnagram(int[] a, int[] b) { for (int i = 0; i< 26; i++) { if (a[i] != b[i]) { return false; } } return true; } } class Solution439 { public String parseTernary(String expression) { if (expression == null || expression.length() == 0) return ""; Stack<Character> stack = new Stack<>(); int i = expression.length()-1; while(i>=0) { if (expression.charAt(i) == '?') { char a = stack.pop(); char b = stack.pop(); if (expression.charAt(i-1) == 'T') { stack.push(a); } else { stack.push(b); } i --; } else if (expression.charAt(i) != ':') { stack.push(expression.charAt(i)); } i --; } return stack.pop().toString(); } } class Solution441 { public int arrangeCoins(int n) { int i = 0; while(n-i >=0) { n = n -i; i++; } return i-1; } } class Solution445 { public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public ListNode addTwoNumbers(ListNode l1, ListNode l2) { Stack<Integer> l1Stack = new Stack<>(); Stack<Integer> l2Stack = new Stack<>(); while(l1 != null) { l1Stack.push(l1.val); l1 = l1.next; } while(l2 != null) { l2Stack.push(l2.val); l2 = l2.next; } ListNode tmp = null; int carry = 0; while(!l1Stack.isEmpty() && !l2Stack.isEmpty()) { int a = l1Stack.pop(); int b = l2Stack.pop(); int val = (a+b+carry)%10; carry = (a+b+carry)/10; ListNode cur = new ListNode(val); cur.next = tmp; tmp = cur; } if (!l2Stack.isEmpty()) { l1Stack = l2Stack; } while(!l1Stack.isEmpty()) { int a = l1Stack.pop(); int val = (a + carry) % 10; carry = (a + carry) / 10; ListNode cur = new ListNode(val); cur.next = tmp; tmp = cur; } if (carry != 0) { ListNode cur = new ListNode(carry); cur.next = tmp; tmp = cur; } return tmp; } } class Solution446 { public int numberOfArithmeticSlices(int[] A) { int diff = Integer.MAX_VALUE; int count = 0; int m = A.length; int res = 0; if (m < 3) return 0; for (int i = 1; i < m ; i++) { if (diff == Integer.MAX_VALUE) { count = 2; diff = A[i] - A[i-1]; } else if (A[i] - A[i-1] == diff) { count++; continue; } else { for (int k = 3; k <=count; k = k+2) { for (int j = k; j <= count; j++) { res += (count - j + 1); } } count = 2; diff = A[i] - A[i-1]; } } for (int k = 3; k <=count; k = k+2) { for (int j = k; j <= count; j++) { res += (count - j + 1); } } return res; } } class Solution447 { public int numberOfBoomerangs(int[][] points) { int m = points.length; if (m < 3) return 0; Map<Integer, Integer> map = new HashMap<>(); int res = 0; for(int i = 0; i < m; i++) { map.clear(); for (int j = 0; j < m; j++) { if (i == j) continue; int dist = findDistance(points[i], points[j]); int count = map.getOrDefault(dist, 0) + 1; map.put(dist, count); } for (int val : map.values()) { res += (val * (val -1)); } } return res; } private int findDistance(int[] a, int[] b) { int xd = a[0] - b[0]; int yd = a[1] - b[1]; return xd*xd + yd*yd; } } // 10/23/17 class Solution448 { public List<Integer> findDisappearedNumbers(int[] nums) { for(int i = 0; i< nums.length; i++) { if (nums[nums[i]-1] > 0 ) { nums[nums[i] -1] = -nums[nums[i] -1]; } } List<Integer> res = new ArrayList<>(); for(int i = 0; i< nums.length; i++) { if (nums[i] > 0) { res.add(i+1); } } return res; } } class Codec449 { // Encodes a tree to a single string. public String serialize(TreeNode root) { StringBuilder sb = new StringBuilder(); serializeRec(root, sb); sb.deleteCharAt(sb.length()-1); return sb.toString(); } private void serializeRec(TreeNode root, StringBuilder sb) { if (root == null) {sb.append('#'); sb.append(','); return;} sb.append(String.valueOf(root.val)); sb.append(","); serializeRec(root.left, sb); serializeRec(root.right, sb); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { Queue<String> d = new LinkedList<>(Arrays.asList(data.split(","))); return create(d); } private TreeNode create(Queue<String> d) { String s = d.poll(); if (s.equals("#")) return null; TreeNode root = new TreeNode(Integer.parseInt(s)); root.left = create(d); root.right = create(d); return root; } } class Solution450 { public TreeNode deleteNode(TreeNode root, int key) { if (root == null) return null; if (key < root.val) { root.left = deleteNode(root.left, key); } else if (key > root.val) { root.right = deleteNode(root.right, key); } else { if (root.left == null) {return root.right;} if (root.right == null) {return root.left;} TreeNode min = findMin(root.right); root.val = min.val; root.right = deleteNode(root.right, root.val); } return root; } private TreeNode findMin(TreeNode root) { while(root.left != null) { root = root.left; } return root; } } class Solution451 { public String frequencySort(String s) { Map<Character, Integer> map = new HashMap<>(); for (int i = 0; i < s.length(); i++) { map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1); } TreeMap<Integer, List<Character>> reverseMap = new TreeMap<>(); for(Character c : map.keySet()) { List<Character> list = reverseMap.getOrDefault(map.get(c), new ArrayList<>()); list.add(c); reverseMap.put(map.get(c), list); } Integer largest = reverseMap.lastKey(); StringBuilder sb = new StringBuilder(); while(largest != null) { List<Character> list = reverseMap.get(largest); for(Character c: list) { for (int i = 0; i< largest; i++) { sb.append(c); } } largest = reverseMap.lowerKey(largest); } return sb.toString(); } } // 10/24/17 class Solution452 { public int findMinArrowShots(int[][] points) { int m = points.length; if (m == 0) return 0; Comparator<int[]> cmp = new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[1] - o2[1]; } }; Arrays.sort(points, cmp); int res = 0; int i = 0; while (i<m) { res ++; int j = i+1; while(j < m && points[j][0] < points[i][1]) { j++; } i = j; } return res; } } class Solution453 { public int minMoves(int[] nums) { int m = nums.length; if (m == 0) return 0; int minVal = nums[0]; for (int i = 1; i < m; i++) { minVal = Math.min(minVal, nums[i]); } int res = 0; for (int i = 0; i < m; i++) { res += (nums[i] - minVal); } return res; } } class Solution454 { public int fourSumCount(int[] A, int[] B, int[] C, int[] D) { Map<Integer, Integer> map = new HashMap<>(); int m = C.length; for (int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { int sum = C[i] + D[j]; map.put(sum, map.getOrDefault(sum, 0) + 1); } } int res = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < m; j++) { int sum = A[i] + B[j]; res += map.getOrDefault(-sum, 0); } } return res; } } class Solution455 { public int findContentChildren(int[] g, int[] s) { Arrays.sort(g); Arrays.sort(s); int i = s.length - 1; int j = g.length - 1; while(i > 0 && j > 0) { if (s[i] >= g[j]) { i--; j--; } else { j++; } } return i; } } class Solution458 { public int poorPigs(int buckets, int minutesToDie, int minutesToTest) { int res = 0; int base = minutesToTest/minutesToDie + 1; while(Math.pow(base, res) < buckets) { res++; } return res; } } class Solution459 { public boolean repeatedSubstringPattern(String s) { int l = s.length(); for (l = s.length()/2; l >0; l--) { int tmp = 0; boolean found = true; while((tmp + l) <= s.length()) { if (!s.substring(0, l).equals(s.substring(tmp, tmp+l))) { found = false; break; } tmp+=l; } if (found && tmp == s.length()) return true; } return false; } } class Solution461 { public int hammingDistance(int x, int y) { int res = 0; int xor = x^y; for (int i = 0; i< 32; i++) { if(((xor>>i) & 1) == 1) { res++; } } return res; } } // 10/26/17 class Solution462 { public int minMoves2(int[] nums) { Arrays.sort(nums); int i = 0, j = nums.length-1; int res = 0; while(i<j) { res = nums[j--] - nums[i++]; } return res; } } class Solution463 { public int islandPerimeter(int[][] grid) { int m = grid.length; if (m == 0) return 0; int n = grid[0].length; int[] xd = new int[]{0, 0, -1, 1}; int[] yd = new int[]{-1,1, 0, 0}; int res = 0; for (int i = 0; i< m ;i ++) { for (int j = 0; j< n; j++) { if (grid[i][j] == 0) {continue;} for (int l = 0; l < 4; l++) { if ((i + xd[l]) < m && (i+ xd[l]) >=0 && (j + yd[l]) < n && (j + yd[l]) >=0) { if (grid[i+xd[l]][j+yd[l]] == 0) { res++; } } else { res ++; } } } } return res; } } // 10/271/7 class Solution464 { Map<Integer, Boolean> map; public boolean canIWin(int maxChoosableInteger, int desiredTotal) { int total = (maxChoosableInteger + 1) * maxChoosableInteger /2; if (total < desiredTotal) return false; boolean[] picked = new boolean[maxChoosableInteger+1]; map = new HashMap<>(); return dfs(picked, desiredTotal); } public boolean dfs(boolean[] picked, int desiredTotal) { if (desiredTotal <=0) return false; int key = convert(picked); if (!map.containsKey(key)) { for (int i = 1; i < picked.length; i++) { if (picked[i]) continue; picked[i] = true; if (!dfs(picked, desiredTotal - i)) { map.put(key, true); picked[i] = false; return true; } picked[i] = false; } map.put(key, false); } return map.get(key); } private int convert (boolean[] picked) { if (picked.length > 32) return 0; int res = 0; for (int i = 0; i< picked.length; i++) { res <<=1; if(picked[i]) res |= 1; } return res; } } //10/28/17 class Solution468 { public String validIPAddress(String IP) { if (IP.indexOf('.') > 0) { return checkIP4(IP) ? "IPv4" : "Neither"; } else if (IP.indexOf(':') > 0) { return checkIP6(IP) ? "IPv6" : "Neither"; } else { return "Neither"; } } boolean checkIP4(String s) { String[] tokens = s.split("\\."); if (tokens.length != 4) return false; if (s.startsWith(".") || s.endsWith(".")) return false; for (int i = 0 ; i< 4; i++) { try { int k = Integer.parseInt(tokens[i]); if (k < 0 || k >=256) return false; if (k == 0 && tokens[i].length() >1) return false; if (k > 0 && tokens[i].startsWith("0")) return false; if (tokens[i].startsWith("+") || tokens[i].startsWith("-")) { return false; } } catch (NumberFormatException ex) { return false; } } return true; } boolean checkIP6(String s) { String[] tokens = s.split(":"); if (tokens.length != 8) return false; if (s.startsWith(":") || s.endsWith(":")) return false; for (int i = 0; i < 8; i++) { if (tokens[i].length() > 4) return false; try { int k = Integer.parseInt(tokens[i], 16); if (tokens[i].startsWith("+") || tokens[i].startsWith("-")) { return false; } } catch(NumberFormatException ex) { return false; } } return true; } } class Solution469 { public boolean isConvex(List<List<Integer>> points) { boolean negative = false; boolean postive = false; for (int i = 0; i < points.size(); i++) { List<Integer> a = points.get(i); List<Integer> b = points.get((i+1)%points.size()); List<Integer> c = points.get((i+2)%points.size()); int crossProduct = crossProduct( a.get(0), a.get(1), b.get(0), b.get(1), c.get(0), c.get(1) ); if (crossProduct < 0) {negative = true;} if (crossProduct > 0) {postive = true;} if (negative & postive) return false; } return true; } private int crossProduct(int Ax, int Ay, int Bx, int By, int Cx, int Cy) { int ABx = Ax - Bx; int ABy = Ay - By; int CBx = Cx - Bx; int CBy = Cy - By; return ABx * CBy - CBx * ABy; } } class Solution471 { public boolean makesquare(int[] nums) { int sum = 0; for (int i : nums) { sum += i; } if (sum%4 != 0) return false; int[] seperator = new int[3]; Arrays.fill(seperator, -1); boolean[] selected = new boolean[nums.length]; return dfs(nums, selected, 0, 0, sum/4); } private boolean dfs(int[] nums, boolean[] selected, int count, int sum, int target) { if (sum > target) return false; if (sum == target) { if (count == 2) { return true; } else { count++; sum = 0; } } for (int i = 0; i < nums.length; i++) { if (selected[i]) continue;; selected[i] = true; if (dfs(nums, selected, count, sum+nums[i], target)) { selected[i] = false; return true; } selected[i] = false; } return false; } } class Solution474 { public int findMaxForm(String[] strs, int m, int n) { int k = strs.length; int[][] tracker = new int[k][]; for (int i = 0; i< k; i++) { tracker[i] = countBits(strs[i]); } boolean[] picked = new boolean[k]; return dfs(tracker, picked, m, n, 0); } private int dfs(int[][] tracker, boolean[] picked, int m, int n, int total) { if (total == picked.length && m >=0 && n >=0) return total; if (m < 0 || n < 0) { return total - 1; } int res = 0; for (int i = 0 ;i < tracker.length; i++) { if (picked[i]) {continue;} picked[i] = true; res = Math.max(res, dfs(tracker, picked, m - tracker[i][0], n - tracker[i][1], total + 1)); picked[i] = false; } return res; } private int[] countBits(String s) { int[] res = new int[2]; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '0') { res[0]++; } else { res[1]++; } } return res; } } class Solution474I { public int findMaxForm(String[] strs, int m, int n) { int[][] dp = new int[m+1][n+1]; int k = strs.length; int[][] tracker = new int[k][]; for (int i = 0; i< k; i++) { tracker[i] = countBits(strs[i]); } for (int l = 0; l < k; l++) { for(int i = m; i >= tracker[l][0]; i--) { for (int j = n; j >= tracker[l][1]; j--) { dp[i][j] = Math.max(dp[i][j], dp[i- tracker[l][0]][ j -tracker[l][1]] + 1); } } } return dp[m][n]; } private int[] countBits(String s) { int[] res = new int[2]; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '0') { res[0]++; } else { res[1]++; } } return res; } } class Solution475 { public int findRadius(int[] houses, int[] heaters) { int radius = 0; int hindex = 0; if (houses.length == 0) return 0; if (heaters.length == 0) return 0; Arrays.sort(houses); Arrays.sort(heaters); for (int i = 0; i< houses.length; i++) { if (hindex + 1 < heaters.length) { while(hindex +1 < heaters.length && Math.abs(houses[i] - heaters[hindex]) > Math.abs(houses[i] - heaters[hindex+1])) { hindex = hindex + 1; } } radius = Math.max(radius, Math.abs(houses[i] - heaters[hindex])); } return radius; } } class Solution476 { public int findComplement(int num) { boolean[] b = new boolean[32]; for (int i = 0; i < 32; i++) { b[i] = (num & 1) == 1 ? true : false; num >>= 1; } boolean start = false; int res = 0; for (int i = 31; i >=0; i--) { if (!start && !b[i]) continue; res <<= 1; start = true; if (!b[i]) { res |= 1;} } return res; } } class Solution477 { public int totalHammingDistance(int[] nums) { int n = nums.length; int[] t = new int[32]; for (int i = 0; i < nums.length; i++) { for (int j = 0; j < 32; j++) { if ((nums[i] & 1) == 1) { t[j]++; } nums[i] >>= 1; } } int res = 0; for (int j = 0; j < 32; j++) { res += (n-t[j]) * t[j]; } return res; } } class Solution482 { public String licenseKeyFormatting(String S, int K) { StringBuilder sb = new StringBuilder(); for(int i = 0; i< S.length(); i++) { if (S.charAt(i) != '-') { sb.append(Character.toUpperCase(S.charAt(i))); } } int i = sb.length(); StringBuilder res = new StringBuilder(); while(i-K >=0) { res.insert(0, sb.substring(i-K, i)); res.insert(0, "-"); i = i - K; } res.insert(0,sb.subSequence(0,i)); return res.toString(); } } class Solution484 { public int[] findPermutation(String s) { int[] res = new int[s.length()+1]; for (int i = 0; i< res.length; i++) { res[i] = i+1; } for (int r = 0; r < s.length(); r++) { if (s.charAt(r) == 'D') { int l = r; while (r < s.length() && s.charAt(r) == 'D') { r++; } reverse(res, l, r); } } return res; } private void reverse(int[] arr, int l, int r) { while (l < r) { int tmp = arr[r]; arr[r] = arr[l]; arr[l] = tmp; l++; r--; } } } class Solution485 { public int findMaxConsecutiveOnes(int[] nums) { int res = 0; int count = 0; for (int i = 0; i< nums.length; i++) { if (nums[i] == 1) { count++; res = Math.max(res, count); } else { count=0; } } return res; } } class Solution486 { public boolean PredictTheWinner(int[] nums) { return dfs(nums, 0, nums.length-1, 0, 0, true); } private boolean dfs(int[] nums, int l, int r, int score1, int score2, boolean start1) { if (l > r) {return score1 > score2;} if (start1) { if (dfs(nums, l+1, r, score1+nums[l], score2, false) || dfs(nums, l, r-1, score1+nums[r], score2, false)) { return true; } } else { if (dfs(nums, l+1, r, score1, score2+nums[l], true) && dfs(nums, l, r-1, score1, score2+ nums[r], true)) { return true; } } return false; } } // 10/29/17 class Solution487 { class Interval { int start; int end; Interval() { start = 0; end = 0; } Interval(int s, int e) { start = s; end = e; } } public int findMaxConsecutiveOnes(int[] nums) { List<Interval> intervals = new ArrayList<>(); int l = -1; for (int i = 0; i< nums.length; i++) { if (nums[i] == 1 && l == -1) {l = i; continue;} if (nums[i] == 0 && l != -1) { Interval tmp = new Interval(l, i-1); intervals.add(tmp); l = -1; } } if (l != -1) { intervals.add(new Interval(l, nums.length -1)); } int res = 0; for (int i = 0; i< intervals.size(); i++) { res = Math.max(res, (intervals.get(i).end - intervals.get(i).start + 2)); if ((i + 1) < intervals.size()) { if (intervals.get(i+1).start - intervals.get(i).end == 2) { int l1 = intervals.get(i).end - intervals.get(i).start + 1; int l2 = intervals.get(i+1).end - intervals.get(i+1).start + 1; res = Math.max(res, l1 + l2 + 1); } } } return res; } } class Solution487I { public int findMaxConsecutiveOnes(int[] nums) { int res = 0; int zero = 0; for (int l = 0, r = 0; r < nums.length; r++) { if (nums[r] == 0) {zero++;} while(zero > 1) { if (nums[l++] == 0) { zero--; } } res = Math.max(res, r -l +1); } return res; } } class Solution490 { class Point{ int x, y; public Point(int a, int b) {x = a; y = b;} @Override public boolean equals(Object o) { if (!(o instanceof Point)) {return false;} return x == ((Point)o).x && y == ((Point)o).y; } } public boolean hasPath(int[][] maze, int[] start, int[] destination) { int m = maze.length; int n = maze[0].length; boolean[][] visited = new boolean[m][n]; return findPath(maze, visited, new Point(start[0] , start[1]), destination); } private boolean findPath(int[][] maze, boolean[][] visited, Point cur, int[] destination) { Point up = moveUp(maze, cur); if (!visited[up.x][up.y]) { visited[up.x][up.y] = true; if (up.x == destination[0] && up.y == destination[1]) return true; else { if (findPath(maze, visited, up, destination)) return true; } } Point left = moveLeft(maze, cur); if (!visited[left.x][left.y]) { visited[left.x][left.y] = true; if (left.x == destination[0] && left.y == destination[1]) return true; else { if (findPath(maze, visited, left, destination)) return true; } } Point down = moveDown(maze, cur); if (!visited[down.x][down.y]) { visited[down.x][down.y] = true; if (down.x == destination[0] && down.y == destination[1]) return true; else { if (findPath(maze, visited, down, destination)) return true; } } Point right = moveRight(maze, cur); if (!visited[right.x][right.y]) { visited[right.x][right.y] = true; if (right.x == destination[0] && right.y == destination[1]) return true; else { if (findPath(maze, visited, right, destination)) return true; } } return false; } private Point moveUp(int[][] maze, Point cur) { int tmp = cur.x; while(tmp-1 >= 0 && maze[tmp-1][cur.y] == 0) { tmp--; } return new Point(tmp, cur.y); } private Point moveDown(int[][] maze, Point cur) { int x = cur.x; while((x+1) <maze.length && maze[x+1][cur.y] == 0) { x++; } return new Point(x, cur.y); } private Point moveLeft(int[][] maze, Point cur) { int y = cur.y; while(y-1 >= 0 && maze[cur.x][y-1] == 0) { y--; } return new Point(cur.x, y); } private Point moveRight(int[][] maze, Point cur) { int y = cur.y; while(y+1<maze[0].length && maze[cur.x][y+1] == 0) { y++; } return new Point(cur.x, y); } } class Solution491 { public List<List<Integer>> findSubsequences(int[] nums) { int m = nums.length; Set<List<Integer>> res = new HashSet<>(); for (int i = 0; i < m; i++) { List<Integer> tmp = new ArrayList<>(); tmp.add(nums[i]); dfs(nums, i, tmp, res); } return new ArrayList<>(res); } private void dfs(int[] nums, int index, List<Integer> track, Set<List<Integer>> res) { if (track.size() > 1 && !res.contains(track)) { res.add(new ArrayList<>(track)); } for (int i = index + 1; i < nums.length; i++) { if (nums[i] >= track.get(track.size()-1)) { track.add(nums[i]); dfs(nums, i, track, res); track.remove(track.size()-1); } } } } class Solution492 { public int[] constructRectangle(int area) { int root = (int)Math.sqrt(area); while(root > 1) { if (area % root == 0) { return new int[] {area/root, root}; } root--; } return new int[]{area, 1}; } } class Solution494 { public int findTargetSumWays(int[] nums, int S) { return dfs(nums, 0, S, 0); } private int dfs(int[] nums, int index, int target, int sum) { if (index >= nums.length){ if (sum == target) { return 1;} else {return 0;} } int plusCount = dfs(nums, index+1, target, sum+nums[index]); int minusCount = dfs(nums, index+1, target, sum-nums[index]); return plusCount + minusCount; } } class Solution496 { public int[] nextGreaterElement(int[] nums1, int[] nums2) { Map<Integer, Integer> map = new HashMap<>(); Stack<Integer> s = new Stack<>(); for (int i = 0; i< nums2.length; i++) { while (!s.isEmpty() && nums2[i] > s.peek()) { map.put(s.pop(), nums2[i]); } s.push(nums2[i]); } int[] res = new int[nums1.length]; for (int i = 0; i < nums1.length; i++) { res[i] = map.getOrDefault(nums1[i], -1); } return res; } } class Solution497 { public int[] findDiagonalOrder(int[][] matrix) { int direction = 1; int i = 0, j = 0; int m = matrix.length; if (m == 0) {return new int[0];} int n = matrix[0].length; List<Integer> res = new ArrayList<>(); while(i != m && j != n) { res.add(matrix[i][j]); if (direction == 1 && (i == 0 || j == n-1)){ direction = -1; if (j + 1 < n) {j++;} else {i++;} continue; } if (direction == -1 && (j == 0 || i == m -1)) { direction = 1; if (i+1 < m) {i ++;} else {j++;} continue; } i = i - direction; j = j + direction; } int[] arr = new int[m*n]; for(int k = 0; k< m*n; k++) { arr[k] = res.get(k); } return arr; } } class Solution499 { // this question need dijkstry method. // 1, build a graphy of which point can go to which point and weight of the edge // 2. class Point implements Comparable<Point> { int x,y,l; String s; public Point(int _x, int _y) {x=_x;y=_y;l=Integer.MAX_VALUE;s="";} public Point(int _x, int _y, int _l,String _s) {x=_x;y=_y;l=_l;s=_s;} public int compareTo(Point p) {return l==p.l?s.compareTo(p.s):l-p.l;} } public String findShortestWay(int[][] maze, int[] ball, int[] hole) { int m=maze.length, n=maze[0].length; Point[][] points=new Point[m][n]; for (int i=0;i<m*n;i++) points[i/n][i%n]=new Point(i/n, i%n); int[][] dir=new int[][] {{-1,0},{0,1},{1,0},{0,-1}}; String[] ds=new String[] {"u","r","d","l"}; PriorityQueue<Point> list=new PriorityQueue<>(); // using priority queue list.offer(new Point(ball[0], ball[1], 0, "")); while (!list.isEmpty()) { Point p=list.poll(); if (points[p.x][p.y].compareTo(p)<=0) continue; // if we have already found a route shorter points[p.x][p.y]=p; for (int i=0;i<4;i++) { int xx=p.x, yy=p.y, l=p.l; while (xx>=0 && xx<m && yy>=0 && yy<n && maze[xx][yy]==0 && (xx!=hole[0] || yy!=hole[1])) { xx+=dir[i][0]; yy+=dir[i][1]; l++; } if (xx!=hole[0] || yy!=hole[1]) { // check the hole xx-=dir[i][0]; yy-=dir[i][1]; l--; } list.offer(new Point(xx, yy, l, p.s+ds[i])); } } return points[hole[0]][hole[1]].l==Integer.MAX_VALUE?"impossible":points[hole[0]][hole[1]].s; } } class Solution500 { public String[] findWords(String[] words) { Map<Character, Integer> map = new HashMap<>(); map.put('a', 1); map.put('b', 2); map.put('c', 2); map.put('d', 1); map.put('e', 0); map.put('f', 1); map.put('g', 1); map.put('h', 1); map.put('i', 0); map.put('j', 1); map.put('k', 1); map.put('l', 1); map.put('m', 2); map.put('n', 2); map.put('o', 0); map.put('p', 0); map.put('q', 0); map.put('r', 0); map.put('s', 1); map.put('t', 0); map.put('u', 0); map.put('v', 2); map.put('w', 0); map.put('x', 2); map.put('y', 0); map.put('z', 2); List<String> res = new ArrayList<>(); for (int i = 0; i< words.length; i++) { int row = map.get(Character.toLowerCase(words[i].charAt(0))); boolean add = true; for (int k = 1; k < words[i].length(); k++) { if (map.get(Character.toLowerCase(words[i].charAt(k))) != row) { add = false; break; } } if (add) { res.add(words[i]); } } String[] arr = new String[res.size()]; for (int i = 0; i< res.size(); i++) { arr[i] = res.get(i); } return arr; } } // 10/30/17 class Solution501 { public int[] findMode(TreeNode root) { Map<Integer, Integer> map = new HashMap<>(); dfs(root, map); List<Integer> list = new ArrayList<>(); int maxCount = 0; for(Integer i : map.keySet()) { if (map.get(i) == maxCount) { list.add(i); } else if (map.get(i) > maxCount) { list.clear(); list.add(i); maxCount = map.get(i); } } int m = list.size(); int[] arr = new int[m]; for (int i = 0;i < m; i++) { arr[i] = list.get(i); } return arr; } private void dfs(TreeNode root, Map<Integer, Integer> map) { if (root == null) {return;} dfs(root.left, map); dfs(root.right, map); map.put(root.val, map.getOrDefault(root.val, 0)+1); } } class Solution502 { class Project{ int capital, profit; public Project(int a, int b) {capital = a; profit = b;} } public int findMaximizedCapital(int k, int W, int[] Profits, int[] Capital) { PriorityQueue<Project> capQueue = new PriorityQueue<>( (Project a, Project b) -> (a.capital - b.capital)); PriorityQueue<Project> proQueue = new PriorityQueue<>( (Project a, Project b) -> -(a.profit - b.profit)); int m = Profits.length; for (int i = 0; i< m; i++) { capQueue.add(new Project(Capital[i], Profits[i])); } for (int i = 0; i< k; i++) { while(!capQueue.isEmpty() && W >= capQueue.peek().capital) { proQueue.add(capQueue.poll()); } if (proQueue.isEmpty()) { break;} W += proQueue.peek().profit; proQueue.poll(); } return W; } } class Solution503 { public int[] nextGreaterElements(int[] nums) { int n = nums.length; int[] res = new int[n]; Arrays.fill(res, -1); Stack<Integer> s = new Stack<>(); for (int i = 0; i< n*2; i++) { while (!s.isEmpty() && nums[i % n] > nums[s.peek()]) { if (s.peek() >=n) { break;} res[s.pop()] = nums[i%n]; } s.push(i%n); } return res; } } class Solution504 { public String convertToBase7(int num) { if (num == 0) return "0"; boolean isNegative = num < 0; num = Math.abs(num); StringBuilder sb = new StringBuilder(); while(num >0) { sb.append(String.valueOf(num%7)); num = num/7; } if (isNegative) { sb.append("-"); } return sb.reverse().toString(); } } class Solution505 { class Point { int x,y,l; public Point(int _x, int _y, int _l) {x=_x;y=_y;l=_l;} } public int shortestDistance(int[][] maze, int[] start, int[] destination) { int m=maze.length, n=maze[0].length; int[][] length=new int[m][n]; // record length for (int i=0;i<m*n;i++) length[i/n][i%n]=Integer.MAX_VALUE; int[][] dir=new int[][] {{-1,0},{0,1},{1,0},{0,-1}}; PriorityQueue<Point> list=new PriorityQueue<>((o1,o2)->o1.l-o2.l); // using priority queue list.offer(new Point(start[0], start[1], 0)); while (!list.isEmpty()) { Point p=list.poll(); if (length[p.x][p.y]<=p.l) continue; // if we have already found a route shorter length[p.x][p.y]=p.l; for (int i=0;i<4;i++) { int xx=p.x, yy=p.y, l=p.l; while (xx>=0 && xx<m && yy>=0 && yy<n && maze[xx][yy]==0) { xx+=dir[i][0]; yy+=dir[i][1]; l++; } xx-=dir[i][0]; yy-=dir[i][1]; l--; list.offer(new Point(xx, yy, l)); } } return length[destination[0]][destination[1]]==Integer.MAX_VALUE?-1:length[destination[0]][destination[1]]; } } // 10/31/17 class Solution506 { class Rank { int val, index; public Rank(int a, int b) {val = a; index = b;} } public String[] findRelativeRanks(int[] nums) { PriorityQueue<Rank> priorityQueue = new PriorityQueue<>((Rank a, Rank b) -> b.val - a.val); int m = nums.length; String[] res = new String[m]; for (int i = 0; i < m; i++) { priorityQueue.add(new Rank(nums[i], i)); } for (int i = 0; i< m; i++) { Rank tmp = priorityQueue.poll(); if (i == 0) { res[tmp.index] = "Gold Medal"; } else if (i == 1) { res[tmp.index] = "Silver Medal"; } else if (i == 2) { res[tmp.index] = "Bronze Medal"; } else { res[tmp.index] = String.valueOf(i+1); } } return res; } } class Solution507 { public boolean checkPerfectNumber(int num) { int sum = 0; int tmp = (int)Math.sqrt(num); while(tmp > 1) { if (num % tmp == 0) { sum += tmp; sum += num/tmp; } tmp --; } sum++; return sum == num; } } class Solution508 { public int[] findFrequentTreeSum(TreeNode root) { Map<Integer, Integer> map = new HashMap<>(); dfs(root, map); int maxCount = Integer.MIN_VALUE; for (int i : map.keySet()) { maxCount = Math.max(maxCount, map.get(i)); } List<Integer> res = new ArrayList<>(); for (int i : map.keySet()) { if (map.get(i) == maxCount) { res.add(i); } } int[] arr = new int[res.size()]; for (int i = 0; i< res.size(); i++) { arr[i] = res.get(i); } return arr; } private int dfs(TreeNode root, Map<Integer,Integer> map) { if (root == null) { return 0;} int leftVal = dfs(root.left, map); int rightVal = dfs(root.right, map); int res = leftVal+ rightVal + root.val; map.put(res, map.getOrDefault(res, 0)+1); return res; } } class Solution512_1 { public int findBottomLeftValue(TreeNode root) { Queue<TreeNode> q = new LinkedList<>(); if (root == null) return 0; int res = 0; q.add(root); q.add(null); boolean isFirst = true; while(!q.isEmpty()) { TreeNode tmp = q.poll(); if (tmp == null) { if (!q.isEmpty()) { q.add(null); isFirst = true; res = 0; } continue; } if (isFirst) { res = tmp.val; isFirst = false; } if (tmp.left != null) {q.add(tmp.left);} if (tmp.right != null) { q.add(tmp.right);} } return res; } } class Solution515 { public List<Integer> largestValues(TreeNode root) { List<Integer> res = new ArrayList<>(); if (root == null) { return res; } int rowMax = Integer.MIN_VALUE; Queue<TreeNode> q = new LinkedList<>(); q.add(root); q.add(null); while(!q.isEmpty()) { TreeNode tmp = q.poll(); if (tmp == null) { res.add(rowMax); rowMax = Integer.MIN_VALUE; if (!q.isEmpty()) { q.add(null); } continue; } rowMax = Math.max(rowMax, tmp.val); if (tmp.left != null) {q.add(tmp.left);} if (tmp.right != null) {q.add(tmp.right);} } return res; } } class Solution516 { public int longestPalindromeSubseq(String s) { int m = s.length(); if (m == 0) return 0; int[][] dp = new int[m][m]; for (int i = 0; i< m; i++) { dp[i][i] = 1; if (i+1<m) { if (s.charAt(i) == s.charAt(i+1)) { dp[i][i+1] = 2; } else { dp[i][i+1] = 1; } } } for (int l = 2; l< m; l++) { for (int i = 0; i < m; i++) { if (i+l < m) { if (s.charAt(i) == s.charAt(i + l)) { dp[i][i + l] = 2 + dp[i + 1][i + l - 1]; } else { dp[i][i+l] = Math.max(dp[i+1][i+l], dp[i][i+l-1]); } } } } return dp[0][m-1]; } }
true
f904b7cecef359bb889935fdbe5d7e815d4eaa39
Java
Liadrinz/SimpleHBaseUtil
/src/main/java/hbase/HBaseUtil.java
UTF-8
4,295
2.5625
3
[]
no_license
package hbase; import org.apache.commons.io.Charsets; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class HBaseUtil implements IHBase { private final Configuration conf; private final Connection conn; public HBaseUtil() { conf = new Configuration(); conf.set("hbase.rootdir", "hdfs://localhost:9000/hbase"); try { conn = ConnectionFactory.createConnection(conf); } catch (IOException e) { throw new Error("Connection failed"); } } public void createTable(String tableName, String[] fields) { try { Admin admin = conn.getAdmin(); if (admin.tableExists(TableName.valueOf(tableName))) { admin.disableTable(TableName.valueOf(tableName)); admin.deleteTable(TableName.valueOf(tableName)); } HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName); for (String field : fields) { hTableDescriptor.addFamily(new HColumnDescriptor(field)); } admin.createTable(hTableDescriptor); } catch (IOException e) { e.printStackTrace(); } } public void addRecord(String tableName, String row, String[] fields, String[] values) { try { Put put = new Put(row.getBytes()); for (int i = 0; i < fields.length; ++i) { String[] familyCol = fields[i].split(":"); put.addColumn(familyCol[0].getBytes(), familyCol[1].getBytes(), values[i].getBytes()); } conn.getTable(TableName.valueOf(tableName)).put(put); } catch (IOException e) { e.printStackTrace(); } } public List<String> scanColumn(String tableName, String column) { try { Table table = conn.getTable(TableName.valueOf(tableName)); List<String> results = new ArrayList<String>(); Scan scan = new Scan(); ResultScanner scanner = table.getScanner(scan); String[] familyCol = column.split(":"); for (Result result : scanner) { if (familyCol.length == 2) { List<Cell> cells = result.getColumnCells(familyCol[0].getBytes(), familyCol[1].getBytes()); if (cells.size() == 0) return null; StringBuilder rowResult = new StringBuilder(); for (Cell cell : cells) { rowResult.append(Bytes.toString(cell.getValue())); } results.add(rowResult.toString()); } else { Map<byte[], byte[]> families = result.getFamilyMap(familyCol[0].getBytes()); List<String> rowResult = new ArrayList<String>(); for (byte[] key : families.keySet()) { rowResult.add(Bytes.toString(families.get(key))); } results.add("\n" + rowResult.toString()); } } return results; } catch (IOException e) { e.printStackTrace(); return null; } } public void modifyData(String tableName, String row, String column, String newValue) { try { Put put = new Put(row.getBytes()); String[] familyCol = column.split(":"); put.addColumn(familyCol[0].getBytes(), familyCol[1].getBytes(), newValue.getBytes()); conn.getTable(TableName.valueOf(tableName)).put(put); } catch (IOException e) { e.printStackTrace(); } } public void deleteRow(String tableName, String row) { try { Delete delete = new Delete(row.getBytes()); conn.getTable(TableName.valueOf(tableName)).delete(delete); } catch (IOException e) { e.printStackTrace(); } } }
true
0e8dd8536249d5718a72db78b2ead6aab13bcf9e
Java
renhuiyong/cocoker
/src/main/java/com/cocoker/controller/UserController.java
UTF-8
10,610
1.875
2
[]
no_license
package com.cocoker.controller; import com.cocoker.VO.ResultVO; import com.cocoker.beans.CommissionRedPack; import com.cocoker.beans.Complaint; import com.cocoker.beans.Signin; import com.cocoker.beans.UserInfo; import com.cocoker.config.ProjectUrl; import com.cocoker.dto.UserDetailDTO; import com.cocoker.enums.Positions; import com.cocoker.enums.ResultEnum; import com.cocoker.enums.UserStatusEnum; import com.cocoker.exception.CocokerException; import com.cocoker.service.*; import com.cocoker.utils.QRCodeUtil; import com.cocoker.utils.ResultVOUtil; import lombok.extern.slf4j.Slf4j; import net.coobird.thumbnailator.Thumbnails; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import java.math.BigDecimal; import java.net.HttpURLConnection; import java.net.URL; import java.util.Arrays; import java.util.Date; /** * @Description: * @Author: y * @CreateDate: 2018/12/24 9:31 PM * @Version: 1.0 */ @Controller @Slf4j @RequestMapping("/user") public class UserController { @Autowired private UserInfoService userInfoService; @Autowired private ComplaintService complaintService; @Autowired private CommissionService commissionService; @Autowired private CommissionRedPackService commissionRedPackService; @Autowired private TipService tipService; @Autowired private SigninService signinService; @Autowired private ProjectUrl projectUrl; private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath(); private static final String TG_PIC2 = "/Users/renhuiyong/Desktop/tgqr2.png"; private static final String TG_PIC3 = "/Users/renhuiyong/Desktop/tgqr3.png"; private static final String TG_PIC4 = "/Users/renhuiyong/Desktop/tgqr4.png"; @GetMapping("/complaint") public ModelAndView complaint(@RequestParam("openid") String openid) { UserInfo userInfo = userInfoService.findByOpenId(openid); if (userInfo != null) { userInfo.setYUstatus(UserStatusEnum.USER_COMPLAINT_STATUS.getCode()); userInfoService.save(userInfo); complaintService.addComplaint(new Complaint().setBalance(userInfo.getYUsermoney()).setCreateTime(new Date()).setWxNickname(userInfo.getYNickname()).setWxOpenid(userInfo.getYOpenid())); } return new ModelAndView("wxtousu/suc"); } @PostMapping("/redpack") @ResponseBody @Transactional public synchronized ResultVO redpack(@RequestParam("m") String money, @RequestParam("openid") String openid) { //检查金额 checkMoney(openid, money); //今日佣金 String commission = commissionService.findByCOpenidAndTime(openid); if (commission == null || Double.valueOf(money) > Double.valueOf(commission)) { return ResultVOUtil.error(-1, "条件未达成!"); } CommissionRedPack exist = commissionRedPackService.selectRedpackDoesItExist(openid, money); if (exist != null) { return ResultVOUtil.error(-1, "已经领取过啦!"); } CommissionRedPack save = commissionRedPackService.save(new CommissionRedPack().setMoney(new BigDecimal(money)).setCreateTime(new Date()).setOpenid(openid)); UserInfo userInfo = userInfoService.findByOpenId(openid); userInfo.setYUsermoney(userInfo.getYUsermoney().add(new BigDecimal(money))); UserInfo result = userInfoService.save(userInfo); if (result == null || save == null) { return ResultVOUtil.error(-1, "请稍后再试!"); } return ResultVOUtil.success(); } private void checkMoney(String openid, String money) { String str = "5-20-50-188"; boolean result = Arrays.asList(str.split("-")).contains(money); if (!result) { log.error("[红包] 红包领取金额异常, openid={},moeny={},正常金额={}", openid, money, str); throw new CocokerException(ResultEnum.RECHARGE_MONEY_ERROR); } } @ResponseBody @GetMapping("/get") public ResultVO getUserByOpenId(@RequestParam("openid") String openid) { UserInfo userInfo = userInfoService.findByOpenId(openid); if (userInfo == null) { // log.error("[用户查询] 查询失败 用户openid={}",openid); return ResultVOUtil.error(ResultEnum.USER_NOT_EXIST.getCode(), ResultEnum.USER_NOT_EXIST.getMsg()); } else { return ResultVOUtil.success(new UserDetailDTO("", userInfo.getYUsername(), userInfo.getYNickname(), userInfo.getYUpic(), userInfo.getYUsermoney(), "请不要攻击我,谢谢!")); } } @GetMapping("/signin") @ResponseBody @Transactional public synchronized ResultVO signIn(@RequestParam("openid") String openid) { String s = signinService.selectSigninDoesItExist(openid); if (s.equals("0")) { // Signin signin = signinService.selectSigninBytoDay(openid); // if (signin == null) { Signin signin1 = new Signin(); signin1.setOpenid(openid); String money = String.format("%.2f", (Math.random() * 0.2 + 0.1)); // Random r = new Random(); // if (r.nextInt(100) < 1) { // money = "8.88"; // } signin1.setMoney(new BigDecimal(money)); signin1.setCreateTime(new Date()); signinService.insertSignin(signin1); UserInfo user = userInfoService.findByOpenId(openid); user.setYUsermoney(user.getYUsermoney().add(new BigDecimal(money))); userInfoService.save(user); return ResultVOUtil.success(signin1); // } } else { Signin signin = signinService.selectSigninBytoDay(openid); if (signin == null) { Signin signin1 = new Signin(); signin1.setOpenid(openid); String money = String.format("%.2f", (Math.random() * 0.1) + 0.1); signin1.setMoney(new BigDecimal(money)); signin1.setCreateTime(new Date()); signinService.insertSignin(signin1); UserInfo user = userInfoService.findByOpenId(openid); user.setYUsermoney(user.getYUsermoney().add(new BigDecimal(money))); userInfoService.save(user); return ResultVOUtil.success(signin1); } else { return ResultVOUtil.error(signin); } } } @RequestMapping(value = "/uniqueQrcode", produces = MediaType.IMAGE_JPEG_VALUE) @ResponseBody public byte[] qr(@RequestParam("openid") String openid) throws Exception { UserInfo userInfo = userInfoService.findByOpenId(openid); if (userInfo == null) { return null; } String text = projectUrl.getQrUrl() + "/cocoker/wechat/authorize?upOpenid=" + openid + "&returnUrl=" + tipService.getReturnUrl() + "/cocoker/coc"; // 随机生成验证码 // String text = projectUrl.getQrUrl() + "/cocoker/wechat/authorize?upOpenid=" + openid + "&returnUrl=" + projectUrl.getReturnUrl() + "/cocoker/coc"; // 随机生成验证码 int width = 135; // 二维码图片的宽 int height = 135; // 二维码图片的高 String format = "png"; // 二维码图片的格式 try { Thumbnails.of(new File("/Users/renhuiyong/Desktop/tg2.png")).size(414, 736) .watermark(com.cocoker.enums.Positions.CUSTOM_CENBUT, ImageIO.read(new File(QRCodeUtil.generateQRCode(text, width, height, format, "/Users/renhuiyong/Desktop/qr2.png"))), 1f) .outputQuality(0.9).toFile(TG_PIC2); } catch (Exception e) { e.getMessage(); } File file = new File(TG_PIC2); saveToFile(userInfo.getYUpic()); changeSize(80, 80, TG_PIC3); Thumbnails.of(file).size(414, 736).watermark(Positions.CUSTOM_BUTLEF2, ImageIO.read(new File(TG_PIC3)), 1F) .outputQuality(0.9).toFile(TG_PIC4); File file4 = new File(TG_PIC4); FileInputStream inputStream = new FileInputStream(file4); byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes, 0, inputStream.available()); return bytes; } public void saveToFile(String destUrl) { FileOutputStream fos = null; BufferedInputStream bis = null; HttpURLConnection httpUrl = null; URL url = null; int BUFFER_SIZE = 1024; byte[] buf = new byte[BUFFER_SIZE]; int size = 0; try { url = new URL(destUrl); httpUrl = (HttpURLConnection) url.openConnection(); httpUrl.connect(); bis = new BufferedInputStream(httpUrl.getInputStream()); fos = new FileOutputStream(TG_PIC3); while ((size = bis.read(buf)) != -1) { fos.write(buf, 0, size); } fos.flush(); } catch (Exception e) { e.getMessage(); } finally { try { fos.close(); bis.close(); httpUrl.disconnect(); } catch (IOException e) { e.getMessage(); } } } public boolean changeSize(int newWidth, int newHeight, String path) { BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(path)); //字节流转图片对象 Image bi = ImageIO.read(in); //构建图片流 BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB); //绘制改变尺寸后的图 tag.getGraphics().drawImage(bi, 0, 0, newWidth, newHeight, null); //输出流 BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(path)); //JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); //encoder.encode(tag); ImageIO.write(tag, "PNG", out); in.close(); out.close(); return true; } catch (IOException e) { return false; } } }
true
626c3f8acb9cb09bf2da8fd613495e7a3255d4a7
Java
jainvaibhav35/BaseProject
/app/src/main/java/baseproject/com/appInterface/RetrofitInterface.java
UTF-8
727
2
2
[]
no_license
package baseproject.com.appInterface; import baseproject.com.beans.PostRequest.Example; import baseproject.com.beans.StackOverflowQuestions; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Query; /** * Created by lin on 2/8/16. */ public interface RetrofitInterface { // Get Request @GET("/2.2/questions?order=desc&sort=creation&site=stackoverflow") Call<StackOverflowQuestions> loadQuestions(@Query("tagged") String tags); // Post Request @FormUrlEncoded @POST("/contentaggregate/Services/edition_and_category") Call<Example> hitService(@Field("userId") String userId); }
true
b0573b3b9f66556985e8ab6722d43f0c66591054
Java
Liquidlkw/magspace2.0
/app/src/main/java/com/example/magspace/FindPic/Findpicturegame3.java
UTF-8
9,392
1.820313
2
[]
no_license
package com.example.magspace.FindPic; import android.animation.ObjectAnimator; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PathMeasure; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Region; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.util.Log; import android.view.Display; import com.example.magspace.Bean.Touchregion; import com.example.magspace.R; import com.example.magspace.Utils.DataUtil; import com.example.magspace.Utils.GameUtil; public class Findpicturegame3 extends FindpicturegameFather { public static Findpicturegame3 instance; public static Findpicturegame3 getInstance(Context context, Display display){ if (instance == null) { instance=new Findpicturegame3(context, display); } return instance; } public Findpicturegame3(Context context,Display display) { super(context); this.init(display); } public void init(Display display) { super.init(display); isneedchoose=true; curretypename=null; checkanimator = ObjectAnimator.ofFloat(Findpicturegame3.this, "checkprogress", 0.0f, 1.0f); checkanimator.setDuration(750); index=3; regions=new Touchregion[10]; rects= new Rect[3]; rects[0]= new Rect((int)(76*onep_screen_w),(int)(88*onep_screen_h),(int)(80*onep_screen_w),(int)(95*onep_screen_h)); rects[1]=new Rect((int)(83*onep_screen_w),(int)(88*onep_screen_h),(int)(87*onep_screen_w),(int)(95*onep_screen_h)); rects[2]=new Rect((int)(90*onep_screen_w),(int)(88*onep_screen_h),(int)(94*onep_screen_w),(int)(95*onep_screen_h)); new Rect((int)(76*onep_screen_w),(int)(88*onep_screen_h),(int)(80*onep_screen_w),(int)(95*onep_screen_h)); pic_num=regions.length-1; //第一个判定区域的位置 path = new Path(); path.moveTo(onep_screen_w*22,onep_screen_h*25); path.lineTo(onep_screen_w*34, onep_screen_h*34); path.lineTo(onep_screen_w*22, onep_screen_h*43); path.close(); regions[1]=new Touchregion(path); regions[1].setTypename("tangle"); ObjectAnimator animator = ObjectAnimator.ofFloat(Findpicturegame3.this, "progress1", 0.0f, 1.0f); animator.setDuration(1000); regions[1].setAnimator(animator); //第二个判定区域的位置 path = new Path(); path.moveTo(onep_screen_w*34,onep_screen_h*34); path.lineTo(onep_screen_w*47, onep_screen_h*34); path.lineTo(onep_screen_w*40, onep_screen_h*50); path.close(); regions[2]=new Touchregion(path); regions[2].setTypename("tangle"); animator = ObjectAnimator.ofFloat(Findpicturegame3.this, "progress2", 0.0f, 1.0f); animator.setDuration(1000); regions[2].setAnimator(animator); //第三个判定区域的位置 path = new Path(); path.moveTo(onep_screen_w*22,onep_screen_h*43); path.lineTo(onep_screen_w*34, onep_screen_h*34); path.lineTo(onep_screen_w*40, onep_screen_h*50); path.lineTo(onep_screen_w*29, onep_screen_h*60); path.close(); regions[3]=new Touchregion(path); regions[3].setTypename("square"); animator = ObjectAnimator.ofFloat(Findpicturegame3.this, "progress3", 0.0f, 1.0f); animator.setDuration(1000); regions[3].setAnimator(animator); //第四个判定区域的位置 path = new Path(); path.moveTo(onep_screen_w*29,onep_screen_h*60); path.lineTo(onep_screen_w*40, onep_screen_h*50); path.lineTo(onep_screen_w*40, onep_screen_h*69); path.close(); regions[4]=new Touchregion(path); regions[4].setTypename("tangle"); animator = ObjectAnimator.ofFloat(Findpicturegame3.this, "progress4", 0.0f, 1.0f); animator.setDuration(1000); regions[4].setAnimator(animator); //第五个判定区域的位置 path = new Path(); path.moveTo(onep_screen_w*40,onep_screen_h*50); path.lineTo(onep_screen_w*53, onep_screen_h*50); path.lineTo(onep_screen_w*53, onep_screen_h*69); path.lineTo(onep_screen_w*40, onep_screen_h*69); path.close(); regions[5]=new Touchregion(path); regions[5].setTypename("square"); animator = ObjectAnimator.ofFloat(Findpicturegame3.this, "progress5", 0.0f, 1.0f); animator.setDuration(1000); regions[5].setAnimator(animator); //第六个判定区域的位置 path = new Path(); path.moveTo(onep_screen_w*53,onep_screen_h*50); path.lineTo(onep_screen_w*66, onep_screen_h*50); path.lineTo(onep_screen_w*66, onep_screen_h*69); path.lineTo(onep_screen_w*53, onep_screen_h*69); path.close(); regions[6]=new Touchregion(path); regions[6].setTypename("square"); animator = ObjectAnimator.ofFloat(Findpicturegame3.this, "progress6", 0.0f, 1.0f); animator.setDuration(1000); regions[6].setAnimator(animator); //第七个判定区域的位置 path = new Path(); path.moveTo(onep_screen_w*40,onep_screen_h*69); path.lineTo(onep_screen_w*53, onep_screen_h*69); path.lineTo(onep_screen_w*48, onep_screen_h*85); path.lineTo(onep_screen_w*35, onep_screen_h*85); path.close(); regions[7]=new Touchregion(path); regions[7].setTypename("prismatic"); animator = ObjectAnimator.ofFloat(Findpicturegame3.this, "progress7", 0.0f, 1.0f); animator.setDuration(1000); regions[7].setAnimator(animator); //第八个判定区域的位置 path = new Path(); path.moveTo(onep_screen_w*53,onep_screen_h*69); path.lineTo(onep_screen_w*66, onep_screen_h*69); path.lineTo(onep_screen_w*73, onep_screen_h*85); path.lineTo(onep_screen_w*60, onep_screen_h*85); path.close(); regions[8]=new Touchregion(path); regions[8].setTypename("prismatic"); animator = ObjectAnimator.ofFloat(Findpicturegame3.this, "progress8", 0.0f, 1.0f); animator.setDuration(1000); regions[8].setAnimator(animator); //第九个判定区域的位置 path = new Path(); path.moveTo(onep_screen_w*66,onep_screen_h*50); path.lineTo(onep_screen_w*78, onep_screen_h*41); path.lineTo(onep_screen_w*78, onep_screen_h*60); path.lineTo(onep_screen_w*66, onep_screen_h*69); path.close(); regions[9]=new Touchregion(path); regions[9].setTypename("prismatic"); animator = ObjectAnimator.ofFloat(Findpicturegame3.this, "progress9", 0.0f, 1.0f); animator.setDuration(1000); regions[9].setAnimator(animator); chooseregions=new Touchregion[3]; //第一个选择区域 path = new Path(); path.addRect(76*onep_screen_w,87*onep_screen_h,83*onep_screen_w,96*onep_screen_h, Path.Direction.CW); chooseregions[0]=new Touchregion(path,"tangle",3); chooseregions[0].setPoint_x(81); chooseregions[0].setPoint_y(93); //第二个选择区域 path = new Path(); path.addRect(83*onep_screen_w,87*onep_screen_h,90*onep_screen_w,96*onep_screen_h, Path.Direction.CW); chooseregions[1]=new Touchregion(path,"square",3); chooseregions[1].setPoint_x(88); chooseregions[1].setPoint_y(93); //第三个选择区域 path = new Path(); path.addRect(90*onep_screen_w,87*onep_screen_h,97*onep_screen_w,96*onep_screen_h, Path.Direction.CW); chooseregions[2]=new Touchregion(path,"prismatic",3); chooseregions[2].setPoint_x(95); chooseregions[2].setPoint_y(93); curretypename=chooseregions[0].typename; chooseregions[0].istouch = true; } Bitmap Back = ((BitmapDrawable) this.getResources().getDrawable(R.drawable.book0_page3)) != null ? ((BitmapDrawable) this.getResources().getDrawable(R.drawable.book0_page3)).getBitmap() : null; @Override public void onDraw(Canvas c) { super.onDraw(c); c.drawBitmap(Back,null,new Rect((int)(22*onep_screen_w),(int)(15*onep_screen_h),(int)(78*onep_screen_w),(int)(95*onep_screen_h)),paint); //右下角方框 paint.setColor(this.getResources().getColor(R.color.colorred)); c.drawRect(75*onep_screen_w,80*onep_screen_h,99*onep_screen_w,85*onep_screen_h,paint); paint.setStyle(Paint.Style.STROKE); c.drawRect(75*onep_screen_w,80*onep_screen_h,99*onep_screen_w,99*onep_screen_h,paint); paint.setColor(Color.WHITE); paint.setStyle(Paint.Style.FILL); paint.setTextSize(20*fontrite); paint.setTypeface(Typeface.DEFAULT_BOLD); c.drawText("MAGSPACEE部件", 81*onep_screen_w, 84*onep_screen_h, paint); c.drawBitmap(GameUtil.getCommonBitmap(R.drawable.tangle),null,rects[0],paint); c.drawBitmap(GameUtil.getCommonBitmap(R.drawable.square),null,rects[1],paint); c.drawBitmap(GameUtil.getCommonBitmap(R.drawable.prismatic),null,rects[2],paint); super.onDraw(c); } }
true
e739e73d9066de8cf629bab0099b8e4ba92c4945
Java
spik/ID1020AlgorithmsAndDataStructures
/PascalsTriangle/RecursivePascal.java
UTF-8
1,378
4.03125
4
[]
no_license
package lab1; import java.util.Scanner; import edu.princeton.cs.algs4.Stopwatch; public class RecursivePascal implements Pascal{ public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter row number: "); int row = in.nextInt(); System.out.println("Enter 'true' or 'false': "); boolean b = in.nextBoolean(); RecursivePascal pascal = new RecursivePascal(); Stopwatch stopwatch = new Stopwatch(); pascal.printPascal(row, b); double time = stopwatch.elapsedTime(); System.out.println(""); System.out.println("Runtime: " + time); in.close(); } public void printPascal(int row, boolean b) { if (row == 0) { System.out.println("\t1"); return; } else { if(b) printPascal(row-1, b); //Calculate every entry in the row by calling binom for (int i = 0; i <= row; i++) { System.out.print(" " + binom(row, i)); } System.out.println(""); if(!b) printPascal(row-1, b); } } public int binom (int n, int k) { if (k < 0 || k > n) { System.out.println("Not defined for 0 > k > n"); return 0; } if (k==0 || k==n) return 1; else //n is the current row an k is the current number. //recursivly add the previous entry from the previous row with the current entry in the previous row return binom(n-1, k-1) + binom(n-1, k); } }
true
6675c17e33441bbf384208faca23fc57795b72fd
Java
RyanTech/ctbri
/WeSee/src/com/ctri/entity/data/RecommendList.java
UTF-8
953
2.234375
2
[]
no_license
package com.ctri.entity.data; import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.reflect.TypeToken; public class RecommendList { private String tag_name; private JsonElement program_list; public String getTag_name() { return tag_name; } public void setTag_name(String tag_name) { this.tag_name = tag_name; } public JsonElement getProgram_list() { return program_list; } public void setProgram_list(JsonElement program_list) { this.program_list = program_list; } public List<ProgramBroadcast> mProgramList = new ArrayList<ProgramBroadcast>(); public ArrayList<ProgramBroadcast> getProgramList(){ Gson gson = new Gson(); return gson.fromJson(program_list, new TypeToken<ArrayList<ProgramBroadcast>>(){}.getType()); } public RecommendListItem toRecommendListItem(){ return new RecommendListItem(tag_name, getProgramList()); } }
true
94707aea0295cfc4826cb90b23b185d8079493ad
Java
FiveMedia/SpaceClones
/Space/core/src/ca/fivemedia/space/MovingBlock.java
UTF-8
12,765
1.921875
2
[]
no_license
package ca.fivemedia.space; import com.badlogic.gdx.ApplicationAdapter; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.*; import com.badlogic.gdx.graphics.g2d.*; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.maps.tiled.*; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer; import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer; import ca.fivemedia.gamelib.*; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Circle; import com.badlogic.gdx.graphics.glutils.*; import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; import com.badlogic.gdx.graphics.g2d.ParticleEffectPool.*; import com.badlogic.gdx.math.Intersector; import com.badlogic.gdx.math.Rectangle; public class MovingBlock extends BaseSprite implements SwitchChangedListener { boolean m_movingSoundPlaying = false; long m_soundId = 0; float m_sawVolume = 0.05f; MainGameLayer m_gameLayer = null; GameAnimateable m_spawnSpecialAnimation = null; float m_scale = 1.0f; int m_startState = 0; int m_switchState = 1; boolean m_switchAttached = false; boolean m_perm = false; TiledMapTile m_topTile, m_leftTile, m_rightTile, m_bottomTile; boolean m_destroyStuff = false; int m_iter = 0; Rectangle m_bb = new Rectangle(); float m_xOff, m_yOff; public MovingBlock(TextureAtlas myTextures, TiledMapTileLayer pTiles, TiledMapTileLayer lTiles, float scale, String move, float speed, MainGameLayer layer, float pt, float pb) { super(myTextures.findRegion("moving_block"),pTiles,lTiles); if (pb < 0) { //flat top/special if (layer.m_stage == 2) this.setRegion(myTextures.findRegion("moving_block_b_r")); else this.setRegion(myTextures.findRegion("moving_block_b")); m_perm = true; TiledMap tm = layer.tiledMap.m_tiledMap; TiledMapTileSets ts = tm.getTileSets(); m_topTile = ts.getTile(1); m_leftTile = ts.getTile(6); m_rightTile = ts.getTile(5); m_bottomTile = ts.getTile(7); } else { if (layer.m_stage == 2) this.setRegion(myTextures.findRegion("moving_block_r")); } m_deathSoundVolume = 0.55f; m_soundPrefix = "movingBlock"; m_numSounds = 0; m_destroyStuff = false; m_hideOnDead = true; m_scale = scale; if (move.equals("Static")) { m_moveController = new StaticMoveController(0f); } else if (move.equals("Vertical")) { boolean shake = false; if (pb >= 0) shake = true; m_moveController = new FallMoveController(4.0f * speed, true, true, pt, pb, shake); } else if (move.equals("Horizontal")) { m_moveController = new SingleDirectionMoveController(4.0f * speed, true,0); if (m_scale > 1.5f) { m_destroyStuff = true; } } //m_walkAnimation = new AnimateSpriteFrame(myTextures, new String[] {"GreenCloud_F1"}, 1.0f, -1); //this.runAnimation(m_walkAnimation); m_numSounds = 0; //m_soundPrefix = "saw"; m_walkAnimation = new AnimateSpriteFrame(myTextures, new String[] {"moving_block"}, 1.0f, -1); this.setScale(scale); m_sawVolume = 0.04f * scale + 0.08f; m_gameLayer = layer; m_standardDeathAnimation = new AnimateFadeOut(0.2f); m_deathAnimation = m_standardDeathAnimation; m_bb.width = this.getBoundingRectangle().width * 0.9f; m_bb.height = this.getBoundingRectangle().height * 0.9f; m_xOff = this.getBoundingRectangle().width * 0.05f; m_yOff = this.getBoundingRectangle().height * 0.05f; } public void die() { if (m_dying) return; super.die(); m_dying = true; if (m_movingSoundPlaying) { this.stopSound("movingBlock1", m_soundId); m_movingSoundPlaying = false; m_soundId = 0; } if (m_scale < 2) { PooledEffect effect = m_gameLayer.sawEffectPool.obtain(); effect.setPosition(this.getX()+this.getWidth()/2, this.getY()); m_gameLayer.addParticleEffect(effect); this.playDeathSound(); } else { this.bigBlockExplode(); } } public void explodeHere(float xx, float yy) { PooledEffect effect = m_gameLayer.sawEffectPool.obtain(); effect.setPosition(xx, yy); m_gameLayer.addParticleEffect(effect); //this.playDeathSound(); this.playSoundIfOnScreen("movingBlockDestroy", 0.8f, 0.6f); } public void move() { if (m_pause) return; if (((m_startState == 0) && (m_switchState == 1)) || ((m_startState == 1) && (m_switchState == 0))) { m_moveController.move(this, m_internalPlayer, m_platformTiles, m_climbableTiles); if ((m_moveController.isMotionActive() == false) && (m_switchAttached)) { //Gdx.app.debug("SingleDirMoveController", "MOVE STOPPED - toggling start state"); m_startState++; if (m_startState > 1) m_startState = 0; } if (m_moveController.isDone()) { float xx = this.getX(); float bottomY = this.getY(); int tileX = (int) Math.floor(xx/tw); int tileY = (int) Math.floor(bottomY/th); TiledMapTileLayer.Cell cc = new TiledMapTileLayer.Cell(); cc.setTile(m_bottomTile); m_platformTiles.setCell(tileX, tileY, cc); cc = new TiledMapTileLayer.Cell(); cc.setTile(m_bottomTile); m_platformTiles.setCell(tileX+1, tileY, cc); cc = new TiledMapTileLayer.Cell(); cc.setTile(m_bottomTile); m_platformTiles.setCell(tileX+2, tileY, cc); cc = new TiledMapTileLayer.Cell(); cc.setTile(m_leftTile); m_platformTiles.setCell(tileX, tileY+1, cc); cc = new TiledMapTileLayer.Cell(); cc.setTile(m_topTile); m_platformTiles.setCell(tileX+1, tileY+1, cc); cc = new TiledMapTileLayer.Cell(); cc.setTile(m_rightTile); m_platformTiles.setCell(tileX+2, tileY+1, cc); cc = new TiledMapTileLayer.Cell(); cc.setTile(m_topTile); m_platformTiles.setCell(tileX, tileY+2, cc); cc = new TiledMapTileLayer.Cell(); cc.setTile(m_topTile); m_platformTiles.setCell(tileX+1, tileY+2, cc); cc = new TiledMapTileLayer.Cell(); cc.setTile(m_topTile); m_platformTiles.setCell(tileX+2, tileY+2, cc); this.setVisible(false); } } else { m_dx = 0; m_dy = 0; } if (m_movingSoundPlaying == false) { if (m_parent.isOnScreen(this.getX(), this.getY())) { if ((m_soundId == 0) && (m_dx != 0)) { m_soundId = loopSoundManageVolume("movingBlock1", this, m_internalPlayer, 0.85f,0.55f); m_movingSoundPlaying = true; } } } else if ((m_parent.isOnScreen(this.getX(), this.getY()) == false) || (m_dx == 0)) { if (m_soundId >= 0) { this.stopSound("movingBlock1", m_soundId); m_movingSoundPlaying = false; m_soundId = 0; } } if ((m_dx != 0) && m_destroyStuff) { this.destroySprites(); this.destroyTiles(); } } @Override public void hitPlayer(PlayerSprite player) { } public void destroySprites() { m_bb.x = this.getBoundingRectangle().x + m_xOff; m_bb.y = this.getBoundingRectangle().y + m_yOff; for (m_iter = 0; m_iter < m_gameLayer.getChildren().size(); m_iter++) { GameDrawable s = m_gameLayer.getChildren().get(m_iter); if (((s instanceof TreeSprite) || (s instanceof MovingBlock) || (s instanceof SwitchSprite)) && (s.isVisible())) { if (s != this) { GameSprite ss = (GameSprite)s; if (Intersector.overlaps(ss.getBoundingRectangle(), m_bb)) { if (s instanceof MovingBlock) { MovingBlock sss = (MovingBlock)s; sss.die(); } else { ss.setVisible(false); this.explodeHere(ss.getX() + ss.getWidth()/2, ss.getY()); } } } } } for (m_iter = 0; m_iter < m_gameLayer.getChildrenBack().size(); m_iter++) { GameDrawable s = m_gameLayer.getChildrenBack().get(m_iter); if (((s instanceof TreeSprite) || (s instanceof MovingBlock) || (s instanceof SwitchSprite)) && (s.isVisible())) { if (s != this) { GameSprite ss = (GameSprite)s; if (Intersector.overlaps(ss.getBoundingRectangle(), m_bb)) { if (s instanceof MovingBlock) { MovingBlock sss = (MovingBlock)s; sss.die(); } else { ss.setVisible(false); } this.explodeHere(ss.getX() + ss.getWidth()/2, ss.getY()); } } } } } public void destroyTiles() { float xx = this.getX() + this.getWidth() + 116; float yy = this.getY() + this.getHeight() + 64; float xOff = 90; if (m_dx < 0) { xx = this.getX() - 116; xOff = -90; } int tileX = (int) Math.floor(xx/48); for (m_iter = 0; m_iter < 9; m_iter++) { int tileY = (int) Math.floor(yy/32); int c = this.getCellAt(tileX, tileY); if (c > 0) { m_platformTiles.setCell(tileX, tileY, null); explodeHere(xx+xOff,yy); } yy -= 32; } } public void bigBlockExplode() { float xx = this.getX() - 120; float yy = this.getY() - 80; float xOff = 16; if (m_dx < 0) xOff = -16; for (int xi = 0; xi < 9; xi++) { for (int yi = 0; yi < 9; yi++) { explodeHere(xx+xOff + xi * 48,yy + yi * 32); } } } @Override public void resetLevel() { if (m_wasSpawned) { m_dx = 0; m_dy = 0; this.stopAllAnimations(); this.setOpacity(1); this.setVisible(false); m_dying = false; m_alive = false; m_spawning = false; m_pauseMoveTicks = 0; m_moveController.reset(); } else if (m_startX >= 0) { this.setPosition(m_startX, m_startY); m_dx = 0; m_dy = 0; m_moveController.reset(); m_pauseMoveTicks = 0; } if (m_soundId != 0) this.stopSound("movingBlock1", m_soundId); else this.stopSound("movingBlock1"); m_movingSoundPlaying = false; m_soundId = 0; this.setScale(m_scale); } @Override public void hitByAttack() { /* this.stopAllAnimations(); this.runAnimation(m_deathAnimation); m_dying = true; this.playDeathSound(); */ } @Override public void hitByBlock() { this.stopAllAnimations(); m_deathAnimation = m_flattenAnimation; this.setOrigin(this.getOriginX(), 0); this.runAnimation(m_deathAnimation); m_dying = true; this.playSound("plasmaCubeCrush", 0.4f); } public void setFastSpawn(boolean soundOn) { m_spawnAnimation = new AnimateFadeIn(0.05f); float max = 0.7f; float min = 0.45f; if (soundOn) { max = 0.35f; min = 0.15f; } AnimateDelay d = new AnimateDelay(0.2f); AnimatePlaySound fi = new AnimatePlaySound("fogVertical", m_internalPlayer, max, min, soundOn); GameAnimateable[] a = {d,fi}; m_spawnSpecialAnimation = new GameAnimationSequence(a,1); } public void setSwitch(SwitchSprite s, int startState) { m_startState = startState; s.addLight(this); m_switchState = s.getState(); m_switchAttached = true; //Gdx.app.debug("SawSprite", "Switch attached."); } public void trigger() { if (m_moveController != null) m_moveController.triggerMotion(); } public void spawn() { if (m_moveController != null) m_moveController.reset(); m_wasSpawned = true; m_pauseMoveTicks = 0; this.setOrigin(this.getOriginX(), m_originalOriginY); m_deathAnimation = m_standardDeathAnimation; if (m_walkAnimation.isRunning() == false) this.runAnimation(m_walkAnimation); this.setVisible(true); m_alive = true; m_dying = false; m_spawning = true; this.runAnimation(m_spawnAnimation); m_dx = 0; m_dy = 0; //Gdx.app.debug("SawSprite", "Spawning"); this.setScale(m_scale); if (m_spawnSpecialAnimation != null) { this.runAnimation(m_spawnSpecialAnimation); } } public void switchStateChanged(int state, boolean animate) { m_switchState = state; } public void endLevel(float mx, float my) { super.endLevel(mx, my); this.stopSound("movingBlock1"); } }
true
d440de22b87b846a1b4b4d51d683534d78fbae2e
Java
team3663/StrongHold
/Cube_CommandBase/src/org/usfirst/frc/team3663/robot/commands/C_WaitSecs.java
UTF-8
1,253
2.578125
3
[]
no_license
package org.usfirst.frc.team3663.robot.commands; import org.usfirst.frc.team3663.robot.Robot; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.command.Command; /** * */ public class C_WaitSecs extends Command { double endTime = 0; double delay = 0; int ctr=0; public C_WaitSecs(double pDelay) { // Use requires() here to declare subsystem dependencies // eg. requires(chassis); delay = pDelay; } // Called just before this Command runs the first time protected void initialize() { endTime = Timer.getFPGATimestamp()+delay; ctr=0; } // Called repeatedly when this Command is scheduled to run protected void execute() { //Robot.gui.sendNumber("general/wait",endTime-Timer.getFPGATimestamp()); //Robot.gui.sendNumber("general/ctr",ctr++); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return Timer.getFPGATimestamp() > endTime; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
true
c043716153b4029dc6b453e2d398126457db3567
Java
abstractionLevel/ReporektBackend
/src/main/java/com/example/ReportPlayer/models/reportTypeRegion/ReportTypeRegion.java
UTF-8
1,183
2.21875
2
[]
no_license
package com.example.ReportPlayer.models.reportTypeRegion; import javax.persistence.*; @Entity @Table(name = "report_type_region") public class ReportTypeRegion { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(name = "report_type") private String reportType; @Column(name = "count") private int count; @Column(name = "region") private String region; public ReportTypeRegion() {} public ReportTypeRegion(String reportType, int count , String region ){ this.reportType = reportType; this.count = count; this.region = region; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getReportType() { return reportType; } public void setReportType(String reportType) { this.reportType = reportType; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } }
true
5b9d7245b0585335cbff75f9168126c3b21bdcaa
Java
KrishnaKTechnocredits/JAVATechnoOct2020
/src/himali/Assignment15/CheckVowels.java
UTF-8
601
3.078125
3
[]
no_license
package himali.Assignment15; import java.util.Scanner; public class CheckVowels { void findVowels(String word) { System.out.println("Vowels are --> "); for(int i=0;i<word.length();i++) { char ch=word.charAt(i); if(ch=='a' || ch=='e' || ch=='i'|| ch=='o' ||ch=='u' || ch=='A' || ch=='E' || ch=='I'|| ch=='O' ||ch=='U') { System.out.println(ch); } } } public static void main(String[] args) { // TODO Auto-generated method stub CheckVowels vowels=new CheckVowels(); Scanner sc=new Scanner(System.in); String word=sc.next(); vowels.findVowels(word); } }
true
a1c36a8169af328a714e333d2e3331fe284bf138
Java
svetomsk/ld29-wet-heads
/src/entity/mob/controllers/ButterflyController.java
UTF-8
730
2.734375
3
[]
no_license
package entity.mob.controllers; import main.World; import entity.Entity; import entity.mob.Mob; public class ButterflyController extends Controller { public ButterflyController(Mob mob) { super(mob); } private boolean right; @Override public void tick() { // if(right) mob.onRight(); // else mob.onLeft(); // // if(isEnd()) right = !right; } private boolean isEnd() { if(Math.abs(mob.getLVX()) < 3) return true; if(!right) if(!mob.getWorld().collideIslands(mob.getCX()-8, mob.getCY()+mob.getHeight()+8) ) return true; if(right) if(!mob.getWorld().collideIslands(mob.getCX()+mob.getWidth()+10, mob.getCY()+mob.getHeight()+10) ) return true; return false; } }
true
bbaf40541fd8b49ad044cbe47f88f59f2d63b3c8
Java
NunoAlexandre/innovation-funding-service
/ifs-web-service/ifs-web-core/src/main/java/org/innovateuk/ifs/project/financecheck/eligibility/viewmodel/FinanceChecksEligibilityViewModel.java
UTF-8
6,060
1.96875
2
[ "MIT" ]
permissive
package org.innovateuk.ifs.project.financecheck.eligibility.viewmodel; import org.apache.commons.lang3.StringUtils; import org.innovateuk.ifs.file.controller.viewmodel.FileDetailsViewModel; import org.innovateuk.ifs.project.finance.resource.EligibilityRagStatus; import org.innovateuk.ifs.project.finance.resource.FinanceCheckEligibilityResource; import java.time.LocalDate; /** * View model backing the internal Finance Team members view of the Finance Check Eligibility page */ public class FinanceChecksEligibilityViewModel { private FinanceCheckEligibilityResource eligibilityOverview; private String organisationName; private boolean leadPartnerOrganisation; private String projectName; private Long applicationId; private Long projectId; private Long organisationId; private boolean eligibilityApproved; private EligibilityRagStatus eligibilityRagStatus; private String approverFirstName; private String approverLastName; private LocalDate approvalDate; private boolean externalView; private boolean isUsingJesFinances; private FileDetailsViewModel jesFileDetails; public FinanceChecksEligibilityViewModel(FinanceCheckEligibilityResource eligibilityOverview, String organisationName, String projectName, Long applicationId, boolean leadPartnerOrganisation, Long projectId, Long organisationId, boolean eligibilityApproved, EligibilityRagStatus eligibilityRagStatus, String approverFirstName, String approverLastName, LocalDate approvalDate, boolean externalView, boolean isUsingJesFinances, FileDetailsViewModel jesFileDetailsViewModel) { this.eligibilityOverview = eligibilityOverview; this.organisationName = organisationName; this.projectName = projectName; this.applicationId = applicationId; this.leadPartnerOrganisation = leadPartnerOrganisation; this.projectId = projectId; this.organisationId = organisationId; this.eligibilityApproved = eligibilityApproved; this.eligibilityRagStatus = eligibilityRagStatus; this.approverFirstName = approverFirstName; this.approverLastName = approverLastName; this.approvalDate = approvalDate; this.externalView = externalView; this.isUsingJesFinances = isUsingJesFinances; this.jesFileDetails = jesFileDetailsViewModel; } public boolean isApproved() { return eligibilityApproved; } public boolean isShowSaveAndContinueButton() { return !isApproved(); } public boolean isShowBackToFinanceCheckButton() { return isApproved(); } public boolean isShowApprovalMessage() { return isApproved(); } public String getApproverName() { return StringUtils.trim(getApproverFirstName() + " " + getApproverLastName()); } public FinanceCheckEligibilityResource getEligibilityOverview() { return eligibilityOverview; } public void setEligibilityOverview(FinanceCheckEligibilityResource eligibilityResource) { this.eligibilityOverview = eligibilityResource; } public String getOrganisationName() { return organisationName; } public void setOrganisationName(String organisationName) { this.organisationName = organisationName; } public boolean isLeadPartnerOrganisation() { return leadPartnerOrganisation; } public void setLeadPartnerOrganisation(boolean leadPartnerOrganisation) { this.leadPartnerOrganisation = leadPartnerOrganisation; } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public Long getApplicationId() { return applicationId; } public void setApplicationId(Long applicationId) { this.applicationId = applicationId; } public Long getProjectId() { return projectId; } public void setProjectId(Long projectId) { this.projectId = projectId; } public boolean isEligibilityApproved() { return eligibilityApproved; } public void setEligibilityApproved(boolean eligibilityApproved) { this.eligibilityApproved = eligibilityApproved; } public EligibilityRagStatus getEligibilityRagStatus() { return eligibilityRagStatus; } public void setEligibilityRagStatus(EligibilityRagStatus eligibilityRagStatus) { this.eligibilityRagStatus = eligibilityRagStatus; } public String getApproverFirstName() { return approverFirstName; } public void setApproverFirstName(String approverFirstName) { this.approverFirstName = approverFirstName; } public String getApproverLastName() { return approverLastName; } public void setApproverLastName(String approverLastName) { this.approverLastName = approverLastName; } public LocalDate getApprovalDate() { return approvalDate; } public void setApprovalDate(LocalDate approvalDate) { this.approvalDate = approvalDate; } public Long getOrganisationId() { return organisationId; } public void setOrganisationId(Long organisationId) { this.organisationId = organisationId; } public boolean isExternalView() { return externalView; } public void setExternalView(boolean externalView) { this.externalView = externalView; } public boolean isUsingJesFinances() { return isUsingJesFinances; } public void setUsingJesFinances(boolean usingJesFinances) { isUsingJesFinances = usingJesFinances; } public FileDetailsViewModel getJesFileDetails() { return jesFileDetails; } public void setJesFileDetails(FileDetailsViewModel jesFileDetails) { this.jesFileDetails = jesFileDetails; } }
true
1bf5fe01a3d8aa360cbeb8d82c2a3b57a048eaa6
Java
mienv567/comtainer-game
/fanweHybridLive/src/main/java/com/fanwe/hybrid/model/AppAddVideoModel.java
UTF-8
3,815
1.820313
2
[]
no_license
package com.fanwe.hybrid.model; import com.fanwe.live.model.UserModel; /** * Created by kevin.liu on 2017/2/24. */ public class AppAddVideoModel extends BaseActModel{ /** * share : {"shareTitle":"辣就这样吧,瞧我播一下","shareUrl":"http://www.qg8.com//index?c=share&user_id=28&video_id=80","shareImgUrl":"http://192.168.1.63:8081/live-web/login/http://q.qlogo.cn/qqapp/1105588451/DA066AE2CF6D77116043E1C4A8CF7EE1/100","shareKey":80,"shareContent":"辣就这样吧,瞧我播一下Huanyu the Carpenter正在直播,快来一起看~"} * hasLianmai : 0 * podcast : {"sex":1,"videoCount":0,"diamonds":0,"isAgree":0,"useDiamonds":0,"isRemind":1,"nickName":"Huanyu the Carpenter","ticket":0,"refundTicket":0,"authentication":0,"headImage":"http://192.168.1.63:8081/live-web/login/http://q.qlogo.cn/qqapp/1105588451/DA066AE2CF6D77116043E1C4A8CF7EE1/100","userId":28,"userLevel":1,"useableTicket":0,"fansCount":0} * push_url : rtmp://pili-publish.qiankeep.com/mala/80?e=1487908389&token=ZUdTZzOrAMrgTac4e2I-w_F2_NsMCU_IrLeE580r:wTFqkGHdZC3LHXKxyU1g0SCSf1w= * watchNum : 0 * group_id : @TGS#2KLCM2MEK */ private ShareBean share; private int hasLianmai; private UserModel podcast; private String push_url; private long watchNum; private String group_id; public ShareBean getShare() { return share; } public void setShare(ShareBean share) { this.share = share; } public int getHasLianmai() { return hasLianmai; } public void setHasLianmai(int hasLianmai) { this.hasLianmai = hasLianmai; } public UserModel getPodcast() { return podcast; } public void setPodcast(UserModel podcast) { this.podcast = podcast; } public String getPush_url() { return push_url; } public void setPush_url(String push_url) { this.push_url = push_url; } public long getWatchNum() { return watchNum; } public void setWatchNum(long watchNum) { this.watchNum = watchNum; } public String getGroup_id() { return group_id; } public void setGroup_id(String group_id) { this.group_id = group_id; } public static class ShareBean { /** * shareTitle : 辣就这样吧,瞧我播一下 * shareUrl : http://www.qg8.com//index?c=share&user_id=28&video_id=80 * shareImgUrl : http://192.168.1.63:8081/live-web/login/http://q.qlogo.cn/qqapp/1105588451/DA066AE2CF6D77116043E1C4A8CF7EE1/100 * shareKey : 80 * shareContent : 辣就这样吧,瞧我播一下Huanyu the Carpenter正在直播,快来一起看~ */ private String shareTitle; private String shareUrl; private String shareImgUrl; private int shareKey; private String shareContent; public String getShareTitle() { return shareTitle; } public void setShareTitle(String shareTitle) { this.shareTitle = shareTitle; } public String getShareUrl() { return shareUrl; } public void setShareUrl(String shareUrl) { this.shareUrl = shareUrl; } public String getShareImgUrl() { return shareImgUrl; } public void setShareImgUrl(String shareImgUrl) { this.shareImgUrl = shareImgUrl; } public int getShareKey() { return shareKey; } public void setShareKey(int shareKey) { this.shareKey = shareKey; } public String getShareContent() { return shareContent; } public void setShareContent(String shareContent) { this.shareContent = shareContent; } } }
true
e4ed15b2b604f96460926aa32e9c0eee7b20902f
Java
JessicaPortilio/Estrutura_De_Dados_1
/ArvoreBalanceado/src/com/atividade/TNodo.java
UTF-8
287
2.296875
2
[]
no_license
package com.atividade; public class TNodo { TNodo esq; TInfo item; TNodo dir; TNodo pai; int bal = 0; int hesq = 0; int hdir = 0; public TNodo(TInfo item, TNodo pai) { this.item = new TInfo(item.chave, item.nome); this.esq = null; this.dir = null; this.pai = pai; } }
true
d549ff7ea27c6cb1b1cf272df5fc58e67a84f5be
Java
jeyjey626/dietHelperBackend
/src/main/java/com/jmakulec/osm/demo/dto/ExamShortDTO.java
UTF-8
527
2.4375
2
[]
no_license
package com.jmakulec.osm.demo.dto; import com.fasterxml.jackson.annotation.JsonFormat; import com.jmakulec.osm.demo.domain.Exam; import lombok.Data; import java.time.LocalDate; import java.time.LocalDateTime; @Data public class ExamShortDTO { private Long exam_id; @JsonFormat(pattern = "yyyy-MM-dd") private LocalDate date; private Double weight; public ExamShortDTO(Exam exam){ this.exam_id = exam.getId(); this.date = exam.getDate(); this.weight = exam.getWeight(); } }
true
c08812b97551c82be17ebe804fe0807f56597b2c
Java
igorkol1/JAVA-OOP
/b_Zadania_domowe/b_Dzien_2/SoundBook.java
UTF-8
829
2.8125
3
[]
no_license
package b_Zadania_domowe.b_Dzien_2; import java.util.List; public class SoundBook extends Book { private double duration; private int numberOfCarriers; public SoundBook(String title, double duration, int numberOfCarriers) { super(title); this.duration = duration; this.numberOfCarriers = numberOfCarriers; } public SoundBook(String title, Author author, double duration, int numberOfCarriers) { super(title, author); this.duration = duration; this.numberOfCarriers = numberOfCarriers; } public SoundBook(String title, Author author, List<Author> additionalAuthors, double duration, int numberOfCarriers) { super(title, author, additionalAuthors); this.duration = duration; this.numberOfCarriers = numberOfCarriers; } }
true
8153e6d002f2dabea25be790515a1c287278b789
Java
shaurya-k/Dictionary-Using-BST
/DictionaryDriver.java
UTF-8
5,291
3.359375
3
[]
no_license
//////////////////// ALL ASSIGNMENTS INCLUDE THIS SECTION ///////////////////// // // Title: (Dictionary Using BST) // Files: (Dictionary.java, DictionaryBST.java, DictionaryDriver.java, DictionarWord.java, // DictionaryTests.java) // Course: (CS 300, Spring, and 2019) // // Author: (Shaurya Kethireddy) // Email: (skethireddy@wisc.edu) // Lecturer's Name: (Gary Dahl) // // // Students who get help from sources other than their partner must fully // acknowledge and credit those sources of help here. Instructors and TAs do // not need to be credited here, but tutors, friends, relatives, room mates, // strangers, and others do. If you received no outside help from either type // of source, then please explicitly indicate NONE. // // Persons: None // Online Sources: None // /////////////////////////////// 80 COLUMNS WIDE /////////////////////////////// import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.Scanner; /** * This class is a driver application which will run the DictionaryBST and the methods * * @author shaurya * */ public class DictionaryDriver { /** * main method which runs the program * * @param args */ public static void main(String[] args) { DictionaryBST dict = new DictionaryBST(); // creates new DictionaryBST object Scanner scnr = new Scanner(System.in); // Initializes new scanner String response = ""; // initialize response string while (!response.equals("q")) { // condition printCommandPrompt(); // calls print method System.out.println("Please enter your command: "); response = scnr.next(); // takes next word response = response.toLowerCase(); // switches to lower case try { if (response.equals("a")) { String word = scnr.next().trim(); // assigns word with characters until next space String meaning = scnr.nextLine().trim(); // assigns meaning with characters until next new // line if (word.equals(null) || meaning.equals(null) || word.isEmpty() || meaning.isEmpty()) { System.out.println("WARNING: Syntax Error for [A <word> <meaning>] command line."); } else { dict.addWord(word, meaning); // add the word and meaning to dictionary } } else if (response.equals("l")) { String lookup = scnr.next(); // assign lookup with characters until next space if (lookup.equals(null) || lookup.isEmpty()) { System.out.println("WARNING: Syntax Error for [L <word>] command line."); } else { System.out.println(lookup + ": " + dict.lookup(lookup)); // calls method with param } } else if (response.equals("g")) { if (dict.size() == 0) { // condition System.out.println("Dictionary is empty."); } else { int size = dict.size(); // assign size with dictionary size ArrayList<String> wordsInList = dict.getAllWords(); // intialize array with all the // words String printWords = null; // intialize new string for (int i = 0; i < size; i++) { // for loop to iterate through if (i == 0) { printWords = wordsInList.get(0); // print the first word } else { printWords = printWords + ", " + wordsInList.get(i); // add words with comma } } System.out.println(printWords); } } else if (response.equals("s")) { System.out.println(dict.size());// prints the called method } else if (response.equals("h")) { System.out.println(dict.height());// prints the called method } else if (response.equals("q")) { break; // break out of the while loop } else { System.out.println("WARNING: Unrecognized command."); // if input not one of desired // commands } } catch (IllegalArgumentException e) { // catch Illegal exception System.out.println(e.getMessage());// print error message } catch (NoSuchElementException e) {// catch NoSuchElement exception System.out.println(e.getMessage());// print error message } } System.out.println("============================== END ==================================="); scnr.close(); // close scanner } /** * helper method to print out the command prompt */ public static void printCommandPrompt() { System.out.println("=========================== Dictionary ============================\n" + "Enter one of the following options:\n" + "[A <word> <meaning>] to add dict new word and its definition in the dictionary\n" + "[L <word>] to search dict word in the dictionary and display its definition\n" + "[G] to print all the words in the dictionary in sorted order\n" + "[S] to get the count of all words in the dictionary\n" + "[H] to get the height of this dictionary implemented as dict binary search tree\n" + "[Q] to quit the program\n" + "======================================================================"); } }
true
dcd9753eceac3d7d48224e1bd99ab3c0fb2ddc67
Java
vanshianec/Hibernate-And-Spring-Data
/Exams/22 April 2018/Most Wanted/src/main/java/mostwanted/service/RaceServiceImpl.java
UTF-8
3,685
2.4375
2
[]
no_license
package mostwanted.service; import mostwanted.common.Constants; import mostwanted.domain.dtos.raceentries.RaceEntryImportDto; import mostwanted.domain.dtos.raceentries.RaceEntryImportRootDto; import mostwanted.domain.dtos.races.EntryImportRootDto; import mostwanted.domain.dtos.races.RaceImportDto; import mostwanted.domain.dtos.races.RaceImportRootDto; import mostwanted.domain.entities.District; import mostwanted.domain.entities.Race; import mostwanted.domain.entities.RaceEntry; import mostwanted.repository.DistrictRepository; import mostwanted.repository.RaceEntryRepository; import mostwanted.repository.RaceRepository; import mostwanted.util.FileUtil; import mostwanted.util.ValidationUtil; import mostwanted.util.XmlParser; import org.modelmapper.ModelMapper; import org.springframework.stereotype.Service; import javax.xml.bind.JAXBException; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; @Service public class RaceServiceImpl implements RaceService { private final static String RACES_XML_FILE_PATH = System.getProperty("user.dir") + "/src/main/resources/files/races.xml"; private final RaceRepository raceRepository; private final RaceEntryRepository raceEntryRepository; private final DistrictRepository districtRepository; private final ModelMapper modelMapper; private final ValidationUtil validationUtil; private final FileUtil fileUtil; private final XmlParser xmlParser; public RaceServiceImpl(RaceRepository raceRepository, RaceEntryRepository raceEntryRepository, DistrictRepository districtRepository, ModelMapper modelMapper, ValidationUtil validationUtil, FileUtil fileUtil, XmlParser xmlParser) { this.raceRepository = raceRepository; this.raceEntryRepository = raceEntryRepository; this.districtRepository = districtRepository; this.modelMapper = modelMapper; this.validationUtil = validationUtil; this.fileUtil = fileUtil; this.xmlParser = xmlParser; } @Override public Boolean racesAreImported() { return raceRepository.count() > 0; } @Override public String readRacesXmlFile() throws IOException { return this.fileUtil.readFile(RACES_XML_FILE_PATH); } @Override public String importRaces() throws JAXBException { StringBuilder stringBuilder = new StringBuilder(); RaceImportRootDto rootDto = this.xmlParser.parseXml(RaceImportRootDto.class, RACES_XML_FILE_PATH); for (RaceImportDto raceDto : rootDto.getRaceDtos()) { Race race = this.modelMapper.map(raceDto, Race.class); if (!this.validationUtil.isValid(race)) { stringBuilder.append(Constants.INCORRECT_DATA_MESSAGE).append(System.lineSeparator()); continue; } District district = this.districtRepository.findDistrictByName(raceDto.getDistrictName()); race.setDistrict(district); Race finalRace = race; List<RaceEntry> entries = raceDto.getEntries().getEntryDtos().stream() .map(e -> { RaceEntry entry = this.raceEntryRepository.findRaceEntriesById(e.getId()); entry.setRace(finalRace); return entry; }).collect(Collectors.toList()); race.setEntries(entries); race = this.raceRepository.saveAndFlush(race); stringBuilder.append(String.format(Constants.SUCCESSFUL_IMPORT_MESSAGE, race.getClass().getSimpleName(), race.getId())).append(System.lineSeparator()); } return stringBuilder.toString().trim(); } }
true
123e5d5a1672ac9c8dbe4358b765e35ce29157a8
Java
wldzam/JavaRushTasks
/2.JavaCore/src/com/javarush/task/task18/task1809/Solution.java
UTF-8
834
3.109375
3
[ "MIT" ]
permissive
package com.javarush.task.task18.task1809; /* Реверс файла */ import java.io.*; import java.util.Stack; public class Solution { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String in1 = reader.readLine(); String in2 = reader.readLine(); FileInputStream in = new FileInputStream(in1); FileOutputStream out = new FileOutputStream(in2); Stack<Integer> stack = new Stack<>(); while (in.available() > 0) { int data = in.read(); stack.push(data);//добавляю в стек } while (!stack.isEmpty()) { out.write(stack.pop()); } in.close(); out.close(); reader.close(); } }
true
aac9ebf711d924b76bce42cf14aa4217f5e72bbe
Java
Aboud7/JSONPlaceHolder
/Documents/NetBeansProjects/Homework/src/homework/Thread3.java
UTF-8
757
3.046875
3
[]
no_license
package homework; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; public class Thread3 extends Thread { BlockingQueue queue; public Thread3(BlockingQueue q){ this.queue = q; } public synchronized void run(){ FileUtils f = null; for (int i = 0; i < 100; i++) { try { String s = (String) queue.pop(); f.appendStringToFile(s); } catch (IOException ex) { Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(Thread3.class.getName()).log(Level.SEVERE, null, ex); } } } }
true
e99b832884193b5d36e7f13822a3a298d9da4798
Java
poomoo/HomeOnLine
/app/src/main/java/com/poomoo/homeonline/ui/activity/CollectActivity.java
UTF-8
7,036
1.8125
2
[]
no_license
/** * # # * # _oo0oo_ # * # o8888888o # * # 88" . "88 # * # (| -_- |) # * # 0\ = /0 # * # ___/`---'\___ # * # .' \\| |# '. # * # / \\||| : |||# \ # * # / _||||| -:- |||||- \ # * # | | \\\ - #/ | | # * # | \_| ''\---/'' |_/ | # * # \ .-\__ '-' ___/-. / # * # ___'. .' /--.--\ `. .'___ # * # ."" '< `.___\_<|>_/___.' >' "". # * # | | : `- \`.;`\ _ /`;.`/ - ` : | | # * # \ \ `_. \_ __\ /__ _/ .-` / / # * # =====`-.____`.___ \_____/___.-`___.-'===== # * # `=---=' # * # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # * # # * # 佛祖保佑 永无BUG # * # # * Copyright (c) 2016. 跑马科技 Inc. All rights reserved. */ package com.poomoo.homeonline.ui.activity; import android.os.Bundle; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import com.poomoo.commlib.LogUtils; import com.poomoo.commlib.MyUtils; import com.poomoo.homeonline.R; import com.poomoo.homeonline.adapter.CollectionListAdapter; import com.poomoo.homeonline.adapter.base.BaseListAdapter; import com.poomoo.homeonline.presenters.CollectPresenter; import com.poomoo.homeonline.reject.components.DaggerActivityComponent; import com.poomoo.homeonline.reject.modules.ActivityModule; import com.poomoo.homeonline.ui.base.BaseListDaggerActivity; import com.poomoo.model.response.RCollectBO; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; /** * 类名 CollectActivity * 描述 收藏 * 作者 李苜菲 * 日期 2016/8/11 15:28 */ public class CollectActivity extends BaseListDaggerActivity<RCollectBO, CollectPresenter> implements BaseListAdapter.OnItemClickListener, CompoundButton.OnCheckedChangeListener { @Bind(R.id.chk_all_commodity) public CheckBox checkBox; private int count;//选中的数量 private List<RCollectBO> rCollectBOs; public boolean isClick = true;//是否是点击全选框 true-点击 false-适配器变化 public static CollectActivity inStance = null; private CollectionListAdapter adapter; private int[] indexes; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ButterKnife.bind(this); inStance = this; setBack(); mSwipeRefreshLayout.setEnabled(false); checkBox.setOnCheckedChangeListener(this); mAdapter.setOnItemClickListener(this); adapter = (CollectionListAdapter) mAdapter; mPresenter.getCollectionList(application.getUserId(), mCurrentPage); } @Override protected int onBindLayout() { return R.layout.activity_collect; } @Override protected int onSetTitle() { return R.string.title_collection; } @Override protected BaseListAdapter onSetupAdapter() { return new CollectionListAdapter(this, BaseListAdapter.ONLY_FOOTER); } @Override protected void setupActivityComponent(ActivityModule activityModule) { DaggerActivityComponent.builder() .activityModule(activityModule) .build() .inject(this); } @Override public void onRefresh() { super.onRefresh(); mCurrentPage = 1; mPresenter.getCollectionList(application.getUserId(), mCurrentPage); } @Override public void onLoadActiveClick() { super.onLoadActiveClick(); mCurrentPage = 1; mPresenter.getCollectionList(application.getUserId(), mCurrentPage); } @Override public void onLoading() { super.onLoading(); mPresenter.getCollectionList(application.getUserId(), mCurrentPage); } /** * 取消收藏 * * @param view */ public void cancelCollect(View view) { indexes = adapter.getIndexes(); count = indexes.length; if (count == 0) { MyUtils.showToast(getApplicationContext(), "没有选中收藏的商品"); return; } showDialog("确认删除这" + count + "个收藏的商品?"); } private void showDialog(String msg) { createDialog(msg, (dialog, which) -> { mPresenter.cancelCollections(((CollectionListAdapter) mAdapter).getIndexes()); }).show(); } public void getListSucceed(List<RCollectBO> rCollectBOs) { this.rCollectBOs = rCollectBOs; LogUtils.d(TAG, "getListSucceed:" + rCollectBOs.size()); setEmptyMsg("您还没有收藏任何商品"); onLoadResultData(rCollectBOs); } public void getListFailed(String msg) { if (isNetWorkInvalid(msg)) onNetworkInvalid(LOAD_MODE_DEFAULT); else onLoadErrorState(LOAD_MODE_DEFAULT); } public void cancelSucceed() { MyUtils.showToast(getApplicationContext(), "删除成功!"); isClick = false; checkBox.setChecked(false); adapter.clearIndexes(); mCurrentPage = 1; mPresenter.getCollectionList(application.getUserId(), mCurrentPage); } public void cancelFailed(String msg) { MyUtils.showToast(getApplicationContext(), msg); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isClick) if (isChecked) adapter.selectAll(); else adapter.cancelAll(); isClick = true; } @Override public void onItemClick(int position, long id, View view) { Bundle bundle = new Bundle(); bundle.putInt(getString(R.string.intent_commodityId), mAdapter.getItem(position).commodityId); bundle.putInt(getString(R.string.intent_commodityDetailId), mAdapter.getItem(position).commodityDetailId); bundle.putInt(getString(R.string.intent_commodityType), mAdapter.getItem(position).commodityType); if (mAdapter.getItem(position).commodityType == 4) //买赠 bundle.putInt(getString(R.string.intent_matchId), mAdapter.getItem(position).activityId);//match_id传activityId else { if (mAdapter.getItem(position).rushPurchaseId != null) bundle.putInt(getString(R.string.intent_matchId), mAdapter.getItem(position).rushPurchaseId); } openActivity(CommodityInfoActivity.class, bundle); } }
true
07ed3cfbd3e637f57bf93a511a497d5c53e45a6e
Java
AceInAndroid/Perfit
/app/src/main/java/com/mperfit/perfit/presenter/presenter/CourseDetailPresenterImpl.java
UTF-8
1,633
2.046875
2
[]
no_license
package com.mperfit.perfit.presenter.presenter; import android.content.Context; import com.mperfit.perfit.app.Constants; import com.mperfit.perfit.base.RxPresenter; import com.mperfit.perfit.model.bean.AddLikeBean; import com.mperfit.perfit.model.bean.CourseDetailBean; import com.mperfit.perfit.model.http.RetrofitHelper; import com.mperfit.perfit.presenter.contract.CourseDetailContract; import com.mperfit.perfit.utils.RxUtil; import javax.inject.Inject; import rx.Subscription; import rx.functions.Action1; /** * Created by zhangbing on 2016/11/23 */ public class CourseDetailPresenterImpl extends RxPresenter<CourseDetailContract.View> implements CourseDetailContract.Presenter{ private RetrofitHelper mRetrofitHelper; @Inject public CourseDetailPresenterImpl(RetrofitHelper mRetrofitHelper) { this.mRetrofitHelper = mRetrofitHelper; } @Override public void getCourseDetai(String courseId) { Subscription subscription = mRetrofitHelper.fetchCourseDetailInfo(courseId) .compose(RxUtil.<CourseDetailBean>rxSchedulerHelper()) .subscribe(new Action1<CourseDetailBean>() { @Override public void call(CourseDetailBean courseDetailBean) { mView.showContent(courseDetailBean); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { mView.showError(throwable.getMessage()); } }); addSubscrebe(subscription); } }
true
af05a3607bb5c726263a4045d83ddbbf4c87ef56
Java
lorenzotabasso/ASD-1617
/ex5/src/ex5/UnitTests.java
UTF-8
3,281
2.90625
3
[]
no_license
package ex5; /** * @author: Simone Stella (813905), Andrea Malgaroli (823429), Lorenzo Tabasso (812499) */ import java.util.*; import org.junit.*; import org.junit.runner.*; import org.junit.runner.notification.Failure; import static org.junit.Assert.*; public class UnitTests { // SETTINGS ---------------------------------------------------------------- private String csvPath = "/Users/simonestella/Desktop/ex5/italian_dist_graph.csv"; // ------------------------------------------------------------------------- public static void main (String[] args) { Result result = JUnitCore.runClasses(UnitTests.class); for (Failure failure : result.getFailures()){ System.out.println(failure.toString()); } System.out.println("\nResult: " + result.wasSuccessful()); } @Test public void addUnitTest() { OrientedGraph g = new OrientedGraph(); assertTrue (g.adjacencyList.isEmpty()); g.add("Roma"); assertTrue(g.adjacencyList.size() == 1); assertTrue(g.adjacencyList.containsKey("Roma")); g.add("Firenze"); assertTrue(g.adjacencyList.size() == 2); assertTrue(g.adjacencyList.containsKey("Firenze")); g.add("Torino", "Milano", 100000); assertTrue(g.adjacencyList.size() == 4); assertTrue(g.adjacencyList.containsKey("Torino")); assertTrue(g.adjacencyList.containsKey("Milano")); assertTrue(g.adjacencyList.get("Torino").size() == 1 && g.EdgesNumber == 1); assertTrue(g.adjacencyList.get("Torino").toString().contains("Milano (100.0km)")); g.add("Firenze", "Genova", 200000); assertTrue(g.adjacencyList.size() == 5); assertTrue(g.adjacencyList.containsKey("Genova")); assertTrue(g.adjacencyList.get("Firenze").size() == 1 && g.EdgesNumber == 2); assertTrue(g.adjacencyList.get("Firenze").toString().contains("Genova (200.0km)")); System.out.println("UnitTest of 'add' completed."); } @Test public void weightUnitTest() { OrientedGraph g = new OrientedGraph(); assertTrue (g.weight() == 0); g.add("Torino", "Milano", 100000); assertTrue (g.weight() == 100000); g.add("Milano", "Firenze", 250000); g.add("Firenze", "Genova", 200000); g.add("Genova", "Torino", 120000); assertTrue (g.weight() == (100000 + 250000 + 200000 + 120000)); System.out.println("UnitTest of 'weight' completed."); } @Test public void mstUnitTest() { OrientedGraph g1 = new OrientedGraph(); g1.add("Torino", "Milano", 100000); OrientedGraph mst1 = Mst.Kruscal(g1); assertTrue (g1.VerticesNumber == mst1.VerticesNumber); assertTrue (g1.EdgesNumber == mst1.EdgesNumber); assertTrue (g1.weight() == mst1.weight()); OrientedGraph g2 = Csv.read(csvPath, ","); OrientedGraph mst2 = Mst.Kruscal(g2); assertTrue (g2.VerticesNumber == mst2.VerticesNumber && mst2.VerticesNumber == 18640); assertTrue (mst2.EdgesNumber == 18637); float mst2Weight = mst2.weight()/1000; assertTrue ((mst2Weight - 89939.913) < 10 || (mst2Weight - 89939.913) > -10); System.out.println("UnitTest of 'mst' completed."); } }
true
2cfe4af07e67d358e37b119b0a43ce733d9e8ffe
Java
eclab/flow
/flow/modules/Swap.java
UTF-8
3,658
2.921875
3
[ "Apache-2.0" ]
permissive
// Copyright 2018 by George Mason University // Licensed under the Apache 2.0 License package flow.modules; import flow.*; /** A Unit which swaps its partials with nearby partials. The meaning of "nearby" depends on a modulation ("distance"). You have the option swapping the fundamental or keeping it out of the process. The modulation doesn't have to be a integral value -- if the distance is "in-between" partials, then partials are smoothly mixed. */ public class Swap extends Unit { private static final long serialVersionUID = 1; public static final int MOD_DISTANCE = 0; boolean swapFundamental; public boolean getSwapFundamental() { return swapFundamental; } public void setSwapFundamental(boolean val) { swapFundamental = val; } public static final int OPTION_SWAP_FUNDAMENTAL = 0; public int getOptionValue(int option) { switch(option) { case OPTION_SWAP_FUNDAMENTAL: return getSwapFundamental() ? 1 : 0; default: throw new RuntimeException("No such option " + option); } } public void setOptionValue(int option, int value) { switch(option) { case OPTION_SWAP_FUNDAMENTAL: setSwapFundamental(value != 0); return; default: throw new RuntimeException("No such option " + option); } } public Swap(Sound sound) { super(sound); defineInputs( new Unit[] { Unit.NIL }, new String[] { "Input" }); defineModulations(new Constant[] { Constant.ZERO }, new String[] { "Distance" }); defineOptions(new String[] { "Fundamental" }, new String[][] { { "Fundamental" } } ); setSwapFundamental(false); } double[] amp2 = new double[NUM_PARTIALS]; public void go() { super.go(); pushFrequencies(0); copyAmplitudes(0); double[] amplitudes = getAmplitudes(0); double val = modulate(MOD_DISTANCE) * (amplitudes.length - (swapFundamental ? 1 : 2)) + 1; int swap = (int)val; double by = val - swap; int start = 1; if (swapFundamental) start = 0; // I don't think I should be swapping orders here.... for(int i = start; i < amplitudes.length; i += swap) { for(int j = 0; j < swap / 2; j++) { if (i + swap - j - 1 < amplitudes.length) { double temp = amplitudes[i + j]; amplitudes[i + j] = amplitudes[i + swap - j - 1]; amplitudes[i + swap - j - 1] = temp; } } } if (swap != NUM_PARTIALS) { swap++; System.arraycopy(getAmplitudes(0), 0, amp2, 0, amp2.length); for(int i = start; i < amp2.length; i += swap) { for(int j = 0; j < swap / 2; j++) { if (i + swap - j - 1 < amp2.length) { double temp = amp2[i + j]; amp2[i + j] = amp2[i + swap - j - 1]; amp2[i + swap - j - 1] = temp; } } } } for(int i = start; i < amplitudes.length; i++) { amplitudes[i] = (1.0 - by) * amplitudes[i] + by * amp2[i]; } constrain(); } }
true
e1652804d03d00c60b0b3436b85b1e13f3475859
Java
mariocervera/DatabaseEditor
/DEPENDENCIES/es.cv.gvcase.mdt.common/src/es/cv/gvcase/mdt/common/provider/MOSKittAbstractSourceProvider.java
UTF-8
1,390
1.859375
2
[]
no_license
/******************************************************************************* * Copyright (c) 2011 Conselleria de Infraestructuras y Transporte, Generalitat * de la Comunitat Valenciana. All rights reserved. This program * and the accompanying materials are made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Marc Gil Sendra (Prodevelop) [mgil@prodevelop.es] - initial API implementation ******************************************************************************/ package es.cv.gvcase.mdt.common.provider; import java.util.HashMap; import java.util.Map; import org.eclipse.ui.AbstractSourceProvider; /** * This class is a Source Provider for MOSKitt that allow to create Services to * get any value. When another service is created using this class, a new ID * should be added, and subClasses should use this new ID. * * @author <a href="mailto:mgil@prodevelop.es">Marc Gil Sendra</a> */ public abstract class MOSKittAbstractSourceProvider extends AbstractSourceProvider { public final static String STORAGE_SERVICE_ID = "es.cv.gvcase.mdt.common.storage.service"; public void dispose() { } public Map getCurrentState() { Map map = new HashMap(); return map; } /** * Get the desired values for this Service */ public abstract Object getValues(); }
true
57840d874f179c4ab6a99a069ca2cef8fed434d2
Java
guicara/Spring-Boot-Demo_Handball-tournaments
/src/main/java/com/esaip/springboot/handball/entities/Team.java
UTF-8
1,510
2.703125
3
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
package com.esaip.springboot.handball.entities; import javax.persistence.*; /** * An entity class which contains the information of a single team. * * @author Guillaume MOREL-BAILLY */ @Entity @Table(name = "teams") public class Team { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Long id; @Column(name = "name", length = 255, nullable = false, unique = true) private String name; @Column(name = "description", length = 1000, nullable = true) private String description; @Column(name = "path_logo", nullable = true) private String pathLogo; public Team() { } public Team(String name, String description) { this.name = name; this.description = description; } public Team(String name, String description, String pathLogo) { this.name = name; this.description = description; this.pathLogo = pathLogo; } 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 String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPathLogo() { return pathLogo; } public void setPathLogo(String pathLogo) { this.pathLogo = pathLogo; } }
true
8ddd9fa28939dc0436d01773a2702856e0edd09a
Java
JHawanetFramework/JHawanetFramework
/src/main/java/annotations/registrable/NewProblem.java
UTF-8
706
2.578125
3
[]
no_license
package annotations.registrable; import registrable.Registrable; import java.lang.annotation.*; /** * This class is used to indicate the name to problem that the class that inherit of {@link Registrable} set up. * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.CONSTRUCTOR) @Documented public @interface NewProblem { /** * Problem name. It is used as a category name in the GUI. * @return the name of algorithm */ String displayName() default ""; /** * Algorithm name. * @return the name of algorithm used to solve the problem */ String algorithmName() default ""; /** * Description of problem. * @return the description */ String description() default ""; }
true
7165fb074ec7b198b02484db14b285e4931c3614
Java
VladimirSerdyuk/Hi-Tech_Webstore
/hitech.webstore/src/main/java/ru/geekbrains/hitech/webstore/services/ItemService.java
UTF-8
1,965
2.359375
2
[]
no_license
package ru.geekbrains.hitech.webstore.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import ru.geekbrains.hitech.webstore.entities.Item; import ru.geekbrains.hitech.webstore.repositories.ItemRepository; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class ItemService { private ItemRepository itemRepository; @Autowired public void setItemRepository(ItemRepository itemRepository) { this.itemRepository = itemRepository; } public Optional<Item> findById(Long id){ return itemRepository.findById(id); } // 1-й вариант реализации метода findItemsByCategory // public List<Item> findItemsByCategory(String category){ // List<Item> filteredItems = new ArrayList<>(); // List <Item> items = itemRepository.findAll(); // for (Item item : items){ // if (category.equals(item.getCategory())){ // filteredItems.add(item); // } // } // return filteredItems; // } public List<Item> findItemsByCategory(String category){ return itemRepository.findAllByCategory(category); } public Page<Item> findAll(int page, int pageSize, Specification<Item> specification) { return itemRepository.findAll(specification, PageRequest.of(page, pageSize, Sort.Direction.ASC, "id")); } public Item add(Item item){ return itemRepository.save(item); } public void deleteById(Long id){ itemRepository.deleteById(id); } public void delete(Item item){ itemRepository.delete(item); } }
true
40f32f79a0c02b3e53994ab2410b4752fa320041
Java
krittikachhabra/timetabling
/src/TimeTable/MMAs.java
UTF-8
3,969
2.734375
3
[]
no_license
package TimeTable; import java.io.IOException; import java.io.PrintStream; public class MMAs { public static void main(String args[])throws IOException { int n_of_ants = Definitions.DEFAULT_N_OF_ANTS; Ant[] ant = new Ant[n_of_ants]; double pheromone_evaporation = Definitions.DEFAULT_PHEROMONE_EVAPORATION; double minimal_pheromone = Definitions.DEFAULT_MINIMAL_PHEROMONE; MMAsProblem problem = new MMAsProblem(pheromone_evaporation, minimal_pheromone); Control control = new Control(); Solution best_solution = new Solution(problem); int cnt = 1; while (control.triesLeft()) { System.out.println("try :" + cnt); cnt++; control.beginTry(); problem.pheromoneReset(); best_solution.RandomInitialSolution(); best_solution.computeFeasibility(); control.setCurrentCost(best_solution); long startTime = System.currentTimeMillis(); while ((System.currentTimeMillis() - startTime) < 60*1000) { for (int i=0;i<n_of_ants;i++) { ant[i] = new Ant(problem); ant[i].start(); try { ant[i].join(); } catch(Exception e) { e.printStackTrace(); } // ant[i].run(); } problem.evaporatePheromone(); int best_fitness = 99999; int ant_idx = -1; for (int i=0;i<n_of_ants;i++) { int fitness = ant[i].computeFitness(); if (fitness<best_fitness) { best_fitness = fitness; ant_idx = i; } } /*System.out.println("before local search idx = " + ant_idx); control.computeHCV(ant[ant_idx].solution);*/ /* for(int i = 0 ; i < ant[ant_idx].solution.data.n_of_events ; i++) { if(sln.elementAt(i).second == -1) counter = counter + 1; else System.out.println("Event = "+i+" Time = "+sln.elementAt(i).first+ " Room = "+sln.elementAt(i).second); }*/ System.out.println("Be LS Room = "); ant[ant_idx].solution.localSearch(Integer.MAX_VALUE,120); ant[ant_idx].solution.computeFeasibility(); if (ant[ant_idx].solution.feasible) { ant[ant_idx].solution.computeScv(); if (ant[ant_idx].solution.scv<=best_solution.scv) { best_solution.copy(ant[ant_idx].solution); best_solution.hcv = 0; control.setCurrentCost(best_solution); } } else { ant[ant_idx].solution.computeHCV(); if (ant[ant_idx].solution.hcv<=best_solution.hcv) { best_solution.copy(ant[ant_idx].solution); control.setCurrentCost(best_solution); best_solution.scv = Integer.MAX_VALUE; } } Solution tmp_solution = ant[ant_idx].solution; ant[ant_idx].solution = best_solution; problem.pheromoneMinMax(); ant[ant_idx].computeFitness(); ant[ant_idx].depositPheromone(); ant[ant_idx].solution = tmp_solution; } control.endTry(best_solution); } } }
true
70e2faf713ca52e9270588a65425127a8a8b92dd
Java
zouqinjia/design-pattern
/src/com/vince/demo/adapter/classadapter/outeruser/IOuterUserHomeInfo.java
UTF-8
162
1.664063
2
[]
no_license
package com.vince.demo.adapter.classadapter.outeruser; import java.util.Map; public interface IOuterUserHomeInfo { Map<String,String> getUserHomeInfo(); }
true
5daf0a1a6a3509062d2721700ab0d27fc8bfd1c0
Java
CPIOC/Logistics
/logistics/src/main/java/com/cpic/taylor/logistics/RongCloudModel/FriendApplyData.java
UTF-8
1,034
2.171875
2
[]
no_license
package com.cpic.taylor.logistics.RongCloudModel; /** * Created by hui on 2016/5/14. */ public class FriendApplyData { private String name; private String id; private String img; private String cloud_id; @Override public String toString() { return "FriendApplyData{" + "name='" + name + '\'' + ", id='" + id + '\'' + ", img='" + img + '\'' + ", cloud_id='" + cloud_id + '\'' + '}'; } public String getCloud_id() { return cloud_id; } public void setCloud_id(String cloud_id) { this.cloud_id = cloud_id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } }
true
dbb6baca62041ff7bd94cd85fc58c42666bcc75d
Java
HanielDorton/Shooter
/core/src/com/haniel/Shooter/util/GameState.java
UTF-8
1,360
2.59375
3
[]
no_license
package com.haniel.Shooter.util; public class GameState { public int numContinues, checkPoint, numLevel, score, numSkips; //public int [] scores = {0, 0, 0, 0, 0}; //public int [] levelMaxes ={1060,1100,750,1300,980}; public int [] level1checkPoints = {0, 4290, 9190, 13990}; public int [] level2checkPoints = {0, 6890, 10790, 18390}; public int [] level3checkPoints = {0, 5940, 11490}; public int [] level4checkPoints = {0, 4990, 13590}; public int [] level5checkPoints = {0, 5090, 13890, 20990}; public GameState(int numLevel, int checkPoint, int numContinues) { this.numContinues = numContinues; this.checkPoint = checkPoint; this.numLevel = numLevel; } public int getCheckpoint() { switch (numLevel) { case 2: { return level2checkPoints[checkPoint]; } case 3: { return level3checkPoints[checkPoint]; } case 4: { return level4checkPoints[checkPoint]; } case 5: { return level5checkPoints[checkPoint]; } default: { return level1checkPoints[checkPoint]; } } } public int[] getCheckpoints(int numLevel) { switch (numLevel) { case 2: { return level2checkPoints; } case 3: { return level3checkPoints; } case 4: { return level4checkPoints; } case 5: { return level5checkPoints; } default: { return level1checkPoints; } } } }
true
ea4736aeec28991cb93354be89507c72cde014d3
Java
iteam-msse/busbuddy
/src/main/java/edu/umn/msse/busbuddy/alert/service/ScheduleAlertExecuteStrategy.java
UTF-8
1,190
2.453125
2
[]
no_license
package edu.umn.msse.busbuddy.alert.service; import org.springframework.beans.factory.annotation.Autowired; import edu.umn.msse.busbuddy.alert.client.AlertUserClient; import edu.umn.msse.busbuddy.alert.domain.AlertRepository; import edu.umn.msse.busbuddy.alert.domain.model.Alert; /** * A concrete implementation of {@link IAlertExecuteStrategy} that handles executing alert related to user's regular * schedule. */ public class ScheduleAlertExecuteStrategy implements IAlertExecuteStrategy { /** * An instance of {@link alert.domain.AlertRepository} that is used to fetch alerts. This is autowired via Spring Framework. */ @Autowired AlertRepository alertRepository; /** * A spring autowired instance of {@link alert.client.AlertUserClient} that can call the User module to get user information. * This is autowired via Spring Framework. */ @Autowired AlertUserClient userClient; /** * For each passed in alert, it pushes notification to the user informing about their upcoming trip and routes (as * they have scheduled in the first place) */ @Override public boolean execute(Alert alertModel) { // TODO Auto-generated method stub return false; } }
true
f288af190c86d385b42756f37d5edfdd3f4534b5
Java
whram/java-web
/servlet2/src/com/response/Demo.java
UTF-8
990
2.65625
3
[]
no_license
package com.response; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /* * Response对象 * 功能:设置响应消息 1. 设置响应行 1. 格式:HTTP/1.1 200 ok 2. 设置状态码:setStatus(int sc) 2. 设置响应头:setHeader(String name, String value) 3. 设置响应体: * 使用步骤: 1. 获取输出流 * 字符输出流:PrintWriter getWriter() * 字节输出流:ServletOutputStream getOutputStream() 2. 使用输出流,将数据输出到客户端浏览器 * */ public class Demo extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }
true
4023a4a756af2e32a1334c0938f7c5cc36478d14
Java
mannprerak2/EventHub
/app/src/main/java/com/pkmnapps/eventsdtu/MyFirebaseMessagingService.java
UTF-8
2,647
2.0625
2
[]
no_license
package com.pkmnapps.eventsdtu; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.v4.app.NotificationCompat; import android.widget.Toast; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; /** * Created by prerak on 16/4/18. */ public class MyFirebaseMessagingService extends FirebaseMessagingService { String CHANNEL_ID = "channelId"; String contentTitle,contentText; @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); if(remoteMessage.getNotification()!=null) { contentTitle = remoteMessage.getNotification().getTitle(); contentText = remoteMessage.getNotification().getBody(); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, SplashActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_check_white_24dp) .setContentTitle(contentTitle) .setContentText(contentText) .setStyle(new NotificationCompat.BigTextStyle() .bigText(contentText)) .setContentIntent(contentIntent) .setPriority(NotificationCompat.PRIORITY_DEFAULT); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library CharSequence name = CHANNEL_ID; String description = "description"; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_DEFAULT); channel.setDescription(description); // Register the channel with the system if(notificationManager!=null) notificationManager.createNotificationChannel(channel); } if(notificationManager != null) notificationManager.notify(1, mBuilder.build()); } } }
true
5e709c298a639caa9edba6125b9dd36e090c6fd4
Java
jinhyun/tutorialLand
/querydsl-jpa/src/main/java/tutorialLand/cooking/domain/CookMaterial.java
UTF-8
1,755
2.640625
3
[]
no_license
package tutorialLand.cooking.domain; import javax.persistence.*; import java.util.ArrayList; import java.util.List; @Entity public class CookMaterial { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "COOK_MATERIAL_UID") private long uid; @Column(name = "COOK_QUANTITY") private int quantity; @Column(name = "MATERIAL_NAME") private String materialName; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "COOK_UID") private Cook cook; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "MATERIAL_UID") private Material material; public String getMaterialName() { return materialName; } public void setMaterialName(String materialName) { this.materialName = materialName; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public long getUid() { return uid; } public Cook getCook() { return cook; } public void setCook(Cook cook) { this.cook = cook; } public Material getMaterial() { return material; } public void setMaterial(Material material) { this.material = material; } public static List<CookMaterial> createCookMaterials(List<Material> materials) { List<CookMaterial> cookMaterials = new ArrayList<CookMaterial>(); for (Material material : materials){ CookMaterial cookMaterial = new CookMaterial(); cookMaterial.setMaterialName(material.getName()); cookMaterial.setMaterial(material); cookMaterials.add(cookMaterial); } return cookMaterials; } }
true
46423b3a43a18e7c3056331b910b246195d4169b
Java
ujjvalkumar18/Selenium-Java-Practise
/Java/src/String/ReverseSentence.java
UTF-8
340
3
3
[]
no_license
package String; public class ReverseSentence { public static void main(String[] args) { // TODO Auto-generated method stub String[] s= "He is the one".split(" "); String finalStr=""; for(int i = s.length-1; i>=0 ;i--){ finalStr=finalStr+s[i]+" "; } System.out.println(finalStr); } }
true
b9c659d38714e73a5c26cae308d14a8d880b985a
Java
Ahmed-Moustafa-Kamel/Educational
/src/Student.java
UTF-8
461
2.9375
3
[]
no_license
public class Student extends Person { private int id; private Subject[] courses; public Subject[] getCourses() { return courses; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int totalGrade(){ int totalGrade=0; for(int i=0; i< courses.length;i++) totalGrade=totalGrade + courses[i].getGrade(); return totalGrade; } }
true
6cbbd61d9a9aab68e05093d41e7a793979792c6a
Java
wenerme/jss
/src/main/java/jss/proto/packet/OK_Packet.java
UTF-8
2,103
2.484375
2
[]
no_license
package jss.proto.packet; import io.netty.buffer.ByteBuf; import jss.proto.util.Dumper; import jss.proto.util.Stringer; /** * An OK packet is sent from the server to the client to signal successful completion of a command. * <p/> * If CLIENT_PROTOCOL_41 is set, the packet contains a warning count. * <pre> * <b>Payload</b> * Type Name Description * int&lt;1> header [00] the OK packet header * int&lt;lenenc> affected_rows affected rows * int&lt;lenenc> last_insert_id last insert-id * if capabilities & CLIENT_PROTOCOL_41 { * int&lt;2> status_flags Status Flags * int&lt;2> warnings number of warnings * } elseif capabilities & CLIENT_TRANSACTIONS { * int&lt;2> status_flags Status Flags * } * if capabilities & CLIENT_SESSION_TRACK { * string&lt;lenenc> info human readable status information * if status_flags & SERVER_SESSION_STATE_CHANGED { * string&lt;lenenc> session_state_changes session state info * } * } else { * string&lt;EOF> info human readable status information * } * <b>Example</b> * OK with CLIENT_PROTOCOL_41. 0 affected rows, last-insert-id was 0, AUTOCOMMIT, 0 warnings. No further info. * * 07 00 00 02 00 00 00 02 00 00 00 * ........... * </pre> * * @see <a href=http://dev.mysql.com/doc/internals/en/packet-OK_Packet.html>OK_Packet</a> */ public class OK_Packet implements Packet { public byte header = 0; public long affectedRows = 0; public long lastInsertId = 0; public long statusFlags = 0; public long warnings = 0; public ByteBuf info; public ByteBuf sessionStateChanges; @Override public String toString() { return "OK_Packet{" + "header=" + header + ", affectedRows=" + affectedRows + ", lastInsertId=" + lastInsertId + ", statusFlags=" + statusFlags + ", warnings=" + warnings + ", info=" + Stringer.string(info) + ", sessionStateChanges=" + Dumper.dump(sessionStateChanges) + '}'; } }
true
60728d3e7d7930c570ae7cf6b8e5dcb4d1b3a347
Java
happyWinner/SportsBuddy
/app/src/main/java/com/qianchen/sportsbuddy/LoginActivity.java
UTF-8
12,235
2.109375
2
[]
no_license
package com.qianchen.sportsbuddy; import android.app.Activity; import android.app.LoaderManager.LoaderCallbacks; import android.content.BroadcastReceiver; import android.content.CursorLoader; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.provider.ContactsContract; import android.text.TextUtils; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.parse.GetCallback; import com.parse.LogInCallback; import com.parse.Parse; import com.parse.ParseException; import com.parse.ParseQuery; import com.parse.ParseUser; import java.util.ArrayList; import java.util.List; /** * A login screen that offers login via email/password. * * Created by Qian Chen on 7/28/2014. */ public class LoginActivity extends Activity implements LoaderCallbacks<Cursor>{ /** * Keep track of the login task to ensure we can cancel it if requested. */ private UserLoginTask mAuthTask = null; // UI references. private AutoCompleteTextView mEmailView; private EditText mPasswordView; public static BroadcastReceiver broadcastReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // authenticates this client to Parse Parse.initialize(this, getString(R.string.application_id), getString(R.string.client_key)); // hide the soft keyboard getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); // register a touch listener to the layout ((LinearLayout) findViewById(R.id.layout_login)).setOnTouchListener(new TouchListener()); // set up the login form. mEmailView = (AutoCompleteTextView) findViewById(R.id.email); populateAutoComplete(); mPasswordView = (EditText) findViewById(R.id.password); mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { if (id == R.id.login || id == EditorInfo.IME_NULL) { attemptLogin(); return true; } return false; } }); Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button); mEmailSignInButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { hideSoftInput(); attemptLogin(); } }); Button mRegisterButton = (Button) findViewById(R.id.register_button); mRegisterButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getApplicationContext(), RegisterActivity.class)); } }); } private class TouchListener implements View.OnTouchListener { public boolean onTouch(View view, MotionEvent motionEvent) { // hide the soft keyboard when the background is touched hideSoftInput(); return true; } } private void hideSoftInput() { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); } private void populateAutoComplete() { getLoaderManager().initLoader(0, null, this); } /** * Attempts to sign in the account specified by the login form. * If there are form errors (invalid email, missing fields, etc.), the * errors are presented and no actual login attempt is made. */ public void attemptLogin() { if (mAuthTask != null) { return; } // reset errors. mEmailView.setError(null); mPasswordView.setError(null); // store values at the time of the login attempt. String email = mEmailView.getText().toString(); String password = mPasswordView.getText().toString(); boolean cancel = false; View focusView = null; // check for a valid password, if the user entered one. if (TextUtils.isEmpty(password)) { mPasswordView.setError(getString(R.string.error_invalid_password)); focusView = mPasswordView; cancel = true; } // check for a valid email address. if (TextUtils.isEmpty(email)) { mEmailView.setError(getString(R.string.error_field_required)); focusView = mEmailView; cancel = true; } else if (!isEmailValid(email)) { mEmailView.setError(getString(R.string.error_invalid_email)); focusView = mEmailView; cancel = true; } if (cancel) { // There was an error; don't attempt login and focus the first // form field with an error. focusView.requestFocus(); } else { // Show a progress spinner, and kick off a background task to // perform the user login attempt. mAuthTask = new UserLoginTask(email, password); mAuthTask.execute((Void) null); } } private boolean isEmailValid(String email) { return email.matches("[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+\\.[a-zA-Z]{2,4}"); } @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { return new CursorLoader(this, // Retrieve data rows for the device user's 'profile' contact. Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, // Select only email addresses. ContactsContract.Contacts.Data.MIMETYPE + " = ?", new String[]{ContactsContract.CommonDataKinds.Email .CONTENT_ITEM_TYPE}, // Show primary email addresses first. Note that there won't be // a primary email address if the user hasn't specified one. ContactsContract.Contacts.Data.IS_PRIMARY + " DESC"); } @Override public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { List<String> emails = new ArrayList<String>(); cursor.moveToFirst(); while (!cursor.isAfterLast()) { emails.add(cursor.getString(ProfileQuery.ADDRESS)); cursor.moveToNext(); } addEmailsToAutoComplete(emails); } @Override public void onLoaderReset(Loader<Cursor> cursorLoader) { } private interface ProfileQuery { String[] PROJECTION = { ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.IS_PRIMARY, }; int ADDRESS = 0; int IS_PRIMARY = 1; } private void addEmailsToAutoComplete(List<String> emailAddressCollection) { //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list. ArrayAdapter<String> adapter = new ArrayAdapter<String>(LoginActivity.this, android.R.layout.simple_dropdown_item_1line, emailAddressCollection); mEmailView.setAdapter(adapter); } /** * Represents an asynchronous login/registration task used to authenticate * the user. */ public class UserLoginTask extends AsyncTask<Void, Void, Void> { private final String mEmail; private final String mPassword; private boolean success; UserLoginTask(String email, String password) { mEmail = email; mPassword = password; } @Override protected Void doInBackground(Void... params) { ParseQuery<ParseUser> query = ParseUser.getQuery(); query.whereEqualTo("email", mEmail); query.getFirstInBackground(new GetCallback<ParseUser>() { public void done(ParseUser user, ParseException e) { if (user == null) { // incorrect email address exceptionHandler(e, getString(R.string.error_incorrect_email_password)); } else { ParseUser.logInInBackground(user.getUsername(), mPassword, new LogInCallback() { public void done(ParseUser user, ParseException e) { if (user != null) { // check whether the user has verified his email address ParseQuery<ParseUser> query = ParseUser.getQuery(); query.whereEqualTo("email", mEmail); query.whereEqualTo("emailVerified", true); query.getFirstInBackground(new GetCallback<ParseUser>() { public void done(ParseUser user, ParseException e) { if (user != null) { // Hooray! The user is logged in. startActivity(new Intent(getApplicationContext(), MainActivity.class)); finish(); } else { exceptionHandler(e, getString(R.string.error_unverified_email)); } } }); } else { // Signup failed. Look at the ParseException to see what happened. exceptionHandler(e, getString(R.string.error_incorrect_email_password)); } } }); } } }); return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); mAuthTask = null; } @Override protected void onCancelled() { mAuthTask = null; } private void exceptionHandler(ParseException e, String objNotFoundMessage) { switch (e.getCode()) { case ParseException.INTERNAL_SERVER_ERROR: Toast.makeText(getApplicationContext(), getString(R.string.error_internal_server), Toast.LENGTH_LONG).show(); break; case ParseException.CONNECTION_FAILED: Toast.makeText(getApplicationContext(), getString(R.string.error_connection_failed), Toast.LENGTH_LONG).show(); break; case ParseException.TIMEOUT: Toast.makeText(getApplicationContext(), getString(R.string.error_timeout), Toast.LENGTH_LONG).show(); break; case ParseException.OBJECT_NOT_FOUND: Toast.makeText(getApplicationContext(), objNotFoundMessage, Toast.LENGTH_LONG).show(); break; default: Toast.makeText(getApplicationContext(), getString(R.string.error_general), Toast.LENGTH_LONG).show(); break; } } } }
true
1f5619a1a6e6fc7175969b082458a4d6de02edc0
Java
SWE2-2020-8/NewBank
/server/test/BankTests.java
UTF-8
3,956
2.65625
3
[]
no_license
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import com.azure.cosmos.models.CosmosContainerProperties; import com.azure.cosmos.models.CosmosQueryRequestOptions; import com.azure.cosmos.util.CosmosPagedIterable; import org.junit.Test; public class BankTests { @Test public void authenticateTest() { NewBank bank = NewBank.getBank(); assertNotNull(bank.checkLogInDetails("Christina", "lol")); } @Test public void loadBankCustomersTest() { List<CustomerRecord> retrieved = BankCosmosDb.getContainerIdentity() .queryItems("SELECT * FROM c", new CosmosQueryRequestOptions(), CustomerRecord.class) .stream() .collect(Collectors.toList()); retrieved.forEach( cr -> System.err.println(cr.getId() + "/" + cr.getPassword())); assertTrue(retrieved.size() > 0); } @Test public void containersExistTest() { CosmosPagedIterable<CosmosContainerProperties> listContainers = BankCosmosDb .retrieveAllContainers(); List<String> listIds = listContainers.stream() .map(CosmosContainerProperties::getId) .collect(Collectors.toList()); System.err.println(listIds); assertTrue(listIds.contains(BankCosmosDb.CONTAINER_ACCOUNTS)); assertTrue(listIds.contains(BankCosmosDb.CONTAINER_IDENTITY)); } @Test public void addRandomAccountToRandomCustomerTest() { Random random = new Random(); BankCosmosDb.loadBankCustomers(); Object[] arrayCust = Customer.getAllCustomersList().toArray(); Customer chosenCustomer = (Customer) arrayCust[random .nextInt(arrayCust.length)]; System.err.println("Found " + chosenCustomer.getUserName()); Account newAccount = chosenCustomer.addAccount( "Testaccount" + random.nextInt(99), +random.nextInt(9999)); BankCosmosDb.createAccountDocument(newAccount); assertTrue(chosenCustomer.getAccounts().contains(newAccount)); } @Test public void addRandomTransactionToRandomAccountToRandomCustomerTest() { Random random = new Random(); BankCosmosDb.loadBankCustomers(); BankCosmosDb.loadBankAccounts(); // get a random customer Object[] arrayCust = Customer.getAllCustomersList().toArray(); Customer chosenCustomer = (Customer) arrayCust[random .nextInt(arrayCust.length)]; System.err.println("Found " + chosenCustomer.getUserName()); // get a random account Object[] arrayAcc = chosenCustomer.getAccounts().toArray(); if (arrayAcc.length == 0) System.err.println( "Sorry, just selected a user with no accounts, test screwed"); Account chosenAccount = (Account) arrayAcc[random .nextInt(arrayAcc.length)]; System.err.println("Found " + chosenAccount.getAccountName()); // make a new transaction Double amount = (double) Math.round(random.nextDouble() * 1000); chosenAccount.newTransaction(amount, "Random transaction " + Double.toString(amount)); BankCosmosDb.replaceAccountDocument(chosenAccount); assertTrue(chosenAccount.getTransactions() .stream() .anyMatch(transaction -> transaction.getAmount() == amount)); } @Test public void loadUsersAndAccountsTest() { BankCosmosDb.loadBankCustomers(); BankCosmosDb.loadBankAccounts(); // Assumes there's a customer named Christina and that she has accounts assertNotNull(Customer.getCustomerByName("Christina")); assertNotNull(Customer.getCustomerByName("Christina").getAccounts()); } }
true
7580ed9a65b06ef5d050638b5ccca11d4479c885
Java
tongkaochen/tdev-demo
/app/src/main/java/com/tifone/tdev/demo/fm/channel/SlideIndicator.java
UTF-8
3,484
2.296875
2
[]
no_license
package com.tifone.tdev.demo.fm.channel; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import com.tifone.tdev.demo.R; import java.util.ArrayList; import java.util.List; public class SlideIndicator extends FrameLayout{ private static final int ANIMATION_DURATION = 1000; private View mIndicatorItem; private List<Item> items = new ArrayList<>(); private float currentLocation; private int currentWidth; public SlideIndicator(@NonNull Context context) { this(context, null); } public SlideIndicator(@NonNull Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public SlideIndicator(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { View indicatorLayout = LayoutInflater.from(getContext()) .inflate(R.layout.indicator_layout, this); mIndicatorItem = indicatorLayout.findViewById(R.id.indicator_item); } public void locationChanged(int from, int to) { Item fromItem = items.get(from); Item toItem = items.get(to); if (fromItem == null || toItem == null) { return; } ObjectAnimator animator = ObjectAnimator.ofFloat(mIndicatorItem, "translationX", currentLocation, toItem.start); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { currentLocation = (float) animation.getAnimatedValue(); } }); animator.setDuration(ANIMATION_DURATION); animator.start(); ValueAnimator widthAnimation = ValueAnimator.ofInt(currentWidth, toItem.width); widthAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int width = (Integer) animation.getAnimatedValue(); setIndicatorWidth(width); currentWidth = width; } }); widthAnimation.setDuration(ANIMATION_DURATION); widthAnimation.start(); } public void setData(List<Item> headerItems) { items = headerItems; } private void setIndicatorWidth(int width) { final ViewGroup.LayoutParams params = mIndicatorItem.getLayoutParams(); params.width = width; mIndicatorItem.setLayoutParams(params); } public int size() { return items.size(); } public void currentPosition(int position) { Item currentItem = items.get(position); mIndicatorItem.setTranslationX(currentItem.start); currentLocation = currentItem.start; setIndicatorWidth(currentItem.width); currentWidth = currentItem.width; } static class Item { float start; float end; int width; Item(float start, float end, int width) { this.start = start; this.end = end; this.width = width; } } }
true
5f71d28986440b58947004aed4f26250b615fb29
Java
itprwe/codehome
/javabase/src/my/prwe/oo/TestInterface.java
UTF-8
859
3.125
3
[]
no_license
package my.prwe.oo; //12 public class TestInterface { public static void main(String[] args) { Volant v = new Angle(); v.fly(); // v.helpOther();//编译器不知道 Honest h = new GoodMan(); h.helpOther(); } } interface Volant{ int FLY_HEIGHT = 1111; void fly(); } interface Honest{ void helpOther(); } class Angle implements Volant,Honest{ @Override public void fly() { System.out.println("Volant.fly()"); } @Override public void helpOther() { System.out.println("Anlgle.helpOther()"); } } class GoodMan implements Honest{ @Override public void helpOther() { System.out.println("Honest.helpOther()"); } } class BirdMan implements Volant{ @Override public void fly() { System.out.println("Volant.fly()"); } }
true
28281b4206f3edb7082be8837656efe798844781
Java
zhuzhihun/LeetCode
/src/dataStructure/InsertDeleteAndFind.java
UTF-8
6,619
4.03125
4
[]
no_license
package dataStructure; import java.util.*; public class InsertDeleteAndFind { /* 给定一个包含 [0,n ) 中独特的整数的黑名单 B,写一个函数从 [ 0,n ) 中返回一个不在 B 中的随机整数。 对它进行优化使其尽量少调用系统方法 Math.random() 。 错误 内存超出 */ class Solution { int[] list; Random random = new Random(); int size; public Solution(int N, int[] blacklist) { //对blacklist排序 使得 Arrays.sort(blacklist); size = N-blacklist.length; list = new int[size]; if (blacklist.length==0){ for (int i = 0; i < N; i++) { list[i]=i; } }else{ for (int i = 0,j=0; i < N; i++) { if (j<blacklist.length&&i==blacklist[j]){ j++; }else{ list[i-j]=i; } } } } public int pick() { return list[random.nextInt(size)]; } } /* code.380. 常数时间插入、删除和获取随机元素 设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。 insert(val):当元素 val 不存在时,向集合中插入该项。 remove(val):元素 val 存在时,从集合中移除该项。 getRandom:随机返回现有集合中的一项。每个元素应该有相同的概率被返回。 */ /* 1、插入,删除,获取随机元素这三个操作的时间复杂度必须都是 O(1)。 2、getRandom 方法返回的元素必须等概率返回随机元素,也就是说,如果集合里面有 n 个元素,每个元素被返回的概率必须是 1/n。 我们先来分析一下:对于插入,删除,查找这几个操作,哪种数据结构的时间复杂度是 O(1)? HashSet 肯定算一个对吧。哈希集合的底层原理就是一个大数组,我们把元素通过哈希函数映射到一个索引上;如果用拉链法解决哈希冲突,那么这个索引可能连着一个链表或者红黑树。 那么请问对于这样一个标准的 HashSet,你能否在 O(1) 的时间内实现 getRandom 函数? 其实是不能的,因为根据刚才说到的底层实现,元素是被哈希函数「分散」到整个数组里面的,更别说还有拉链法等等解决哈希冲突的机制,基本做不到 O(1) 时间等概率随机获取元素。 除了 HashSet,还有一些类似的数据结构,比如哈希链表 LinkedHashSet,我们前文 手把手实现LRU算法 和 手把手实现LFU算法 讲过这类数据结构的实现原理,本质上就是哈希表配合双链表,元素存储在双链表中。 但是,LinkedHashSet 只是给 HashSet 增加了有序性,依然无法按要求实现我们的 getRandom 函数,因为底层用链表结构存储元素的话,是无法在 O(1) 的时间内访问某一个元素的。 根据上面的分析,对于 getRandom 方法,如果想「等概率」且「在 O(1) 的时间」取出元素,一定要满足:底层用数组实现,且数组必须是紧凑的。 这样我们就可以直接生成随机数作为索引,从数组中取出该随机索引对应的元素,作为随机元素。 但如果用数组存储元素的话,插入,删除的时间复杂度怎么可能是 O(1) 呢? 可以做到!对数组尾部进行插入和删除操作不会涉及数据搬移,时间复杂度是 O(1)。 所以,如果我们想在 O(1) 的时间删除数组中的某一个元素 val,可以先把这个元素交换到数组的尾部,然后再 pop 掉。 交换两个元素必须通过索引进行交换对吧,那么我们需要一个哈希表 valToIndex 来记录每个元素值对应的索引。 */ static class RandomizedSet { Map<Integer,Integer> map; //将数字的值与在list中位置的索引联系起来 List<Integer> list; //list用来实现随机取数时为O(1)操作 Random rand = new Random(); //产生随机数 /** Initialize your data structure here. */ public RandomizedSet() { map = new HashMap<>(); list = new ArrayList<>(); } /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */ public boolean insert(int val) { if (map.containsKey(val)){ return false; } map.put(val,list.size()); list.add(val); return true; } /** Removes a value from the set. Returns true if the set contained the specified element. */ public boolean remove(int val) { Integer idx = map.remove(val); if (idx==null){ return false; } //先需要将删除的元素与最末尾的元素交换位置后进行删除 if (idx!=list.size()-1){ int last = list.remove(list.size()-1); map.put(last,idx); //将最后位置的索引换到a list.set(idx,list.get(list.size()-1)); //map中更新移动最后位置节点的索引 }else{ list.remove(list.size()-1); //map.remove() } return true; } /** Get a random element from the set. */ public int getRandom() { return list.get(rand.nextInt(list.size())); } } public static void main(String[] args) { // 初始化一个空的集合。 RandomizedSet randomSet = new RandomizedSet(); // 向集合中插入 1 。返回 true 表示 1 被成功地插入。 System.out.println(randomSet.insert(1)); // 返回 false ,表示集合中不存在 2 。 System.out.println(randomSet.remove(2)); // 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。 System.out.println(randomSet.insert(2)); // getRandom 应随机返回 1 或 2 。 System.out.println(randomSet.getRandom()); // 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。 System.out.println(randomSet.remove(1)); // 2 已在集合中,所以返回 false 。 System.out.println(randomSet.insert(2)); // 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。 System.out.println(randomSet.getRandom()); } }
true
589b36c065bb92b8849ad609ef18929e6589ca26
Java
gxlioper/collections
/深圳/szjx_portal/src/com/gwssi/ad/AdDao.java
UTF-8
34,116
1.796875
2
[]
no_license
package com.gwssi.ad; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Properties; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.BasicAttribute; import javax.naming.directory.BasicAttributes; import javax.naming.directory.DirContext; import javax.naming.directory.ModificationItem; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.ldap.InitialLdapContext; import javax.naming.ldap.LdapContext; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import com.gwssi.optimus.core.common.ConfigManager; /** * 操作windows AD域类 * * @author Leezen */ public class AdDao { private static Logger logger = Logger.getLogger(AdDao.class); // LdapContext ctx = null; // 登录脚本标志。如果通过 ADSI LDAP 进行读或写操作时,该标志失效。如果通过 ADSI WINNT,该标志为只读。 int UF_SCRIPT = 0X0001; // 主文件夹标志 int UF_HOMEDIR_REQUIRED = 0X0008; // 过期标志 int UF_LOCKOUT = 0X0010; // 本地帐号标志 int UF_TEMP_DUPLICATE_ACCOUNT = 0X0100; // 普通用户的默认帐号类型 int UF_NORMAL_ACCOUNT = 0X0200; // 跨域的信任帐号标志 int UF_INTERDOMAIN_TRUST_ACCOUNT = 0X0800; // 工作站信任帐号标志 int UF_WORKSTATION_TRUST_ACCOUNT = 0x1000; // 服务器信任帐号标志 int UF_SERVER_TRUST_ACCOUNT = 0X2000; // 用户密码不是必须的 int UF_PASSWD_NOTREQD = 0X0020; // 密码不能更改标志 int UF_PASSWD_CANT_CHANGE = 0X0040; // 密码永不过期标志 int UF_DONT_EXPIRE_PASSWD = 0X10000; // 使用可逆的加密保存密码 int UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0X0080; // 用户帐号禁用标志 int UF_ACCOUNTDISABLE = 0X0002; // 交互式登录必须使用智能卡 int UF_SMARTCARD_REQUIRED = 0X40000; // 用户帐号可委托标志 int UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0X1000000; // 当设置该标志时,即使服务帐号是通过 Kerberos 委托信任的,敏感帐号不能被委托 int UF_NOT_DELEGATED = 0X100000; // 此帐号需要 DES 加密类型 int UF_USE_DES_KEY_ONLY = 0X200000; // 当设置该标志时,服务帐号(用户或计算机帐号)将通过 Kerberos 委托信任 int UF_TRUSTED_FOR_DELEGATION = 0X80000; // 不要进行 Kerberos 预身份验证 int UF_DONT_REQUIRE_PREAUTH = 0X4000000; // MNS 帐号标志 int UF_MNS_LOGON_ACCOUNT = 0X20000; // 使用AES加密 int UF_USE_AES_KEYS = 0x8000000; // 用户密码过期标志 int UF_PASSWORD_EXPIRED = 0X800000; /** * 连接AD域(供查询用) * * @return 连接状态 */ public LdapContext conAd389() { logger.info("进入连接AD域方法"); // 读出配置文件里的AD域超级管理员的用户名和密码 Properties properties = ConfigManager.getProperties("ad"); String adminName = properties.getProperty("ad.admin.name"); // 用户名 String adminPassword = properties.getProperty("ad.admin.pwd"); // 密码 // 读出配置文件里的AD域的连接路径 String ldapUrl = properties.getProperty("ad.ldap.url.389"); // 连接路径 Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // 设置连接 env.put(Context.SECURITY_AUTHENTICATION, "simple"); // 使用用户名和密码认证 env.put(Context.SECURITY_PRINCIPAL, adminName); env.put(Context.SECURITY_CREDENTIALS, adminPassword); env.put(Context.PROVIDER_URL, ldapUrl); env.put("com.sun.jndi.ldap.connect.pool", "true"); env.put("java.naming.referral", "follow"); logger.info("连接对象env为: " + env); LdapContext ctx = null; try { ctx = new InitialLdapContext(env, null); logger.info("连接AD域成功!"); } catch (NamingException e) { try { ctx.close(); logger.debug("连接AD域 失败!"); e.printStackTrace(); logger.debug("连接AD域 失败原因===> "+e.getMessage()); } catch (NamingException e1) { e1.printStackTrace(); logger.debug("连接AD域 失败原因===> "+e1.getMessage()); } } return ctx; } /** * 连接AD域(供查编辑用) * * 636端口慎用,需要用ssl协议一旦没有关闭连接系统会报错socket close * * @return 连接状态 */ public LdapContext conAd636() { logger.info("进入连接AD域方法"); Properties properties = ConfigManager.getProperties("ad"); String adminName = properties.getProperty("ad.admin.name"); String adminPassword = properties.getProperty("ad.admin.pwd"); // 读出配置文件里的 ssl证书在jdk下的路径 String keystore = properties.getProperty("keystore"); // 读出配置文件里的AD域的连接路径 String ldapUrl = properties.getProperty("ad.ldap.url.636"); // 设置系统使用ssl协议 System.setProperty("javax.net.ssl.trustStore", keystore); Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); // 设置连接 env.put(Context.SECURITY_AUTHENTICATION, "simple"); // 使用用户名和密码认证 env.put(Context.SECURITY_PRINCIPAL, adminName); env.put(Context.SECURITY_CREDENTIALS, adminPassword); env.put(Context.PROVIDER_URL, ldapUrl); env.put(Context.SECURITY_PROTOCOL, "ssl"); env.put("com.sun.jndi.ldap.connect.pool", "true"); env.put("java.naming.referral", "follow"); logger.info("连接对象env为: " + env); LdapContext ctx = null; try { ctx = new InitialLdapContext(env, null); logger.info("连接AD域成功!"); } catch (NamingException e) { try { ctx.close(); } catch (NamingException e1) { logger.info("AD域关闭失败" + e1.getMessage()); e1.printStackTrace(); } logger.debug("连接AD域 失败!"); e.printStackTrace(); } finally { if(ctx!=null) { try { ctx.close(); } catch (NamingException e) { logger.info("AD域关闭失败" + e.getMessage()); e.printStackTrace(); } } } return ctx; } /** * 关闭AD域 */ public void closeAd(LdapContext ctx) { try { ctx.close(); logger.info("关闭AD域连接成功!"); } catch (NamingException e) { e.printStackTrace(); logger.debug("关闭AD域连接失败!"); } } /** * 测试ad域连接 * * @return String */ public String testCon() { String str389 = ""; LdapContext ctx = conAd389(); if (null != ctx) { closeAd(ctx); str389 = "连接AD域389端口成功"; } else { str389 = "连接AD域389端口失败"; } String str636 = ""; LdapContext ctx636 = conAd636(); if (null != ctx636) { closeAd(ctx636); str636 = "连接AD域636端口成功"; } else { str636 = "连接AD域636端口失败"; } return str389 + str636; } /** * 创建用户 * * @param person * @return 创建用户状态 */ public Map createOnePerson(Person person) { // 返回值 Map resMap = new HashMap(); Properties properties = ConfigManager.getProperties("ad"); String res = properties.getProperty("create.user.success"); // 成功状态返回代码 BasicAttribute ocattr = new BasicAttribute("objectClass"); ocattr.add("top"); ocattr.add("person"); ocattr.add("organizationalPerson"); ocattr.add("user"); Attributes attrs = new BasicAttributes(true); attrs.put(ocattr); attrs.put("sn", person.getSn()); // 姓 attrs.put("givenName", person.getGiveName()); // 名 attrs.put("cn", person.getCn()); // 面板显示名称 attrs.put("displayName", person.getDisplayName()); // 显示姓名 String samAccountName = ""; // 判断用户的组织单位是否存在,如不存在创建组织单位 boolean isOuExist = checkPersonOu(person.getOu()); logger.info("用户组织是否存在:" + isOuExist); if (isOuExist) { // 判断用户登录ID是否存在重复,如果重复按照规则在后面依次加上数字 samAccountName = checkPersonName(person.getsAMAccountName()); logger.info("samAccountName名称为:" + samAccountName); attrs.put("samAccountName", samAccountName); attrs.put("userAccountControl", Integer.toString(UF_NORMAL_ACCOUNT + UF_ACCOUNTDISABLE)); attrs.put("userPrincipalName",samAccountName + properties.getProperty("ad.dn.com")); // 建立636端口连接 LdapContext ctx = conAd636(); try { // 创建用户 ctx.createSubcontext(person.getDistinguishedName(), attrs); // 为用户设置默认密码 ModificationItem[] mods = new ModificationItem[3]; String newQuotedPassword = "\"" + properties.getProperty("default.pwd") + "\""; byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE"); mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("unicodePwd", newUnicodePassword)); mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("userAccountControl",Integer.toString(UF_NORMAL_ACCOUNT+ UF_PASSWORD_EXPIRED))); // 设置用户第一次登录必须修改密码 mods[2] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,new BasicAttribute("pwdLastSet", "0")); ctx.modifyAttributes(person.getDistinguishedName(), mods); resMap.put("USER_NAME", samAccountName); resMap.put("PASSWORD", properties.getProperty("default.pwd")); logger.info("创建用户 " + person.getDistinguishedName()+ " 成功!"); } catch (NamingException e) { res = properties.getProperty("create.user.fail"); // 失败状态返回代码 e.printStackTrace(); logger.info("创建用户 " + person.getDistinguishedName()+ " 失败!"); logger.info(samAccountName + "创建用户失败原因 ===> " +e.getMessage()); logger.info(Integer.toString(UF_NORMAL_ACCOUNT + UF_ACCOUNTDISABLE) + "userAccountControl原因 ===> " +e.getMessage()); logger.info(samAccountName + properties.getProperty("ad.dn.com") + "userPrincipalName 原因 ===> " +e.getMessage()); } catch (UnsupportedEncodingException e) { logger.info(samAccountName + "创建用户失败原因 ===> " +e.getMessage()); e.printStackTrace(); } finally { // 关闭连接 resMap.put("RETURN_CODE", res); closeAd(ctx); } return resMap; } else { res = properties.getProperty("user.ou.noexist"); // 失败状态返回代码 logger.info("创建用户 " + person.getDistinguishedName()+ " 失败,因为用户所属组织机构不存在!"); resMap.put("RETURN_CODE", res); return resMap; } } /** * 创建用户时先查看用户所属机构是否存在 * * @param person */ private boolean checkPersonOu(String ouStr) { logger.info("用户的组织单位为:" + ouStr); boolean isExist = false; String startDN = ouStr; String filter = "(&(objectClass=top)(objectClass=organizationalUnit))"; // 实例化一个搜索器 SearchControls cons = new SearchControls(); // 搜索范围: 树形检索 cons.setSearchScope(SearchControls.OBJECT_SCOPE); // 设置为false时返回结果占用内存减少 cons.setReturningObjFlag(true); // 定制返回属性 String returnedAtts[] = { "name", "ou", "distinguishedName" }; cons.setReturningAttributes(returnedAtts); LdapContext ctx = this.conAd389(); // 执行查询 try { NamingEnumeration<SearchResult> sEnum = ctx.search(startDN, filter, cons); while (sEnum.hasMoreElements()) { SearchResult sr = sEnum.nextElement(); Attributes attrs = sr.getAttributes(); NamingEnumeration<? extends Attribute> aEnum = attrs.getAll(); // 取到所有属性 while (aEnum.hasMoreElements()) { Attribute attr = aEnum.nextElement(); if (attr == null) { continue; } if ("distinguishedName".equals(attr.getID())) { String name = (String) attr.get(0); if (ouStr.equals(name)) { isExist = true; } } } } } catch (NamingException e) { // e.printStackTrace(); logger.info("AD域查询初始搜索器化出错:该"+ouStr+" 组织不存在"); } finally { closeAd(ctx); } return isExist; } /** * 检查用户重复 * * @param String登录ID */ private String checkPersonName(String sAMAccountName) { // 实例化一个搜索器 SearchControls searchCtls = new SearchControls(); // 搜索范围: 树形检索 searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // 设置为false时返回结果占用内存减少 searchCtls.setReturningObjFlag(true); // 设置查询过滤器 String searchFilter = "(sAMAccountName=" + sAMAccountName + "*)"; // String searchFilter = "(&(objectClass=user)(sAMAccountName=CeM))"; // 设置搜索域节点 Properties properties = ConfigManager.getProperties("ad"); String searchBase = properties.getProperty("ad.dn.base"); // 定制返回属性 String returnedAtts[] = { "sAMAccountName" }; searchCtls.setReturningAttributes(returnedAtts); LdapContext ctx = this.conAd389(); List userNameList = new ArrayList(); int size = 0; String res = ""; // 执行查询 try { NamingEnumeration<SearchResult> sEnum = ctx.search(searchBase, searchFilter, searchCtls); if (sEnum == null || sEnum.equals(null)) { logger.info("没有重ID的用户"); res = sAMAccountName; } else { // logger.info("有重ID的用户,重id的用户分别是"); while (sEnum.hasMoreElements()) { SearchResult sr = sEnum.nextElement(); Attributes attrs = sr.getAttributes(); NamingEnumeration<? extends Attribute> aEnum = attrs .getAll(); // 取到所有属性 while (aEnum.hasMoreElements()) { Attribute attr = aEnum.nextElement(); if (attr == null) { continue; } if ("sAMAccountName".equals(attr.getID())) { String name = (String) attr.get(0); userNameList.add(name.toLowerCase()); //logger.info(name); size++; } } } } res = getName(userNameList, sAMAccountName); } catch (NamingException e) { e.printStackTrace(); } finally { closeAd(ctx); } return res; } /** * 具体创建用户名 * @author chaihw * @param nameList * @param name * @return */ public static String getName(List<String> nameList, String name) { String sAMAccountName=""; int nameright=0; if(nameList!=null&&nameList.size()>0){ for(String existname:nameList){ if(StringUtils.equals(existname, name)){ nameright=nameright+1; logger.info(existname); }else{ // System.out.println(existname+"处理后字符串"+existname.substring(name.length())); boolean isnumber = isNumeric(existname.substring(name.length())); // System.out.println("是否为数字:"+isnumber); if(isnumber){ logger.info(existname); nameright=nameright+1; } } } } if(nameright>0){ logger.info("有重ID的用户,以上为重id的用户,共有"+nameright+"重复"); }else{ logger.info("没有重复的ID直接创建"); } if(nameright!=0){ sAMAccountName=name+nameright; }else{ sAMAccountName=name; } if(nameList.contains(sAMAccountName)){ // System.out.println("包含"); while(nameList.contains(sAMAccountName)){ nameright =nameright+1; sAMAccountName =name+nameright; } return sAMAccountName; }else{ // System.out.println("不包含"); return sAMAccountName; } } /** * 判断是否为数字 * @param str * @return */ public static boolean isNumeric(String str){ for (int i = str.length();--i>=0;){ if (!Character.isDigit(str.charAt(i))){ return false; } } return true; } /** * * @param nameList * @param name * @return 用户ID */ /* public static String getName(List<String> nameList, String name) { // 比较器 Comparator<String> comparator = new Comparator<String>() { public int compare(String o1, String o2) { // 前面3个IF主要是判空的 if (o1 == o2) { return 0; } if (o1 == null) { return 1; } if (o2 == null) { return -1; } // 这里没有做太多的判断, index 代表第几个开始是数字, 直接从后面遍历 // 比如 aa11, 我们就会判断从下标[2]开始为不是数字, 就直接截取 [2] 后面, 即11 int length1 = o1.length() - 1; int length2 = o2.length() - 1; int index = 0; int num1 = 0; int num2 = 0; for (index = length1; index >= 0 && (o1.charAt(index) >= '0' && o1.charAt(index) <= '9'); index--) ; if (index < length1) { num1 = Integer.parseInt(o1.substring(index + 1)); } else { num1 = 0; } for (index = length2; index >= 0 && (o2.charAt(index) >= '0' && o2.charAt(index) <= '9'); index--) ; if (index < length2) { num2 = Integer.parseInt(o2.substring(index + 1)); } else { num2 = 0; } return num1 - num2; } }; if (nameList.size() > 0) { Collections.sort(nameList, comparator); String maxName = nameList.get(nameList.size() - 1); int index = 0; int length = maxName.length() - 1; int num = 0; for (index = length; index >= 0 && (maxName.charAt(index) >= '0' && maxName.charAt(index) <= '9'); index--) ; if (index < length) { num = Integer.parseInt(maxName.substring(index + 1)); } else { num = 0; } num++; return name + num; } else { return name; } } */ /** * 禁用用户 * * @param person * @return 禁用用户状态 */ public Map disablePerson(Person person) { Map resMap = new HashMap(); Properties properties = ConfigManager.getProperties("ad"); String res = properties.getProperty("disable.user.success"); String userName = person.getDistinguishedName(); ModificationItem[] mods = new ModificationItem[1]; mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userAccountControl", Integer.toString(UF_ACCOUNTDISABLE + UF_NORMAL_ACCOUNT + UF_DONT_EXPIRE_PASSWD))); if(userName==null){ logger.info("禁用用户失败 ,未找到该用户"); res=properties.getProperty("user.is.noexist"); resMap.put("RETURN_CODE", res); return resMap; } // 建立636端口连接 LdapContext ctx = conAd636(); try { ctx.modifyAttributes(userName, mods); logger.info("禁用用户 " + userName + " 成功!"); } catch (NamingException e) { res = properties.getProperty("disable.user.fail"); e.printStackTrace(); logger.info("禁用用户 " + userName + " 失败!"); } finally { resMap.put("RETURN_CODE", res); closeAd(ctx); } return resMap; } /** * 启用用户 * * @param person * @return 启用用户状态 */ public Map enablePerson(Person person) { Map resMap = new HashMap(); Properties properties = ConfigManager.getProperties("ad"); String res = properties.getProperty("enable.user.success"); String userName = person.getDistinguishedName(); ModificationItem[] mods = new ModificationItem[1]; mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userAccountControl", Integer.toString(UF_NORMAL_ACCOUNT))); if(userName==null){ logger.info("启用用户失败 ,未找到该用户"); res=properties.getProperty("user.is.noexist"); resMap.put("RETURN_CODE", res); return resMap; } // 建立636端口连接 LdapContext ctx = conAd636(); try { ctx.modifyAttributes(userName, mods); logger.info("启用用户 " + userName + " 成功!"); } catch (NamingException e) { res = properties.getProperty("enable.user.fail"); e.printStackTrace(); logger.info("启用用户 " + userName + " 失败!"); } finally { resMap.put("RETURN_CODE", res); closeAd(ctx); } return resMap; } /** * 重置用户密码 * * @param person * @return Map */ public Map resetPwd(Person person) { String sAMAccountName = checkPersonExist(person); Map resMap = new HashMap(); Properties properties = ConfigManager.getProperties("ad"); String res = properties.getProperty("reset.pwd.success"); if (!"".equals(sAMAccountName)) { person.setsAMAccountName(sAMAccountName); // 建立636端口连接 LdapContext ctx = conAd636(); try { ModificationItem[] mods = new ModificationItem[3]; String newQuotedPassword = "\"" + properties.getProperty("default.pwd") + "\""; byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE"); mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd", newUnicodePassword)); mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("userAccountControl", Integer.toString(UF_NORMAL_ACCOUNT + UF_PASSWORD_EXPIRED))); mods[2] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("pwdLastSet", "0")); ctx.modifyAttributes(person.getDistinguishedName(), mods); resMap.put("USER_NAME", person.getsAMAccountName()); resMap.put("PASSWORD", properties.getProperty("default.pwd")); logger.info("重置用户密码 " + person.getDistinguishedName() + " 成功!"); } catch (NamingException e) { res = properties.getProperty("reset.pwd.fail"); logger.info("重置用户密码失败原因 " + e.getMessage()); logger.info("重置用户密码 " + person.getDistinguishedName() + " 失败!"); e.printStackTrace(); } catch (UnsupportedEncodingException e) { logger.info("重置用户密码失败原因 " + e.getMessage()); e.printStackTrace(); } finally { resMap.put("RETURN_CODE", res); closeAd(ctx); } return resMap; } else { res = properties.getProperty("user.is.noexist"); resMap.put("RETURN_CODE", res); resMap.put("USER_NAME", person.getDisplayName()); resMap.put("USERID", person.getsAMAccountName()); return resMap; } } /** * * @param person * @return */ private String checkPersonExist(Person person) { // 实例化一个搜索器 SearchControls searchCtls = new SearchControls(); // 搜索范围: 树形检索 searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // 设置为false时返回结果占用内存减少 searchCtls.setReturningObjFlag(true); // 设置查询过滤器 String searchFilter = "(distinguishedName=" + person.getDistinguishedName() + ")"; // 设置搜索域节点 Properties properties = ConfigManager.getProperties("ad"); String searchBase = properties.getProperty("ad.dn.base"); // 定制返回属性 String returnedAtts[] = { "sAMAccountName" }; searchCtls.setReturningAttributes(returnedAtts); LdapContext ctx = this.conAd389(); List userNameList = new ArrayList(); String res = ""; // 执行查询 try { NamingEnumeration<SearchResult> sEnum = ctx.search(searchBase, searchFilter, searchCtls); if (sEnum == null || sEnum.equals(null)) { logger.info("没有重ID的用户"); } else { logger.info("有重ID的用户,重id的用户分别是"); while (sEnum.hasMoreElements()) { SearchResult sr = sEnum.nextElement(); Attributes attrs = sr.getAttributes(); NamingEnumeration<? extends Attribute> aEnum = attrs .getAll(); // 取到所有属性 while (aEnum.hasMoreElements()) { Attribute attr = aEnum.nextElement(); if (attr == null) { continue; } if ("sAMAccountName".equals(attr.getID())) { res = (String) attr.get(0); logger.info("要重置密码的用户【sAMAccountName】为:" + res); } } } } } catch (NamingException e) { e.printStackTrace(); } finally { closeAd(ctx); } return res; } /** * 修改用户组织单位 * * @param name * 用户姓名 * @param oldOu * 原组织单位 * @param newOu * 新组织单位 * @return Map */ public Map changePersonOu(String name, String oldOu, String newOu) { Map resMap = new HashMap(); Properties properties = ConfigManager.getProperties("ad"); String baseDN = properties.getProperty("ad.dn.base"); String res = properties.getProperty("change.ou.success"); StringBuffer oldDistinguishedName=null; if(!oldOu.startsWith("CN=")){ oldDistinguishedName= new StringBuffer(); oldDistinguishedName.append("CN="); oldDistinguishedName.append(name); oldDistinguishedName.append(","); String oldOuStr[] = oldOu.split(","); if (oldOuStr.length == 0) { oldDistinguishedName.append("CN=Users,"); } else { for (int i = 0; i < oldOuStr.length; i++) { oldDistinguishedName.append("OU="); oldDistinguishedName.append(oldOuStr[i]); if (i <= oldOuStr.length - 1) oldDistinguishedName.append(","); } } oldDistinguishedName.append(baseDN); }else{ oldDistinguishedName=new StringBuffer(oldOu); } StringBuffer newDistinguishedName = new StringBuffer(); newDistinguishedName.append("CN="); newDistinguishedName.append(name); newDistinguishedName.append(","); if(name==null){ logger.info("启用用户失败 ,未找到该用户"); res=properties.getProperty("user.is.noexist"); resMap.put("RETURN_CODE", res); return resMap; } StringBuffer newUserOu = new StringBuffer(); String newOuStr[] = newOu.split(","); if (newOuStr.length == 0) { newDistinguishedName.append("CN=Users,"); } else { for (int i = 0; i < newOuStr.length; i++) { newDistinguishedName.append("OU="); newDistinguishedName.append(newOuStr[i]); newUserOu.append("OU="); newUserOu.append(newOuStr[i]); if (i <= newOuStr.length - 1) { newDistinguishedName.append(","); newUserOu.append(","); } } } newDistinguishedName.append(baseDN); newUserOu.append(baseDN); logger.info("用户要调整到:" + newUserOu + "部门"); // 判断新的组织单位是否存在 boolean isOuExist = checkPersonOu(newUserOu.toString()); if (isOuExist) { // 建立636端口连接 LdapContext ctx = conAd636(); try { ctx.rename(oldDistinguishedName.toString(), newDistinguishedName.toString()); logger.info("将用户" + oldDistinguishedName + "修改组织单位" + newDistinguishedName + " 成功!"); } catch (NamingException e) { e.printStackTrace(); res = properties.getProperty("change.ou.fail"); // 返回值 logger.info("将用户" + oldDistinguishedName + "修改组织单位" + newDistinguishedName + " 失败!"); } finally { resMap.put("RETURN_CODE", res); closeAd(ctx); } return resMap; } else { res = properties.getProperty("user.ou.noexist"); // 返回值 resMap.put("RETURN_CODE", res); logger.info("将用户" + oldDistinguishedName + "修改组织单位" + newDistinguishedName + " 失败!"); return resMap; } } /** * 创建组织单位 * * @param ou * @return Map */ public Map createOneOu(Ou ou) { Map resMap = new HashMap(); Properties properties = ConfigManager.getProperties("ad"); String res = properties.getProperty("create.ou.success"); String baseDN = properties.getProperty("ad.dn.base"); BasicAttribute ocattr = new BasicAttribute("objectClass"); ocattr.add("top"); ocattr.add("organizationalUnit"); Attributes attrs = new BasicAttributes(true); attrs.put(ocattr); attrs.put("name", ou.getName()); attrs.put("ou", ou.getOu()); attrs.put("distinguishedName", ou.getDistinguishedName()); String ouStr = ou.getDistinguishedName(); String ouFatherStr = ouStr.substring(("OU=" + ou.getName() + ",").length()); boolean isExist = false; // 判断上级组织单位是否存在 boolean isOuExist1 = checkPersonOu(ouFatherStr.toString()); logger.debug("上级单位存在:"+isOuExist1); // 判断新的组织单位是否存在 boolean isOuExist = checkPersonOu(ouStr.toString()); if (!isOuExist) { if (isOuExist1) { // 建立636端口连接 LdapContext ctx = conAd636(); try { ctx.createSubcontext(ou.getDistinguishedName(), attrs); logger.info("创建组织单位 " + ou.getDistinguishedName() + " 成功!"); } catch (NamingException e) { res = properties.getProperty("create.ou.fail"); logger.info("创建组织单位 " + ou.getDistinguishedName() + " 失败!"); e.printStackTrace(); } finally { resMap.put("RETURN_CODE", res); closeAd(ctx); } return resMap; } else { logger.info("创建组织单位 " + ou.getDistinguishedName() + " 失败,该组织上级机构不存在!"); res = properties.getProperty("ou.up.noexist"); resMap.put("RETURN_CODE", res); return resMap; } } else { logger.info("创建组织单位 " + ou.getDistinguishedName() + " 失败,该组织已经存在!"); res = properties.getProperty("ou.is.exist"); resMap.put("RETURN_CODE", res); return resMap; } } /** * 修改组织单位名称 * * @param oldName * 原名称 * @param newName * 新名称 * @return Map */ public Map updateOneOu(String oldName, String newName) { Map resMap = new HashMap(); Properties properties = ConfigManager.getProperties("ad"); String res = properties.getProperty("update.ou.success"); // 建立636端口连接 LdapContext ctx = conAd636(); try { ctx.rename(oldName, newName); logger.info("修改组织单位名称 " + oldName + " 成功!"); } catch (NamingException e) { res = properties.getProperty("update.ou.fail"); logger.info("修改组织单位名称 " + oldName + " 失败!"); logger.info("修改组织单位名称失败原因====> " +e.getMessage()); e.printStackTrace(); } finally { closeAd(ctx); resMap.put("RETURN_CODE", res); } return resMap; } /** * 手动迁移用户 * * @param oldOu * @param newOu */ public void change(String oldOu, String newOu) { // 建立636端口连接 LdapContext ctx = conAd636(); try { ctx.rename(oldOu.toString(), newOu.toString()); System.out.println("修改用户组织成功!"); } catch (NamingException e) { e.printStackTrace(); System.out.println("将用户" + oldOu + "修改组织单位" + newOu + " 失败!"); } finally { closeAd(ctx); } } /** * 更具登录id sAMAccountName 查询某人的组织机构 * @param persionid * @return */ public Person searchOnePersion(String sAMAccountName){ Person person = new Person();; // 实例化一个搜索器 SearchControls searchCtls = new SearchControls(); // 搜索范围: 树形检索 searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // 设置为false时返回结果占用内存减少 searchCtls.setReturningObjFlag(true); // 设置查询过滤器 String searchFilter = "(sAMAccountName=" + sAMAccountName + ")"; // String searchFilter = "(&(objectClass=user)(sAMAccountName=CeM))"; // 设置搜索域节点 Properties properties = ConfigManager.getProperties("ad"); String searchBase = properties.getProperty("ad.dn.base"); // 定制返回属性 String returnedAtts[] = { "sAMAccountName","distinguishedName" }; searchCtls.setReturningAttributes(returnedAtts); LdapContext ctx = this.conAd389(); List userNameList = new ArrayList(); int size = 0; String res = ""; // 执行查询 try { NamingEnumeration<SearchResult> sEnum = ctx.search(searchBase, searchFilter, searchCtls); if (sEnum == null || sEnum.equals(null)) { logger.info("未找到该ID的用户,该id为:"+sAMAccountName); res = sAMAccountName; } else { while (sEnum.hasMoreElements()) { SearchResult sr = sEnum.nextElement(); Attributes attrs = sr.getAttributes(); NamingEnumeration<? extends Attribute> aEnum = attrs .getAll(); // 取到所有属性 while (aEnum.hasMoreElements()) { Attribute attr = aEnum.nextElement(); if (attr == null) { continue; } if ("sAMAccountName".equals(attr.getID())) { String name = (String) attr.get(0); //userNameList.add(name.toLowerCase()); person.setsAMAccountName(name); } if("distinguishedName".equalsIgnoreCase(attr.getID())){ String name = (String) attr.get(0); // userNameList.add(name.toLowerCase()); person.setDistinguishedName(name); logger.info("找到该用户,该用户的DistinguishedName串为:"+person.getDistinguishedName()); return person; } } } } //res = getName(userNameList, sAMAccountName); } catch (NamingException e) { e.printStackTrace(); } finally { closeAd(ctx); } return person; } //https://www.cnblogs.com/cnjavahome/p/9043490.html /** * @Description:修改AD域用户属性 * @author moonxy * @date 2018-05-15 */ public boolean modifyInformation(String dn, String fieldValue) { DirContext dc = null; String root = null; try { dc = this.conAd389(); ModificationItem[] mods = new ModificationItem[1]; // 修改属性 Attribute attr0 = new BasicAttribute("homePhone",fieldValue); //mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, attr0);//新增属性 //mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE,attr0);//删除属性 mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr0);//覆盖属性 dc.modifyAttributes(dn + "," + root, mods); System.out.println("修改AD域用户属性成功"); return true; } catch (Exception e) { System.err.println("修改AD域用户属性失败"); e.printStackTrace(); return false; } } }
true
0b3648663e589242b13ea3066171ebc30aef7ea0
Java
mpaniushkina/usafe
/app/src/main/java/com/covrsecurity/io/ui/viewmodel/baseactivity/BaseActivityViewModelFactory.java
UTF-8
947
2.234375
2
[]
no_license
package com.covrsecurity.io.ui.viewmodel.baseactivity; import androidx.annotation.NonNull; import androidx.lifecycle.ViewModel; import androidx.lifecycle.ViewModelProvider; import com.covrsecurity.io.domain.usecase.identity.IsApprovedUseCase; import javax.inject.Inject; public class BaseActivityViewModelFactory implements ViewModelProvider.Factory { protected final IsApprovedUseCase isApprovedUseCase; @Inject public BaseActivityViewModelFactory(IsApprovedUseCase isApprovedUseCase) { this.isApprovedUseCase = isApprovedUseCase; } @NonNull @Override public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { if (modelClass.isAssignableFrom(BaseActivityViewModel.class)) { return (T) new BaseActivityViewModel( isApprovedUseCase ); } else { throw new IllegalArgumentException("ViewModel Not Found"); } } }
true
6a66eaeebafabc06e48c724836e3a39897af4814
Java
Selenium39/micro-weather
/micro-weather-city-client/src/main/java/com/selenium/microweathercityclient/cityDataService/CityDataService.java
UTF-8
204
1.6875
2
[]
no_license
package com.selenium.microweathercityclient.cityDataService; import java.util.List; import com.selenium.microweathercityclient.vo.City; public interface CityDataService { List<City> getAllCity(); }
true
b9be49a0b471fc78caf9fc894c4a1798c96331be
Java
cortezsydney/137spaceImpact
/MapState.java
UTF-8
575
3.15625
3
[]
no_license
import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.ArrayList; public class MapState{ private Map aliens=new HashMap(); public MapState(){} public void update(String name, NetAlien player){ aliens.put(name, player); } public String toString(){ String retval=""; for(Iterator ite = aliens.keySet().iterator(); ite.hasNext();){ String name = (String)ite.next(); NetAlien player = (NetAlien)aliens.get(name); retval+=player.toString()+":"; } return retval; } public Map getliens(){ return aliens; } }
true
65a9414c72f0acf454649543722c63624387feda
Java
adielmo/algoritmoJava
/src/br/com/algoritmo/base/Ex05.java
UTF-8
1,303
3.765625
4
[]
no_license
package br.com.algoritmo.base; import br.com.algoritmo.pilhas.Pilha; public class Ex05 { public static void main(String[] args) { imprimir("adielmo"); imprimir("ada"); imprimir("abcd"); imprimir("abccba"); } public static void imprimir(String palavra) { System.out.println(primeiroMaiusculo(palavra) + " é uma palavra Palidromo: " +saida(palavra)); } public static String saida(String palavra) { return teste(palavra) ? "Sim" : "Não"; } public static boolean teste(String palavra) { String novaPalavra = ""; for(int i = palavra.length()-1; i >= 0; i--) { novaPalavra += palavra.charAt(i); } return novaPalavra.equalsIgnoreCase(palavra) ? true : false; } public static boolean testaPalidromo(String palavra) { Pilha<Character> pilha = new Pilha<>(); for(int i=0; i < palavra.length(); i++) { pilha.empilha(palavra.charAt(i)); } String palavraInversa = ""; while(!pilha.estavazia()) { palavraInversa += pilha.desempilhar(); } if (palavraInversa.equalsIgnoreCase(palavra)) { return true; } return false; } public static String primeiroMaiusculo(String palavra) { String PrimMaiúscula = ""; PrimMaiúscula= palavra.substring(0, 1).toUpperCase().concat(palavra.substring(1)); return PrimMaiúscula; } }
true
06f1c40bb6911d2a5153353d198d520b3e97e3e1
Java
keval02/BOSSB2B
/app/src/main/java/com/nivida/bossb2b/Bean/Bean_Custom_list.java
UTF-8
443
2.234375
2
[]
no_license
package com.nivida.bossb2b.Bean; /** * Created by Dhruvil Bhosle on 02-12-2016. */ public class Bean_Custom_list { String txt =""; int image ; public Bean_Custom_list() { } public String getTxt() { return txt; } public void setTxt(String txt) { this.txt = txt; } public int getImage() { return image; } public void setImage(int image) { this.image = image; } }
true
110bbed437ae5c1d47ce74e29bf2e80c7551659a
Java
xxiao23/xiao-puzzle
/leetcode/triangle/java/Solution2.java
UTF-8
1,132
3.203125
3
[]
no_license
public class Solution { private Map<Integer, HashMap<Integer, Integer>> cache = null; // memorization cache public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) { // Note: The Solution object is instantiated only once and is reused by each test case. if (triangle == null || triangle.size() == 0) return 0; cache = new HashMap<Integer, HashMap<Integer, Integer>>(); return worker(triangle, 0, 0); } private int worker(ArrayList<ArrayList<Integer>> triangle, int row, int col) { if (cache.containsKey(row) && cache.get(row).containsKey(col)) return cache.get(row).get(col); int e = triangle.get(row).get(col); // base case if (row == triangle.size()-1) return e; // recursion int m1 = worker(triangle, row+1, col); // go down left int m2 = worker(triangle, row+1, col+1); // go down right int ret = m1 < m2 ? e+m1 : e+m2; if (!cache.containsKey(row)) { cache.put(row, new HashMap<Integer, Integer>()); } cache.get(row).put(col, ret); return ret; } }
true
dd2c595e3b85dd724302fb8297d73659a5c7b44b
Java
gsh978079141/ssmsrd
/src/main/java/com/gsh/ssmsrd/controller/RoomControl.java
UTF-8
21,897
1.953125
2
[]
no_license
//package com.gsh.ssmsrd.controller; // //import com.gsh.model.*; //import com.gsh.service.*; //import com.gsh.util.DateUtil; //import com.gsh.util.IDCardCheck; //import org.springframework.stereotype.Controller; //import org.springframework.ui.Model; //import org.springframework.web.bind.annotation.RequestMapping; //import org.springframework.web.bind.annotation.ResponseBody; // //import javax.annotation.Resource; //import javax.servlet.http.HttpServletRequest; //import javax.servlet.http.HttpSession; //import java.net.URLDecoder; //import java.util.ArrayList; //import java.util.HashMap; //import java.util.List; //import java.util.Map; // //@Controller //@RequestMapping("room") ///** // * //*<p>Title:RoomControl </p> //*<p style="color:red;">Description: </p> //*<p>Company: jxxkhotel </p> //*@author gdd //*@date 2017-1-2 下午8:09:36 // */ //public class RoomControl { // // @Resource // private RoomService roomService; // @Resource // private GuestService guestService; // @Resource // private RoomCService roomCService; // @Resource // private ConService conService; // @Resource // private RTService rtService; // @Resource // private RgoodService rgoodService; // @Resource // private BalService balService; // @Resource // private HotelService hotelService; // /** // * // <p style="color:green;">Description :房间信息获取,包括动态多条件查询</p> // * Map<String,Object> // * @param // * @return // * @throws Exception // */ // @RequestMapping("/getlist.do") // @ResponseBody // public Map<String, Object> getlist(Room r, HttpSession session, PageInfo p) throws Exception{ // if(null==p.getPage()) // p.setPage(1); // if(null==p.getSize()) // p.setSize(100); // //判断是否为求房型 // if(r.getRoomType()==null){ // RoomType rt=new RoomType(); // rt.setHid(Integer.parseInt(session.getAttribute("hotelId").toString())); // r.setRoomType(rt); // } // //设默认值 // if(null==r.getRoomType().getId()) // r.setRoomType(null); // if(("").equals(r.getRoomnum())) // r.setRoomnum(null); // if(("").equals(r.getRoompwd())) // r.setRoompwd(null); // Map<String, Object> map=new HashMap<String, Object>(); // map.put("total", roomService.getTotal(r)); // map.put("rows", roomService.findcri(r, p.getPage(), p.getSize())); // return map; // } // // /* // Map<String, Object> map=new HashMap<String, Object>(); // int floor = r.getFloor() == null?0:r.getFloor(); // int state = r.getRoomstate()== null?0: r.getRoomstate(); // int rtype=0; // if(r.getRoomType()!=null) // rtype=r.getRoomType().getId()==null?0:r.getRoomType().getId(); // Map<String, Integer> m = new HashMap<String, Integer>(); // m.put("floor", floor); // m.put("roomstate", state); // m.put("roomType.id", rtype); // m.put("hotelId", Integer.parseInt(session.getAttribute("hotelId").toString())); // map.put("rows",roomService.searchbymap(m,p)); // return map; // */ // /** // * // <p style="color:green;">Description :新增房间信息</p> // * Map<String,String> // * @param r 房间信息实体类 // * @param typeid 房型id // * @param session // * @return // */ // @RequestMapping("/save.do") // @ResponseBody // public Map<String,String> save(Room r,int typeid,HttpSession session) { // r.setHid(Integer.parseInt(session.getAttribute("hotelId").toString())); // Map<String, String> map=new HashMap<String, String>(); // RoomType rt=new RoomType(); // rt.setId(typeid); // r.setRoomType(rt); // roomService.save(r); // map.put("status", "ok"); // map.put("message", "success"); // return map; // } // // /** // * // <p style="color:green;">Description :身份证合法性校验</p> // * Map<String,String> // * @param id 身份证号 // * @return String类型 // */ // @RequestMapping("/checkid.do") // @ResponseBody // public String checkid(String id){ // return IDCardCheck.checkid(id); // } // // /** // * // <p style="color:green;">Description :根据ID获得房间信息</p> // * Map<String,String> // * @param id 房间ID // * @return String类型 // */ // @RequestMapping("/getroom.do") // @ResponseBody // public Map<String, Object> getroom(int id){ // Map<String, Object> map=new HashMap<String, Object>(); // Room room=roomService.get(Room.class, id); // map.put("room", room); // map.put("resinfo", "no"); // return map; // } // /** // * // *Description:<p style="color:red">房态变更 </p> // *@param roomid 房间ID // *@param state 房间状态 // *@param remark 备注信息 // *@return “” // * @throws Exception // */ // @RequestMapping("/changestate.do") // @ResponseBody // public String update_roomstate(int roomid, int state, String remark, HttpSession session, PageInfo p) throws Exception{ // Map<String, Object> map=new HashMap<String, Object>(); // Room r=roomService.get(Room.class, roomid); // if(remark!=null) // r.setRemark(remark); // r.setRoomstate(state); // getlist(r,session,p); // return ""; // } // /** // * // *Description:<p style="color:red"> 办理入住处理 </p> // *@param roomid 房间ID // *@param g 宾客信息实体 // *@param paymethod 支付方式 // *@param deposit 押金 // *@param roomprice 房价 // *@param con 消费信息 // *@return “” // */ // @RequestMapping("/checkin.do") // @ResponseBody // public String checkin(int roomid,Guest g,int paymethod,Double deposit,double roomprice,Consumption con,int hourday,HttpSession session){ // Room r=roomService.get(Room.class, roomid); // con.setOrdernum(DateUtil.getTimes()); // con.setStarttime(DateUtil.getTime()); // con.setHid(Integer.parseInt(session.getAttribute("hotelId").toString())); // conService.save(con); // Consumption con1=conService.find(con).get(0); // //房态修改 // r.setRoomstate(5); // //是否为钟点房*******重点 !后面计算房价需要! // r.sethourday(hourday); // //房间消费清单添加 // //房费 // ffrz(roomprice,con1,""); // //押金 // Paymethod p2=new Paymethod(); // p2.setId(paymethod); // RoomConList rc2=new RoomConList(); // rc2.setItemname("入住押金"); // rc2.setItemprice(0.0); // rc2.setPayprice(deposit); // rc2.setPaymethod(p2); // rc2.setAmount(1); // rc2.setBookitime(DateUtil.getTime()); // rc2.setBookkeeper("系统"); // rc2.setTotalprice(0.0); // rc2.setConsumption(con1); // roomCService.save(rc2); // g.setRoomid(r.getId()); // //保存房间信息 // roomService.save(r); // //保存宾客信息 // guestService.save(g); // //保存账单 // return ""; // } // /** // * // <p style="color:green;">Description :结账退房</p> // * Map<String,String> // * @param id 房间id m 模型 // * @return 跳转到结账页面 // */ // @RequestMapping("/checkout.do") // public String checkout(int id,Model m){ // Map<String, Object> map=new HashMap<String, Object>(); // Room r=roomService.get(Room.class, id); // //房间号 // String roomnum=r.getRoomnum(); // //根据房间号得到入住账单号 // Consumption c1=new Consumption(); // c1.setRoomnum(roomnum); // c1.setChecked(0); // Consumption con=conService.find(c1).get(0); // map.put("con",con); // double totalmoney = 0,paymoney=0,needmoney=0; // for(int i=0;i<con.getRoomConLists().size();i++){ // RoomConList rcon= con.getRoomConLists().get(i); // totalmoney+=rcon.getTotalprice(); // paymoney+=rcon.getPayprice(); // } // needmoney=totalmoney-paymoney; // map.put("totalmoney", totalmoney); // map.put("paymoney", paymoney); // map.put("needmoney", needmoney); // //m.addAllAttributes(map); // m.addAllAttributes(map); // return "reception/checkout"; // } // // /** // * // *Description:<p style="color:red"> 结账退房,改入住单为已经计算</p> // *@param bal 收支详情单 // *@param conid 入住单 ID // *@param request // *@return // */ // @RequestMapping("/checkoutend.do") // @ResponseBody // public Map checkoutend(Balance bal,int conid,String roomnum,HttpSession session){ // Map<String, Object> map=new HashMap<String, Object>(); // Room r=roomService.find("from Room as r where r.roomnum ="+"'"+roomnum+"'").get(0); // r.setRoomstate(1); // roomService.save(r); // Consumption con=conService.get(Consumption.class, conid); // con.setChecked(1); // bal.setBilltime(DateUtil.getTime()); // bal.setMother(bal.getTotalmoney()-bal.getMcash()); // bal.setBookkeeper(session.getAttribute("username").toString()); // bal.setHid(Integer.parseInt(session.getAttribute("hotelId").toString())); // conService.save(con); // balService.save(bal); // return map; // } // // /** // * // *Description:<p style="color:red"> 计算到退房时的房价 </p> // *@param roomid // *@return // */ // @RequestMapping("/checkroomprice.do") // @ResponseBody // public String checkroomprice(int roomid){ // //收费说明 // String remark =""; // //获得系统时间 // String endtime=DateUtil.getTime(); // //房费最后一次入账时间 // String lastrztime=""; // //要增加的房费 // double addroomprice=0; // //房价 // double roomprice=0; // //得到房间信息 // Room r= roomService.get(Room.class, roomid); // int hourorday =r.gethourday();//1表示钟点房0表示天房 // //房号 // String roomnum=r.getRoomnum(); // //得到入住账单 // Consumption c1=new Consumption(); // c1.setRoomnum(roomnum); // c1.setChecked(0); // Consumption c=conService.find(c1).get(0); // //所有房间消费信息的list,为求最后一次添加房费的时间 // List<RoomConList> rclist =new ArrayList<RoomConList>(); // // //遍历房间消费列表,得到房费项目的list // for(RoomConList rc: c.getRoomConLists()){ // if(rc.getItemname().equals("房费")){ // rclist.add(rc); // } // } // //得到最后一次添加房费的时间 // lastrztime=rclist.get(rclist.size()-1).getBookitime(); // roomprice=rclist.get(rclist.size()-1).getItemprice(); // //最后一次入账时间与当前时间差几个小时 // long differhours=DateUtil.getTimeSub(lastrztime, DateUtil.getTime()); // /****钟点房记价规则****/ // if(hourorday==1&&differhours>1){ // addroomprice=roomprice*(differhours-1); // } // /*** 天房记价规则***/ // //根据最后一次入账时间与系统时间差去掉入住时记录的房费信息 // // else{ // long hours=differhours-24; // if(hours-24>0){ // //3<hours<12,追加半天房费 // if(hours>=3&&hours<12){ // addroomprice=roomprice/2; // remark="超过三小时,未超过12小时,补半天房价"+addroomprice; // } // //12<hours<24,追加一天 // else if(hours>=12&&hours<24){ // addroomprice=roomprice; // remark="超过12小时,补一天房价"+addroomprice; // } // //如果大于24小时(1天) // else { // //如果是整的天数,就增加天数*房费 // if(hours%24==0){ // addroomprice=roomprice*hours/24; // remark="补房价"+addroomprice; // } // //如果不是整天数,求余 // else { // //余数在(6,12)间整天数再加半天房 // if(hours%24<12&&hours%24>=3){ // addroomprice=roomprice*(hours/24+0.5); // remark="整天,超(3,12)补房价"+addroomprice; // } // //余数大于12按一天算 // else addroomprice=roomprice*(hours/24+1); // remark="整天,超(12,24)补房价"+addroomprice; // } // } // } // } // if(addroomprice!=0){ // // //保存消费信息 // ffrz(addroomprice, c,remark); // } // return ""; // } // // /** // * // *Description:<p style="color:red">封装房费入账 </p> // *@param roomprice // *@param con // */ // public void ffrz(double roomprice,Consumption con,String remark){ // //房费 // RoomConList rc1=new RoomConList(); // Paymethod p1=new Paymethod(); // p1.setId(2); // rc1.setRemark(remark); // rc1.setItemname("房费"); // rc1.setItemprice(roomprice); // rc1.setAmount(1); // rc1.setBookitime(DateUtil.getTime()); // rc1.setBookkeeper("系统"); // rc1.setPaymethod(p1); // rc1.setTotalprice(roomprice); // rc1.setPayprice(0.0); // rc1.setConsumption(con); // roomCService.save(rc1); // } // /** // * // *Description:<p style="color:red">遍历房间类型表获得动态添加房态图的tabs </p> // *@return // */ // @RequestMapping("/getrtype.do") // @ResponseBody // public Map<String, Object> getrtype(String typeid, Integer hid, RoomType rtype, PageInfo p, HttpSession session, String act){ // Map<String, Object> map=new HashMap<String, Object>(); // //判断是否是根据房型求房间 // //typeid为null则求房型combox // if(typeid==null){ // if(hid==null) // hid=Integer.parseInt(session.getAttribute("hotelId").toString()); // List<RoomType> rtlist=new ArrayList<RoomType>(); // //判断是否为求房型列表 // if("".equals(act)||null==act){ // rtype.setHid(hid); // try { // if("".equals(rtype.getState()))rtype.setState(null); // if("".equals(rtype.getSprice()))rtype.setSprice(null); // if("".equals(rtype.getTypecode()))rtype.setTypecode(null); // if("".equals(rtype.getTypename()))rtype.setTypename(null); // rtlist=rtService.find(rtype,p.getPage(),p.getSize()); // } catch (Exception e) { // e.printStackTrace(); // } // map.put("total", rtService.find(rtype).size()); // map.put("rows", rtlist); // } // else { // System.out.println("getrtype.do hid="+hid); // rtlist=rtService.find("from RoomType as rt where rt.hid="+hid+"and rt.state = 1 "); // map.put("rtlist", rtlist); // } // } // //否则求此房型下所有可以预定的房间号 // else{ // RoomType rt=rtService.get(RoomType.class, Integer.parseInt(typeid)); // List<Room> rooms=new ArrayList<Room>(); // for(Room r:rt.getRooms()){ // //判断房态只有为空房或者打扫的房间才可以预定 // if(r.getRoomstate()==1||r.getRoomstate()==3){ // rooms.add(r); // } // } // map.put("rooms", rooms); // } // return map; // } // /** // * // *Description:<p style="color:red">预订入住 </p> // *@param id 房间ID // *@return // */ // @RequestMapping("/resin.do") // @ResponseBody // public Map<String, Object> resin(int id){ // Map<String,Object> map=new HashMap<String, Object>(); // Room r=roomService.get(Room.class, id); // return map; // } // /** // * // *Description:<p style="color:red"> 通过房间ID 获得房间消费信息</p> // *@param roomid // *@return // */ // @RequestMapping("/getconsumpt.do") // @ResponseBody // public Map<String, Object> getconsumption(int roomid){ // Map<String,Object> map=new HashMap<String, Object>(); // Room r=roomService.get(Room.class, roomid); // Consumption c1=new Consumption(); // c1.setRoomnum(r.getRoomnum()); // c1.setChecked(0); // Consumption con=conService.find(c1).get(0); // con.setRoomConLists(null); // map.put("con",con); // return map; // } // /** // * // *Description:<p style="color:red">得到所有房间消费品表 </p> // *@param rg 房间商品信息实体 // *@param p 分页参数 // *@return // *@throws Exception // */ // @RequestMapping("/goodlist.do") // @ResponseBody // public Map<String, Object> addgoon(Rgood rg,PageInfo p) throws Exception{ // Map<String, Object> map=new HashMap<String, Object>(); // List<Rgood> rglist=rgoodService.find(rg, p.getPage(), p.getSize()); // map.put("total", rglist.size()); // map.put("rows", rglist); // return map; // } // /** // * // *Description:<p style="color:red"> 添加商品信息到房间消费账单</p> // *@param conid // *@param goodid // *@param request // *@return // */ // @RequestMapping("/sureadd.do") // @ResponseBody // public String sureaddgood(int conid,int goodid,HttpServletRequest request){ // Rgood rg=rgoodService.get(Rgood.class, goodid); // rg.setAmount(rg.getAmount()-1); // rgoodService.save(rg); // Consumption con=conService.get(Consumption.class, conid); // Paymethod paymethod=new Paymethod(); // paymethod.setId(2); // Map<String, Object> map=new HashMap<String, Object>(); // RoomConList rc=new RoomConList(); // rc.setAmount(1); // rc.setBookitime(DateUtil.getTime()); // rc.setBookkeeper(request.getSession().getAttribute("username").toString()); // rc.setItemname(rg.getSpname()); // rc.setItemprice(rg.getSpprice()); // rc.setPaymethod(paymethod); // rc.setTotalprice(rg.getSpprice()); // rc.setConsumption(con); // roomCService.save(rc); // return "ok"; // } // /** // * 特价房的设置 // * @param roomid 房间id // * @param relprice 实际价格 // * @return // */ // @RequestMapping("/changerelprice.do") // @ResponseBody // public Map<String, String> changerelprice(int roomid,double relprice){ // Map<String, String> map=new HashMap<String, String>(); // Room r=roomService.get(Room.class, roomid); // r.setRelprice(relprice); // roomService.save(r); // map.put("msg", "ok"); // return map; // // } // /** // * // *<p>Description: 房间宾客信息查询</p> // * @param g 查询的宾客信息 // * @return // * @throws Exception // */ // @RequestMapping("/searchinfo.do") // @ResponseBody // public Map<String, Object> searchinfo(Guest g) throws Exception{ // if(g.getGuestname()!=null) // g.setGuestname(URLDecoder.decode(g.getGuestname(), "UTF-8")); // Map<String, Object> map=new HashMap<String, Object>(); // List<Room> rlist= new ArrayList<Room>(); // List<Guest> glist=guestService.findcri(g, 1, 10); // if(glist.size()!=0){ // Guest sg=glist.get(0); // Room room=roomService.get(Room.class, sg.getRoomid()); // if(room.getRoomstate()==2||room.getRoomstate()==5) // { // rlist.add(room); // map.put("msg", "ok"); // map.put("rows",rlist); // } // else{ // map.put("msg", "error"); // map.put("tip","可到历史入住信息查找" ); // } // } // else{ // map.put("msg", "error"); // map.put("tip","未找到符合搜索信息的宾客" ); // } // return map; // } // // /*@RequestMapping("/crisearch.do") // @ResponseBody // public Map<String, Object> crisearch(Members m,PageInfo p,HttpSession session) throws Exception{ // if(m.getMemType()==null){ // MemType mt=new MemType(); // mt.setId(0); // mt.setHid(Integer.parseInt(session.getAttribute("hotelId").toString())); // m.setMemType(mt); // } // if(m.getMemType().getId()==0) // m.setMemType(null); // if(("").equals(m.getMemnum())) // m.setMemnum(null); // if(("").equals(m.getMemname())) // m.setMemname(null); // Map<String, Object> map=new HashMap<String, Object>(); // map.put("total", memService.getTotal(m)); // map.put("rows", memService.findcri(m, p.getPage(), p.getSize())); // //map.put("memlist", memService.findcriteria(m, 1, 5)); // return map; // }*/ // /** // * // *<p>Description:保存房间信息</p> // * @param o 前台接收的数据 // * @return // */ // @RequestMapping("/update.do") // @ResponseBody // public Map<String, String> update(Room r,int roomtype,HttpSession session){ // Map<String, String> map= new HashMap<String, String>(); // Room room=roomService.get(Room.class, r.getId()); // room.setFloor(r.getFloor()); // room.setWindow(r.getWindow()); // room.setRelprice(r.getRelprice()); // room.setHid(Integer.parseInt(session.getAttribute("hotelId").toString())); // room.setRoompwd(r.getRoompwd()); // room.setRoomnum(r.getRoomnum()); // room.setState(r.getState()); // RoomType rt=new RoomType(); // rt.setId(roomtype); // room.setRoomType(rt); // roomService.update(room); // map.put("status", "提示"); // map.put("msg", "修改成功"); // return map; // // } // /** // * // *<p>Description:删除房间 </p> // * @param roomid 房间ID // * @return 提示信息 // */ // @RequestMapping("/delete.do") // @ResponseBody // public Map<String, String> delete(int roomid){ // Map<String, String> map= new HashMap<String, String>(); // Room r=roomService.get(Room.class, roomid); // roomService.delete(r); // map.put("status", "提示"); // map.put("msg", "删除成功"); // return map; // } // /** // * // *<p>Description:删除房间 </p> // * @param roomid 房间ID // * @return 提示信息 // */ // @RequestMapping("/delete_roomtype.do") // @ResponseBody // public Map<String, String> delete_roomtype(int id){ // Map<String, String> map= new HashMap<String, String>(); // RoomType rt=new RoomType(); // rt.setId(id); // rtService.delete(rt); // map.put("status", "提示"); // map.put("msg", "删除成功"); // return map; // // } // /** // * // *<p>Description:  房型的管理</p> // * @param rt 房型信息 // * @param session // * @return // */ // @RequestMapping("/update_roomtype.do") // @ResponseBody // public Map<String, String> update_roomtype(RoomType rt,HttpSession session){ // Map<String, String> map= new HashMap<String, String>(); // rt.setHid(Integer.parseInt(session.getAttribute("hotelId").toString())); // rtService.saveOrupdate(rt); // map.put("status", "提示"); // map.put("msg", "修改成功"); // return map; // } // // /** // * // *<p>Description: 得到酒店列表</p> // * @return // */ // @RequestMapping("/gethotel.do") // @ResponseBody // public Map<String, Object> gethotel(){ // Map<String, Object> map=new HashMap<String, Object>(); // map.put("hlist", hotelService.find("from Hotel")); // return map; // } // //}
true
7a4e95bfb61d06c1f24606df59c4400cc5dc9961
Java
md5checksum/acume
/cache/src/main/java/com/guavus/acume/cache/utility/SQLUtility.java
UTF-8
2,063
2.265625
2
[]
no_license
package com.guavus.acume.cache.utility; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import net.sf.jsqlparser.JSQLParserException; import net.sf.jsqlparser.parser.CCJSqlParserManager; import net.sf.jsqlparser.statement.Statement; import net.sf.jsqlparser.statement.select.Select; import com.guavus.acume.cache.common.AcumeConstants; /** * @author archit.thakur */ public class SQLUtility { public List<Tuple> getList(String qx) { List<Tuple> list = new ArrayList<Tuple>(); try{ CCJSqlParserManager sql = SQLParserFactory.getParserManager(); Statement statement = sql.parse(new StringReader(qx)); ((Select)statement).getSelectBody().accept(new QuerySelectClauseVisitor(0l, 0l, null, list)); return list; } catch (JSQLParserException e) { e.printStackTrace(); } return list; } public String getRequestType(String qx) { RequestType requestType = new RequestType(); requestType.setRequestType(AcumeConstants.Aggregate()); try{ CCJSqlParserManager sql = SQLParserFactory.getParserManager(); Statement statement = sql.parse(new StringReader(qx)); ((Select)statement).getSelectBody().accept(new Visitor(requestType)); return requestType.getRequestType(); } catch (JSQLParserException e) { e.printStackTrace(); } return requestType.getRequestType(); } public static void main(String args[]) { SQLUtility util = new SQLUtility(); List<Tuple> list = util.getList("select * from ((select * from (select * from (t full outer join b) where ts < 105 and ts >=10 and binsource = mybinsource)) full outer join xt) as T where ts<10 and ts >=104 and binsource = ifjkdh"); System.out.println(util.getRequestType("select ts,x from ((select * from (select * from (t full outer join b) where ts < 105 and ts >=10)) full outer join xt) as T where ts<10 and ts >=104")); for (Tuple tx: list) { System.out.println(tx.getStartTime()); System.out.println(tx.getEndTime()); System.out.println(tx.getBinsource()); System.out.println(tx.getCubeName()); } } }
true
0b0bf531e3bd3402974c553acf561a506fcc9738
Java
W12woj34/ZPI_hr-app
/src/main/java/pwr/zpi/hrapp/service/mapper/LoginMapper.java
UTF-8
235
1.609375
2
[]
no_license
package pwr.zpi.hrapp.service.mapper; import org.mapstruct.Mapper; import pwr.zpi.hrapp.dto.Login; import pwr.zpi.hrapp.persistance.entities.LoginEntity; @Mapper public interface LoginMapper extends BaseMapper<Login, LoginEntity> {}
true
9e4a375e823b90a782a1f85cc314cf9cd79b4f95
Java
guaracy/Android-LAMW
/Polias/src/org/lamw/polias/jDrawingView.java
UTF-8
48,912
2.015625
2
[]
no_license
package org.lamw.polias; import java.io.File; import java.io.FileOutputStream; import java.lang.reflect.Field; import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.CornerPathEffect; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.Layout; import android.text.StaticLayout; import android.text.TextPaint; import android.util.Log; import android.util.SparseArray; import android.util.TypedValue; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener; import android.view.View; import android.view.ViewGroup; import java.nio.charset.Charset; /*Draft java code by "Lazarus Android Module Wizard" [5/20/2016 3:18:58]*/ /*https://github.com/jmpessoa/lazandroidmodulewizard*/ /*jVisualControl template*/ public class jDrawingView extends View /*dummy*/ { //please, fix what GUI object will be extended! private long pascalObj = 0; // Pascal Object private Controls controls = null; // Control Class for events private jCommons LAMWCommon; private Context context = null; private Boolean enabled = true; // click-touch enabled! private Bitmap mBitmap; private Canvas mCanvas = null; //offscreen canvas private Paint mDrawPaint = null; private TextPaint mTextPaint = null; private Path mPath = null; private OnClickListener onClickListener; // click event private GestureDetector gDetect; private ScaleGestureDetector scaleGestureDetector; private float mScaleFactor = 1.0f; private float mMinZoom = 0.25f; private float mMaxZoom = 4.0f; int mPinchZoomGestureState = 3;//pzNone int mFling = 0; float mPointX[]; //five fingers float mPointY[]; //five fingers int mCountPoint = 0; private SparseArray<PointF> mActivePointers; private int mBackgroundColor; // = Color.WHITE; private boolean mBufferedDraw = false; private int mWidth; private int mHeight; private Paint.Style mStyle; private long mLastClickTime = 0; private int mTimeClick = 250; private int mTimeDoubleClick = 350; private final Charset UTF8_CHARSET = Charset.forName("UTF-8"); //GUIDELINE: please, preferentially, init all yours params names with "_", ex: int _flag, String _hello ... public jDrawingView(Controls _ctrls, long _Self, boolean _bufferedDraw, int _backgroundColor) { //Add more others news "_xxx"p arams if needed! super(_ctrls.activity); context = _ctrls.activity; pascalObj = _Self; controls = _ctrls; mBufferedDraw = _bufferedDraw; if (_backgroundColor != 0) mBackgroundColor = _backgroundColor; else mBackgroundColor = Color.TRANSPARENT; this.setBackgroundColor(mBackgroundColor); //this.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN); LAMWCommon = new jCommons(this, context, pascalObj); mTextPaint = new TextPaint();//new Paint(); //mPaint.setStyle(Paint.Style.STROKE); mTextPaint.setFlags(Paint.ANTI_ALIAS_FLAG); float ts = mTextPaint.getTextSize(); //default 12 float unit = controls.activity.getResources().getDisplayMetrics().density; mTextPaint.setTextSize(ts*unit); //ts * unit mDrawPaint = new Paint(); //used to draw shapes and lines ... mPath = new Path(); mCountPoint = 0; mActivePointers = new SparseArray<PointF>(); onClickListener = new OnClickListener() { /*.*/ public void onClick(View view) { //please, do not remove /*.*/ mask for parse invisibility! if (enabled) { //controls.pOnClick(PasObj, Const.Click_Default); //JNI event onClick! } } ; }; setOnClickListener(onClickListener); gDetect = new GestureDetector(controls.activity, new GestureListener()); scaleGestureDetector = new ScaleGestureDetector(controls.activity, new simpleOnScaleGestureListener()); mStyle = mTextPaint.getStyle(); } //end constructor public void jFree() { //free local objects... mTextPaint = null; mCanvas = null; gDetect = null; mDrawPaint = null; mBitmap = null; mPath = null; setOnClickListener(null); scaleGestureDetector = null; LAMWCommon.free(); } public long GetPasObj() { return LAMWCommon.getPasObj(); } public void SetViewParent(ViewGroup _viewgroup) { LAMWCommon.setParent(_viewgroup); } public ViewGroup GetParent() { return LAMWCommon.getParent(); } public void RemoveFromViewParent() { LAMWCommon.removeFromViewParent(); } public void SetLeftTopRightBottomWidthHeight(int left, int top, int right, int bottom, int w, int h) { LAMWCommon.setLeftTopRightBottomWidthHeight(left, top, right, bottom, w, h); } public void SetLParamWidth(int w) { LAMWCommon.setLParamWidth(w); } public void SetLParamHeight(int h) { LAMWCommon.setLParamHeight(h); } public int GetLParamHeight() { return LAMWCommon.getLParamHeight(); } public int GetLParamWidth() { return LAMWCommon.getLParamWidth(); } public void SetLGravity(int _g) { LAMWCommon.setLGravity(_g); } public void SetLWeight(float _w) { LAMWCommon.setLWeight(_w); } public void AddLParamsAnchorRule(int rule) { LAMWCommon.addLParamsAnchorRule(rule); } public void AddLParamsParentRule(int rule) { LAMWCommon.addLParamsParentRule(rule); } public void SetLayoutAll(int idAnchor) { LAMWCommon.setLayoutAll(idAnchor); } public void ClearLayoutAll() { LAMWCommon.clearLayoutAll(); } public View GetView() { return this; } //write others [public] methods code here...... //GUIDELINE: please, preferentially, init all yours params names with "_", ex: int _flag, String _hello ... @Override /*.*/ public boolean dispatchTouchEvent(MotionEvent e) { super.dispatchTouchEvent(e); this.gDetect.onTouchEvent(e); this.scaleGestureDetector.onTouchEvent(e); return true; } //http://android-er.blogspot.com.br/2014/05/cannot-detect-motioneventactionmove-and.html //http://www.vogella.com/tutorials/AndroidTouch/article.html @Override public boolean onTouchEvent(MotionEvent event) { int act = event.getAction() & MotionEvent.ACTION_MASK; //get pointer index from the event object int pointerIndex = event.getActionIndex(); // get pointer ID int pointerId = event.getPointerId(pointerIndex); switch (act) { case MotionEvent.ACTION_DOWN: { PointF f = new PointF(); f.x = event.getX(pointerIndex); f.y = event.getY(pointerIndex); mActivePointers.put(pointerId, f); mPointX = new float[mActivePointers.size()]; //fingers mPointY = new float[mActivePointers.size()]; //fingers for (int size = mActivePointers.size(), i = 0; i < size; i++) { PointF point = mActivePointers.valueAt(i); if (point != null) { mPointX[i] = point.x; mPointY[i] = point.y; } } byte mAction = Const.TouchDown; // double click event long mClickTime = controls.getTick(); if ((mClickTime - mLastClickTime) < mTimeDoubleClick) { mAction = Const.DoubleClick; } mLastClickTime = mClickTime; controls.pOnDrawingViewTouch(pascalObj, mAction/*Const.TouchDown*/, mActivePointers.size(), mPointX, mPointY, mFling, mPinchZoomGestureState, mScaleFactor); break; } case MotionEvent.ACTION_MOVE: { for (int size = event.getPointerCount(), i = 0; i < size; i++) { PointF point = mActivePointers.get(event.getPointerId(i)); if (point != null) { point.x = event.getX(i); point.y = event.getY(i); } } mPointX = new float[mActivePointers.size()]; //fingers mPointY = new float[mActivePointers.size()]; //fingers for (int size = mActivePointers.size(), i = 0; i < size; i++) { PointF point = mActivePointers.valueAt(i); if (point != null) { mPointX[i] = point.x; mPointY[i] = point.y; } } controls.pOnDrawingViewTouch(pascalObj, Const.TouchMove, mActivePointers.size(), mPointX, mPointY, mFling, mPinchZoomGestureState, mScaleFactor); break; } case MotionEvent.ACTION_UP: { for (int size = event.getPointerCount(), i = 0; i < size; i++) { PointF point = mActivePointers.get(event.getPointerId(i)); if (point != null) { point.x = event.getX(i); point.y = event.getY(i); } } mPointX = new float[mActivePointers.size()]; //fingers mPointY = new float[mActivePointers.size()]; //fingers for (int size = mActivePointers.size(), i = 0; i < size; i++) { PointF point = mActivePointers.valueAt(i); if (point != null) { mPointX[i] = point.x; mPointY[i] = point.y; } } // click event if ((controls.getTick() - mLastClickTime) < mTimeClick) { controls.pOnDrawingViewTouch(pascalObj, Const.Click, mActivePointers.size(), mPointX, mPointY, mFling, mPinchZoomGestureState, mScaleFactor); } controls.pOnDrawingViewTouch(pascalObj, Const.TouchUp, mActivePointers.size(), mPointX, mPointY, mFling, mPinchZoomGestureState, mScaleFactor); break; } case MotionEvent.ACTION_POINTER_DOWN: { PointF f = new PointF(); f.x = event.getX(pointerIndex); f.y = event.getY(pointerIndex); mActivePointers.put(pointerId, f); mPointX = new float[mActivePointers.size()]; //fingers mPointY = new float[mActivePointers.size()]; //fingers for (int size = mActivePointers.size(), i = 0; i < size; i++) { PointF point = mActivePointers.valueAt(i); if (point != null) { mPointX[i] = point.x; mPointY[i] = point.y; } } controls.pOnDrawingViewTouch(pascalObj, Const.TouchDown, mActivePointers.size(), mPointX, mPointY, mFling, mPinchZoomGestureState, mScaleFactor); break; } case MotionEvent.ACTION_POINTER_UP: { for (int size = event.getPointerCount(), i = 0; i < size; i++) { PointF point = mActivePointers.get(event.getPointerId(i)); if (point != null) { point.x = event.getX(i); point.y = event.getY(i); } } mPointX = new float[mActivePointers.size()]; //fingers mPointY = new float[mActivePointers.size()]; //fingers for (int size = mActivePointers.size(), i = 0; i < size; i++) { PointF point = mActivePointers.valueAt(i); if (point != null) { mPointX[i] = point.x; mPointX[i] = point.y; } } controls.pOnDrawingViewTouch(pascalObj, Const.TouchUp, mActivePointers.size(), mPointX, mPointY, mFling, mPinchZoomGestureState, mScaleFactor); break; } case MotionEvent.ACTION_CANCEL: { mActivePointers.remove(pointerId); break; } } return true; } //ref1. http://code.tutsplus.com/tutorials/android-sdk-detecting-gestures--mobile-21161 //ref2. http://stackoverflow.com/questions/9313607/simpleongesturelistener-never-goes-in-to-the-onfling-method //ref3. http://x-tutorials.blogspot.com.br/2011/11/detect-pinch-zoom-using.html private class GestureListener extends GestureDetector.SimpleOnGestureListener { private static final int SWIPE_MIN_DISTANCE = 60; private static final int SWIPE_THRESHOLD_VELOCITY = 100; @Override public boolean onDown(MotionEvent event) { //Log.i("Down", "------------"); return true; } @Override public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) { if (event1.getX() - event2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { mFling = 0; //onRightToLeft; return true; } else if (event2.getX() - event1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { mFling = 1; //onLeftToRight(); return true; } if (event1.getY() - event2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) { mFling = 2; //onBottomToTop(); return false; } else if (event2.getY() - event1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) { mFling = 3; //onTopToBottom(); return false; } return false; } } //ref. http://vivin.net/2011/12/04/implementing-pinch-zoom-and-pandrag-in-an-android-view-on-the-canvas/ private class simpleOnScaleGestureListener extends SimpleOnScaleGestureListener { //TPinchZoomScaleState = (pzScaleBegin, pzScaling, pzScaleEnd, pxNone); @Override public boolean onScale(ScaleGestureDetector detector) { mScaleFactor *= detector.getScaleFactor(); mScaleFactor = Math.max(mMinZoom, Math.min(mScaleFactor, mMaxZoom)); mPinchZoomGestureState = 1; return true; } @Override public boolean onScaleBegin(ScaleGestureDetector detector) { mScaleFactor = detector.getScaleFactor(); mPinchZoomGestureState = 0; return true; } @Override public void onScaleEnd(ScaleGestureDetector detector) { mScaleFactor = detector.getScaleFactor(); mPinchZoomGestureState = 2; super.onScaleEnd(detector); } } public Bitmap GetDrawingCache() { if (mBufferedDraw) { return mBitmap; } else { this.setDrawingCacheEnabled(true); Bitmap b = Bitmap.createBitmap(this.getDrawingCache()); this.setDrawingCacheEnabled(false); return b; } } public Paint GetPaint() { return mDrawPaint; } @Override protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) { super.onSizeChanged(width, height, oldWidth, oldHeight); mWidth = width; mHeight = height; if (mBufferedDraw) { // Create bitmap, create canvas with bitmap, fill canvas with color. mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); mCanvas = new Canvas(mBitmap); // Fill the Bitmap with the background color. if (mBackgroundColor != 0 ) mCanvas.drawColor(mBackgroundColor); else mCanvas.drawColor(Color.WHITE); } controls.pOnDrawingViewSizeChanged(pascalObj, width, height, oldWidth, oldHeight); } // @Override /*.*/ public void onDraw(Canvas canvas) { //super.onDraw(canvas); if (mBufferedDraw) canvas.drawBitmap(mBitmap,0,0,null); //mDrawPaint draw offscreen changes else mCanvas = canvas; controls.pOnDrawingViewDraw(pascalObj, Const.TouchUp, mActivePointers.size(), mPointX, mPointY, mFling, mPinchZoomGestureState, mScaleFactor); } public void SaveToFile(String _filename) { Bitmap image = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); Canvas c = new Canvas(image); draw(c); FileOutputStream fos = null; try { fos = new FileOutputStream(_filename); if (fos != null) { if (_filename.toLowerCase().contains(".jpg")) image.compress(Bitmap.CompressFormat.JPEG, 90, fos); if (_filename.toLowerCase().contains(".png")) image.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.close(); } } catch (Exception e) { Log.e("jDrawingView_SaveImage1", "Exception: " + e.toString()); } } public void SaveToFile(String _path, String _filename) { Bitmap image = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); Canvas c = new Canvas(image); draw(c); File file = new File(_path + "/" + _filename); if (file.exists()) file.delete(); try { FileOutputStream out = new FileOutputStream(file); if (_filename.toLowerCase().contains(".jpg")) image.compress(Bitmap.CompressFormat.JPEG, 90, out); if (_filename.toLowerCase().contains(".png")) image.compress(Bitmap.CompressFormat.PNG, 100, out); out.flush(); out.close(); } catch (Exception e) { Log.e("jDrawingView_Save", "Exception: " + e.toString()); } } public int GetHeight() { return getHeight(); } public int GetWidth() { return getWidth(); } private Bitmap GetResizedBitmap(Bitmap _bitmap, int _newWidth, int _newHeight) { float factorH = _newHeight / (float) _bitmap.getHeight(); float factorW = _newWidth / (float) _bitmap.getWidth(); float factorToUse = (factorH > factorW) ? factorW : factorH; Bitmap bm = Bitmap.createScaledBitmap(_bitmap, (int) (_bitmap.getWidth() * factorToUse), (int) (_bitmap.getHeight() * factorToUse), false); return bm; } // in drawing functions where the rotation, translation or scale matrix is ​​not used, the following function calls are not needed: // mCanvas.save () ; // mCanvas.restore (); // example: public void DrawBitmap(Bitmap _bitmap, int _width, int _height) { if (mCanvas == null) return; Bitmap bmp = GetResizedBitmap(_bitmap, _width, _height); Rect rect = new Rect(0, 0, _width, _height); //mCanvas.save(); // not needed! fixed by Kordal mCanvas.drawBitmap(bmp, null, rect, mDrawPaint); //mCanvas.restore(); // not needed! } // new by Kordal private String decodeUTF8(byte[] bytes) { return new String(bytes, UTF8_CHARSET); //return new String(bytes); } // new by Kordal public void DrawText(byte[] _text, float _x, float _y) { mCanvas.drawText(decodeUTF8(_text), _x, _y, mTextPaint); } public void DrawBitmap(Bitmap _bitmap, float _x, float _y, float _angleDegree) { if (mCanvas == null) return; int x = (int) _x; int y = (int) _y; Bitmap bmp = GetResizedBitmap(_bitmap, _bitmap.getWidth(), _bitmap.getHeight()); mCanvas.save(); // needed, uses rotate matrix mCanvas.rotate(_angleDegree, x + _bitmap.getWidth() / 2, y + _bitmap.getHeight() / 2); mCanvas.drawBitmap(bmp, x, y, null); mCanvas.restore(); } public void DrawCroppedBitmap(Bitmap _bitmap, float _x, float _y, int _cropOffsetLeft, int _cropOffsetTop, int _cropWidth, int _cropHeight) { if (mCanvas == null) return; Bitmap croppedBitmap = Bitmap.createBitmap(_bitmap,_cropOffsetLeft , _cropOffsetTop, _cropWidth, _cropHeight); int w = croppedBitmap.getWidth(); int h = croppedBitmap.getHeight(); Bitmap bmp = GetResizedBitmap(croppedBitmap, w, h); mCanvas.save(); mCanvas.drawBitmap(bmp, (int)_x, (int)_y, null); mCanvas.restore(); } public void DrawBitmap(Bitmap _bitmap, int _left, int _top, int _right, int _bottom) { /* Figure out which way needs to be reduced less */ /* int scaleFactor = 1; if ((right > 0) && (bottom > 0)) { scaleFactor = Math.min(bitmap.getWidth()/(right-left), bitmap.getHeight()/(bottom-top)); } */ if (mCanvas == null) return; Rect rect = new Rect(_left, _top, _right, _bottom); if ((_bitmap.getHeight() > GL10.GL_MAX_TEXTURE_SIZE) || (_bitmap.getWidth() > GL10.GL_MAX_TEXTURE_SIZE)) { int nh = (int) (_bitmap.getHeight() * (512.0 / _bitmap.getWidth())); Bitmap scaled = Bitmap.createScaledBitmap(_bitmap, 512, nh, true); mCanvas.save(); mCanvas.drawBitmap(scaled, null, rect, mDrawPaint); mCanvas.restore(); //??? } else { mCanvas.save(); mCanvas.drawBitmap(_bitmap, null, rect, mDrawPaint); mCanvas.restore(); } } public void SetPaintWidth(float _width) { mDrawPaint.setStrokeWidth(_width); } public void SetPaintStyle(int _style) { switch (_style) { case 0: { mDrawPaint.setStyle(mStyle); break; } case 1: { mDrawPaint.setStyle(Paint.Style.FILL); break; } case 2: { mDrawPaint.setStyle(Paint.Style.FILL_AND_STROKE); break; } case 3: { mDrawPaint.setStyle(Paint.Style.STROKE); break; } } } //https://guides.codepath.com/android/Basic-Painting-with-Views :: TODO DeviceDimensionsHelper.java utility public void SetPaintStrokeJoin(int _strokeJoin) { switch (_strokeJoin) { case 1: { mDrawPaint.setStrokeJoin(Paint.Join.ROUND); break; } } } public void SetPaintStrokeCap(int _strokeCap) { switch (_strokeCap) { case 1: { mDrawPaint.setStrokeCap(Paint.Cap.ROUND); break; } } } public void SetPaintCornerPathEffect(float _radius) { mDrawPaint.setPathEffect(new CornerPathEffect(_radius)); } public void SetPaintDashPathEffect(float _lineDash, float _dashSpace, float _phase) { mDrawPaint.setPathEffect(new DashPathEffect(new float[]{_lineDash, _dashSpace}, _phase)); } public void SetPaintColor(int _color) { mTextPaint.setColor(_color); mDrawPaint.setColor(_color); } public void SetTextSize(float _textSize) { float unit = controls.activity.getResources().getDisplayMetrics().density; mTextPaint.setTextSize(_textSize*unit); //_textSize * unit } public void SetTypeface(int _typeface) { Typeface t = null; switch (_typeface) { case 0: { t = Typeface.DEFAULT; break;} case 1: { t = Typeface.SANS_SERIF; break;} case 2: { t = Typeface.SERIF; break;} case 3: { t = Typeface.MONOSPACE; break;} } mTextPaint.setTypeface(t); } public void DrawLine(float _x1, float _y1, float _x2, float _y2) { if (mCanvas == null) return; mCanvas.drawLine(_x1, _y1, _x2, _y2, mDrawPaint); } public float[] GetTextBox(String _text, float _x, float _y) { float[] r = new float[4]; r[0]= _x; //left r[1]= _y - GetTextHeight(_text); //top r[2]= _x + GetTextWidth(_text); //right r[3]= _y; //bottom return r; } class Pointf{ public float x; public float y; } private Pointf[] GetTextBoxEx(String _text, float _x, float _y) { Pointf[] box = new Pointf[4]; for(int i = 0; i < 4 ; i++) { box[i] = new Pointf(); } box[0].x = _x; //left box[0].y = _y - GetTextHeight(_text); //top box[1].x = _x + GetTextWidth(_text); //right box[1].y = _y - GetTextHeight(_text); //top box[2].x = _x; //left box[2].y = _y; //bottom box[3].x = _x + GetTextWidth(_text); //right box[3].y = _y; //bottom //DrawLine(box[0].x, box[0].y, box[1].x, box[1].y); //DrawLine(box[2].x, box[2].y, box[3].x, box[3].y); //DrawLine(box[0].x, box[0].y, box[2].x, box[2].y); //DrawLine(box[1].x, box[1].y, box[3].x, box[3].y); return box; } public float[] GetTextBox(String _text, float _x, float _y, float _angleDegree, boolean _rotateCenter) { if (mCanvas == null) return null; //draw bounding rect before rotating text Pointf[] box = GetTextBoxEx(_text, _x, _y); Pointf c; //center float[] r8 = new float[8]; //return Rect rect = new Rect(); mTextPaint.getTextBounds(_text, 0, _text.length(), rect); mCanvas.save(); //rotate the canvas on center of the text to draw if (_rotateCenter) { mCanvas.rotate(_angleDegree, _x + rect.exactCenterX(), _y + rect.exactCenterY()); } else { mCanvas.rotate(_angleDegree, _x, _y); } //mCanvas.drawText(_text, _x, _y, mTextPaint); mCanvas.restore(); if (_rotateCenter) { c = GetTextCenter(box[0],box[3]); }else { c = box[2]; } Pointf[] rotatedBox = GetRotatedBoxEx(box, c, _angleDegree); r8[0] = rotatedBox[0].x; //left-top r8[1] = rotatedBox[0].y; r8[2] = rotatedBox[1].x; //right-top r8[3] = rotatedBox[1].y; r8[4] = rotatedBox[2].x; //left-bottom r8[5] = rotatedBox[2].y; r8[6] = rotatedBox[3].x; //right-bottom r8[7] = rotatedBox[3].y; return r8; } public void DrawText(String _text, float _x, float _y) { if (mCanvas == null) return; mCanvas.drawText(_text, _x, _y, mTextPaint); //float[] r = GetTextBox(_text, _x, _y); //DrawRect(r[0],r[1],r[2], r[3]); } public float[] DrawTextEx(String _text, float _x, float _y) { DrawText(_text, _x, _y); float[] r = GetTextBox(_text, _x, _y); //DrawRect(r[0],r[1],r[2], r[3]); return r; } public void DrawText(String _text, float _x, float _y, float _angleDegree) { DrawText(_text, _x, _y, _angleDegree, false); } public Pointf GetTextCenter(Pointf d1, Pointf d2) { Pointf c = new Pointf(); c.x = (d1.x +d2.x)/2; c.y = (d1.y + d2.y)/2; return c; } //https://stackoverflow.com/questions/20936429/rotating-a-rectangle-shaped-polygon-around-its-center-java public float[] rotatePoint(float x, float y, float cx, float cy, float angle) { float[] r = new float[2]; float radian=(float)angle*3.14f/180; //TRANSLATE TO ORIGIN float x1 = x - cx; float y1 = y - cy; //APPLY ROTATION double temp_x1 = (x1 * Math.cos(radian) - y1 * Math.sin(radian)); double temp_y1 = (x1 * Math.sin(radian) + y1 * Math.cos(radian)); //TRANSLATE BACK r[0] = (float) temp_x1 + cx; r[1] = (float) temp_y1 + cy; return r; } public float[] GetRotatedBox(float x1, float y1, float x2, float y2, float _angleDegree) { float[] r = new float[4]; float[] p; r[0] = x1; r[1] = y1; p = rotatePoint(x2, y2, x1, y1, _angleDegree); r[2] = p[0]; r[3] = p[1]; return r; } private Pointf[] GetRotatedBoxEx(Pointf[] box, Pointf _rotateCenter, float _angleDegree) { int count = box.length; float[] p; Pointf[] r = new Pointf[count]; for(int i = 0; i < count ; i++) { r[i] = new Pointf(); } for(int i = 0; i < count; i++) { p = rotatePoint(box[i].x, box[i].y, _rotateCenter.x, _rotateCenter.y, _angleDegree); r[i].x = p[0]; r[i].y = p[1]; } return r; } public void DrawText(String _text, float _x, float _y, float _angleDegree, boolean _rotateCenter) { if (mCanvas == null) return; Rect rect = new Rect(); mTextPaint.getTextBounds(_text, 0, _text.length(), rect); mCanvas.save(); //rotate the canvas on center of the text to draw if (_rotateCenter) { mCanvas.rotate(_angleDegree, _x + rect.exactCenterX(), _y + rect.exactCenterY()); } else { mCanvas.rotate(_angleDegree, _x, _y); } mCanvas.drawText(_text, _x, _y, mTextPaint); mCanvas.restore(); } public float[] DrawTextEx(String _text, float _x, float _y, float _angleDegree, boolean _rotateCenter) { if (mCanvas == null) return null; //draw bounding rect before rotating text Pointf[] box = GetTextBoxEx(_text, _x, _y); Pointf c; //center float[] r8 = new float[8]; //return Rect rect = new Rect(); mTextPaint.getTextBounds(_text, 0, _text.length(), rect); mCanvas.save(); //rotate the canvas on center of the text to draw if (_rotateCenter) { mCanvas.rotate(_angleDegree, _x + rect.exactCenterX(), _y + rect.exactCenterY()); } else { mCanvas.rotate(_angleDegree, _x, _y); } mCanvas.drawText(_text, _x, _y, mTextPaint); mCanvas.restore(); if (_rotateCenter) { c = GetTextCenter(box[0],box[3]); }else { c = box[2]; } Pointf[] rotatedBox = GetRotatedBoxEx(box, c, _angleDegree); //DrawLine(rotatedBox[0].x, rotatedBox[0].y, rotatedBox[1].x, rotatedBox[1].y); // DrawLine(rotatedBox2].x, rotatedBox[2].y, rotatedBox[3].x, rotatedBox[3].y); //DrawLine(rotatedBox[0].x, rotatedBox[0].y, rotatedBox[2].x, rotatedBox[2].y); //DrawLine(rotatedBox[1].x, rotatedBox[1].y, rotatedBox[3].x, rotatedBox[3].y); r8[0] = rotatedBox[0].x; //left-top r8[1] = rotatedBox[0].y; r8[2] = rotatedBox[1].x; //right-top r8[3] = rotatedBox[1].y; r8[4] = rotatedBox[2].x; //left-bottom r8[5] = rotatedBox[2].y; r8[6] = rotatedBox[3].x; //right-bottom r8[7] = rotatedBox[3].y; return r8; } public float[] DrawTextEx(String _text, float _x, float _y, float _angleDegree) { float[] r8; r8 = DrawTextEx(_text,_x, _y, _angleDegree, false); return r8; } //by CC public void DrawTextAligned(String _text, float _left, float _top, float _right, float _bottom, float _alignHorizontal, float _alignVertical) { if (mCanvas == null) return; Rect bounds = new Rect(); mTextPaint.getTextBounds(_text, 0, _text.length(), bounds); float x = _left + (_right - _left - bounds.width()) * _alignHorizontal; float y = _top + (_bottom - _top - bounds.height()) * _alignVertical + bounds.height(); mCanvas.drawText(_text, x, y, mTextPaint); } public float[] DrawTextAlignedEx(String _text, float _left, float _top, float _right, float _bottom, float _alignHorizontal, float _alignVertical) { if (mCanvas == null) return null; Rect bounds = new Rect(); mTextPaint.getTextBounds(_text, 0, _text.length(), bounds); float x = _left + (_right - _left - bounds.width()) * _alignHorizontal; float y = _top + (_bottom - _top - bounds.height()) * _alignVertical + bounds.height(); mCanvas.drawText(_text, x, y, mTextPaint); float[] r = GetTextBox(_text, x, y); //DrawRect(r[0],r[1],r[2], r[3]); return r; } public void DrawLine(float[] _points) { if (mCanvas == null) return; mCanvas.drawLines(_points, mDrawPaint); } public void DrawPoint(float _x1, float _y1) { if (mCanvas == null) return; mCanvas.drawPoint(_x1, _y1, mDrawPaint); } public void DrawCircle(float _cx, float _cy, float _radius) { if (mCanvas == null) return; mCanvas.drawCircle(_cx, _cy, _radius, mDrawPaint); } public void DrawBackground(int _color) { //mBackgroundColor = _color; if (mCanvas == null) return; mCanvas.drawColor(_color); } public void DrawRect(float _left, float _top, float _right, float _bottom) { if (mCanvas == null) return; mCanvas.drawRect(_left, _top, _right, _bottom, mDrawPaint); } public void DrawRect(float _P0x, float _P0y, float _P1x, float _P1y, float _P2x, float _P2y, float _P3x, float _P3y) { DrawLine(_P0x, _P0y, _P1x, _P1y); //top horiz DrawLine(_P1x, _P1y, _P3x, _P3y); //rigth vert DrawLine(_P3x, _P3y, _P2x, _P2y); //bottom horiz DrawLine(_P2x, _P2y, _P0x, _P0y); //left vert } public void DrawRect(float[] _box) { if (mCanvas == null) return; if (_box.length == 4) { DrawRect(_box[0], _box[1], _box[2], _box[3]); return; } if (_box.length != 8) return; DrawLine(_box[0], _box[1], _box[2], _box[3]); //PO - P1 DrawLine(_box[2], _box[3], _box[6], _box[7]); //P1 - P3 DrawLine(_box[6], _box[7], _box[4], _box[5]); //P3 - P2 DrawLine(_box[4], _box[5], _box[0], _box[1]); //P2 - P0 } //https://thoughtbot.com/blog/android-canvas-drawarc-method-a-visual-guide public void DrawArc(float _leftRectF, float _topRectF, float _rightRectF, float _bottomRectF, float _startAngle, float _sweepAngle, boolean _useCenter) { if (mCanvas == null) return; RectF oval = new RectF(_leftRectF, _topRectF, _rightRectF, _bottomRectF); mCanvas.drawArc(oval, _startAngle, _sweepAngle, _useCenter, mDrawPaint); } public void DrawOval(float _leftRectF, float _topRectF, float _rightRectF, float _bottomRectF) { if (mCanvas == null) return; mCanvas.drawOval(new RectF(_leftRectF, _topRectF, _rightRectF, _bottomRectF), mDrawPaint); } public void SetImageByResourceIdentifier(String _imageResIdentifier) { Drawable d = controls.GetDrawableResourceById(controls.GetDrawableResourceId(_imageResIdentifier)); if (d == null) return; Bitmap bmp = ((BitmapDrawable) d).getBitmap(); this.DrawBitmap(bmp); this.invalidate(); } public void DrawBitmap(Bitmap _bitmap) { if (mCanvas == null) return; int w = _bitmap.getWidth(); int h = _bitmap.getHeight(); Rect rect = new Rect(0, 0, w, h); Bitmap bmp = GetResizedBitmap(_bitmap, w, h); mCanvas.drawBitmap(bmp, null, rect, mDrawPaint); } public void SetMinZoomFactor(float _minZoomFactor) { mMinZoom = _minZoomFactor; } public void SetMaxZoomFactor(float _maxZoomFactor) { mMaxZoom = _maxZoomFactor; } public Canvas GetCanvas() { return mCanvas; } public Path GetPath(float[] _points) { // path.reset(); int len = _points.length; mPath.reset(); mPath.moveTo(_points[0], _points[1]); int i = 2; while ((i + 1) < len) { mPath.lineTo(_points[i], _points[i + 1]); //2,3 4,5 i = i + 2; } //mPath.close(); return mPath; } public Path GetPath() { // path.reset(); return mPath; } public Path ResetPath() { // path.reset(); mPath.reset(); return mPath; } public Path ResetPath(Path _path) { // path.reset(); _path.reset(); return _path; } //CCW //counter-clockwise // CW //clockwise public void AddCircleToPath(float _x, float _y, float _r, int _pathDirection) { Path.Direction dir = Path.Direction.CW; if (_pathDirection == 1) dir = Path.Direction.CCW; mPath.addCircle(_x, _y, _r, dir); } public void AddCircleToPath(Path _path, float _x, float _y, float _r, int _pathDirection) { Path.Direction dir = Path.Direction.CW; if (_pathDirection == 1) dir = Path.Direction.CCW; mPath.addCircle(_x, _y, _r, dir); } public Path GetNewPath(float[] _points) { int len = _points.length; //Log.i("len=",""+ len); Path path = new Path(); path.moveTo(_points[0], _points[1]); int i = 2; while ((i + 1) < len) { path.lineTo(_points[i], _points[i + 1]); //2,3 4,5 i = i + 2; } //path.close(); return path; } public Path GetNewPath() { Path path = new Path(); return path; } public Path AddPointsToPath(Path _path, float[] _points) { int len = _points.length; _path.moveTo(_points[0], _points[1]); int i = 2; while ((i + 1) < len) { _path.lineTo(_points[i], _points[i + 1]); //2,3 4,5 i = i + 2; } //path.close(); return _path; } public Path AddPathToPath(Path _srcPath, Path _targetPath, float _dx, float _dy) { _targetPath.addPath(_srcPath, _dx, _dy); return _targetPath; } public void DrawPath(Path _path) { if (mCanvas == null) return; //mPaint.setStyle(Paint.Style.STROKE); //<----- important! //seted in pascal side mCanvas.drawPath(_path, mDrawPaint); } public void DrawPath(float[] _points) { if (mCanvas == null) return; //mPaint.setStyle(Paint.Style.STROKE); //<----- important! //seted in pascal side mCanvas.drawPath(GetPath(_points), mDrawPaint); } public void DrawTextOnPath(Path _path, String _text, float _xOffset, float _yOffset) { if (mCanvas == null) return; //setLayerType(View.LAYER_TYPE_SOFTWARE, mPaint); // Required for API level 11 or higher. mCanvas.drawTextOnPath(_text, _path, _xOffset, _yOffset, mTextPaint); //setLayerType(View.LAYER_TYPE_SOFTWARE, mPaint); // Required for API level 11 or higher. } public void DrawTextOnPath(String _text, float _xOffset, float _yOffset) { if (mCanvas == null) return; if (!mPath.isEmpty()) { //setLayerType(View.LAYER_TYPE_SOFTWARE, mPaint); // Required for API level 11 or higher. mCanvas.drawTextOnPath(_text, mPath, _xOffset, _yOffset, mTextPaint); } } //https://blog.danlew.net/2013/10/03/centering_single_line_text_in_a_canvas/ TODO //https://ivankocijan.xyz/android-drawing-multiline-text-on-canvas/ public void DrawTextMultiLine(String _text, float _left, float _top, float _right, float _bottom) { if (mCanvas == null) return; Rect bounds = new Rect((int) _left, (int) _top, (int) _right, (int) _bottom); //Static layout which will be drawn on canvas //bounds.width - width of the layout //Layout.Alignment.ALIGN_CENTER - layout alignment //1 - text spacing multiply //1 - text spacing add //true - include padding StaticLayout sl = new StaticLayout(_text, mTextPaint, bounds.width(), Layout.Alignment.ALIGN_CENTER, 1, 1, true); mCanvas.save(); //calculate X and Y coordinates - In this case we want to draw the text in the //center of canvas so we calculate //text height and number of lines to move Y coordinate to center. float textHeight = getTextHeight(_text, mTextPaint); int numberOfTextLines = sl.getLineCount(); float textYCoordinate = bounds.exactCenterY() - ((numberOfTextLines * textHeight) / 2); //text will be drawn from left float textXCoordinate = bounds.left; mCanvas.translate(textXCoordinate, textYCoordinate); //draws static layout on canvas sl.draw(mCanvas); mCanvas.restore(); } private float getTextHeight(String text, Paint paint /*textPaint*/) { Rect rect = new Rect(); paint.getTextBounds(text, 0, text.length(), rect); return rect.height(); } public float GetTextHeight(String _text) { Rect rect = new Rect(); mTextPaint.getTextBounds(_text, 0, _text.length(), rect); return rect.height(); } public float GetTextWidth(String _text) { Rect rect = new Rect(); mTextPaint.getTextBounds(_text, 0, _text.length(), rect); return rect.width(); } //LMB public float GetTextLeft(String _text) { Rect rect = new Rect(); mTextPaint.getTextBounds(_text, 0, _text.length(), rect); return rect.left; } //LMB public float GetTextBottom(String _text) { Rect rect = new Rect(); mTextPaint.getTextBounds(_text, 0, _text.length(), rect); return rect.bottom; } public int GetViewportX(float _worldX, float _minWorldX, float _maxWorldX, int _viewPortWidth) { float escX; int r; escX = _viewPortWidth / (_maxWorldX - _minWorldX); r = (int) (escX * (_worldX - _minWorldX)); //round return r; } public int GetViewportY(float _worldY, float _minWorldY, float _maxWorldY, int _viewPortHeight) { float escY; int r; escY = -(_viewPortHeight - 10) / (_maxWorldY - _minWorldY); r = (int) (escY * (_worldY - _maxWorldY)); //round] return r; } public void Invalidate() { this.invalidate(); } public void Clear(int _color) { if (mCanvas == null) return; if (_color != 0) mCanvas.drawColor(_color); else mCanvas.drawColor(Color.WHITE); } public void Clear() { if (mCanvas == null) return; if (mBackgroundColor != 0) mCanvas.drawColor(mBackgroundColor); else mCanvas.drawColor(Color.WHITE); } public void SetBufferedDraw(boolean _value) { mBufferedDraw = _value; if (mBufferedDraw) { // Create bitmap, create canvas with bitmap, fill canvas with color. if (mBitmap == null) { mBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888); mCanvas = new Canvas(mBitmap); // Fill the Bitmap with the background color. if (mBackgroundColor != 0) mCanvas.drawColor(mBackgroundColor); else mCanvas.drawColor(Color.WHITE); } } } public void SetFontAndTextTypeFace(int fontFace, int fontStyle) { Typeface t = null; switch (fontFace) { case 0: { t = Typeface.DEFAULT; break;} case 1: { t = Typeface.SANS_SERIF; break;} case 2: { t = Typeface.SERIF; break;} case 3:{ t = Typeface.MONOSPACE; break;} } //fontStyle = (tfNormal/0, tfBold/1, tfItalic/2, tfBoldItalic/3); //Typeface.BOLD_ITALIC mTextPaint.setTypeface(Typeface.create(t, fontStyle)); } public void SetFontFromAssets(String _fontName) { // "fonts/font1.ttf" or "font1.ttf" Typeface customfont = Typeface.createFromAsset(controls.activity.getAssets(), _fontName); mTextPaint.setTypeface(customfont); } public void DrawTextFromAssetsFont(String _text, float _x, float _y, String _assetsFontName, int _size, int _color) { if (mCanvas == null) return; TextPaint textPaint = new TextPaint(); textPaint.setFlags(Paint.ANTI_ALIAS_FLAG); textPaint.setColor(_color); float unit = controls.activity.getResources().getDisplayMetrics().density; textPaint.setTextSize(_size*unit); // Typeface assetsfont = Typeface.createFromAsset(controls.activity.getAssets(), _assetsFontName); textPaint.setTypeface(assetsfont); mCanvas.drawText(_text, _x, _y, textPaint); } public void SetBackgroundColor(int _backgroundColor) { mBackgroundColor = _backgroundColor; this.setBackgroundColor(mBackgroundColor); } //by Kordal public void DrawBitmap(Bitmap _bitMap, int _srcLeft, int _srcTop, int _srcRight, int _srcBottom, float _dstLeft, float _dstTop, float _dstRight, float _dstBottom) { if (mCanvas == null) return; Rect srcRect = new Rect(_srcLeft, _srcTop, _srcRight, _srcBottom); RectF dstRect = new RectF(_dstLeft, _dstTop, _dstRight, _dstBottom); mCanvas.drawBitmap(_bitMap, srcRect, dstRect, mDrawPaint); } public void DrawFrame(Bitmap _bitMap, int _srcX, int _srcY, int _srcW, int _srcH, float _X, float _Y, float _Wh, float _Ht, float _rotateDegree) { if (mCanvas == null) return; Rect srcRect = new Rect(_srcX, _srcY, _srcX + _srcW, _srcY + _srcH); RectF dstRect = new RectF(_X, _Y, _X + _Wh, _Y + _Ht); if (_rotateDegree != 0) { mCanvas.save(); mCanvas.rotate(_rotateDegree, _X + _Wh / 2, _Y + _Ht / 2); mCanvas.drawBitmap(_bitMap, srcRect, dstRect, mDrawPaint); mCanvas.restore(); } else { mCanvas.drawBitmap(_bitMap, srcRect, dstRect, mDrawPaint); } } public void DrawFrame(Bitmap _bitMap, float _X, float _Y, int _Index, int _Size, float _scaleFactor, float _rotateDegree) { float sf = _Size * _scaleFactor; DrawFrame(_bitMap, _Index % (_bitMap.getWidth() / _Size) * _Size, _Index / (_bitMap.getWidth() / _Size) * _Size, _Size, _Size, _X, _Y, sf, sf, _rotateDegree); } //by Kordal public void DrawRoundRect(float _left, float _top, float _right, float _bottom, float _rx, float _ry) { if (mCanvas == null) return; //[ifdef_api21up] if (Build.VERSION.SDK_INT >= 21) { mCanvas.drawRoundRect(_left, _top, _right, _bottom, _rx, _ry, mDrawPaint); }//[endif_api21up] } //by Kordal public void SetTimeClicks(int _timeClick, int _timeDbClick) { mTimeClick = _timeClick; mTimeDoubleClick = _timeDbClick; } public float GetDensity() { return controls.activity.getResources().getDisplayMetrics().density; } public void ClipRect(float _left, float _top, float _right, float _bottom) { if (mCanvas == null) return; mCanvas.clipRect(_left, _top, _right, _bottom); } public void DrawGrid(float _left, float _top, float _width, float _height, int _cellsX, int _cellsY) { if (mCanvas == null) return; float cw = _width / _cellsX; float ch = _height / _cellsY; for (int i = 0; i < _cellsX + 1; i++) { mCanvas.drawLine(_left + i * cw, _top, _left + i * cw, _top + _height, mDrawPaint); // draw Y lines } for (int i = 0; i < _cellsY + 1; i++) { mCanvas.drawLine(_left, _top + i * ch, _left + _width, _top + i * ch, mDrawPaint); // draw X lines } } public void SetLayerType(byte _value) { setLayerType(_value/*View.LAYER_TYPE_SOFTWARE*/, null); } } //end class
true
537392a001a40f65ffa7b787a5faa5c87558b194
Java
danilogoulart/gestaodegastos
/NetBeansProjects/WebGestaoDeGastos-master/src/java/ws/wsCategoria.java
UTF-8
3,488
2.625
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ws; import java.util.GregorianCalendar; import java.util.List; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; /** * * @author danilo */ public class wsCategoria { public boolean excluirCategoria(String nomecategoria){ return excluicategoria(nomecategoria); } public List<String> listarCategoria() throws Exception { return listacategoria(); } public boolean salvarCategoria(String nome){ return salvacategoria(nome); } public float obterSaldo() { return getSaldo(); } public List<Movimentacao> listarMovimentacao() { return listaMovimentacao(); } public boolean atualizarCategoria(String categoria, String categoriaEditada){ return atualizaCategoria(categoria, categoriaEditada); } public boolean salvarMovimentacao(model.Movimentacao m) throws DatatypeConfigurationException { Movimentacao m1 = new Movimentacao(); GregorianCalendar c = new GregorianCalendar(); c.setTime(m.getData()); XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c); m1.setData(date2); m1.setDescricao(m.getDescricao()); m1.setNomeCategoria(m.getNomeCategoria()); m1.setTipo(m.getTipo()); m1.setValor(m.getValor()); return salvaMovimentacao(m1); } private static java.util.List<java.lang.String> listacategoria() { ws.WsCategoria_Service service = new ws.WsCategoria_Service(); ws.WsCategoria port = service.getWsCategoriaPort(); return port.listacategoria(); } private static boolean salvacategoria(java.lang.String nomecategoria) { ws.WsCategoria_Service service = new ws.WsCategoria_Service(); ws.WsCategoria port = service.getWsCategoriaPort(); return port.salvacategoria(nomecategoria); } private static float getSaldo() { ws.WsCategoria_Service service = new ws.WsCategoria_Service(); ws.WsCategoria port = service.getWsCategoriaPort(); return port.getSaldo(); } private static java.util.List<ws.Movimentacao> listaMovimentacao() { ws.WsCategoria_Service service = new ws.WsCategoria_Service(); ws.WsCategoria port = service.getWsCategoriaPort(); return port.listaMovimentacao(); } private static boolean salvaMovimentacao(ws.Movimentacao arg0) { ws.WsCategoria_Service service = new ws.WsCategoria_Service(); ws.WsCategoria port = service.getWsCategoriaPort(); return port.salvaMovimentacao(arg0); } private static boolean excluicategoria(java.lang.String nomecategoria) { ws.WsCategoria_Service service = new ws.WsCategoria_Service(); ws.WsCategoria port = service.getWsCategoriaPort(); return port.excluicategoria(nomecategoria); } private static boolean atualizaCategoria(java.lang.String arg0, java.lang.String arg1) { ws.WsCategoria_Service service = new ws.WsCategoria_Service(); ws.WsCategoria port = service.getWsCategoriaPort(); return port.atualizaCategoria(arg0, arg1); } }
true
6ee67fb22d09f569d7b8bfea2825c6759b394eaf
Java
andongni/nianien
/src/test/java/com/nianien/test/TestTaskService.java
UTF-8
1,053
2.828125
3
[]
no_license
package com.nianien.test; import com.nianien.core.util.TaskService; public class TestTaskService { static int flag = 1; /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { TaskService ts = new TaskService(); ts.start(); for (int i = 0; i < 5; i++) { System.out.println("add task..."); ts.addTask(new Runnable() { @Override public void run() { System.out.println("==>:" + flag++); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }); } System.out.println("waiting for..."); Thread.sleep(3000); for (int i = 0; i < 5; i++) { System.out.println("add task..."); ts.addTask(new Runnable() { @Override public void run() { System.out.println("==>:" + flag++); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread.sleep(100); } ts.shutdown(); System.out.println("shout down..."); } }
true
e2fad193867808f3c663cf27591f452a129617ea
Java
peterpan001/XmlTest
/src/com/xml/read/xpath/TestXmlByXpath.java
UTF-8
699
2.59375
3
[]
no_license
package com.xml.read.xpath; import java.util.List; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.junit.Test; public class TestXmlByXpath { @Test public void testReadStudentXml()throws Exception{ //获取dom树 Document dom = new SAXReader().read("D:\\program\\eclipse_chuanzhiboke\\XmlTest\\xml\\student.xml"); //获取单一节点 Element ele = (Element) dom.selectSingleNode("//student/name"); System.out.println(ele.getText()+"--"); //获取节点列表 List<Element> list = dom.selectNodes("//student/name"); for (Element elem : list) { System.out.println(elem.getText()); } } }
true
acb0745774713019b6d97c3ebe478ccc32081fef
Java
alexmilis/java-course
/hw05-0036499702/src/main/java/hr/fer/zemris/java/hw05/db/parser/ParserException.java
UTF-8
918
2.5625
3
[]
no_license
package hr.fer.zemris.java.hw05.db.parser; import hr.fer.zemris.java.hw05.db.QueryParser; /** * Class used to describe exceptions that occur in {@link QueryParser}. * @author Alex * */ public class ParserException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; public ParserException() { // TODO Auto-generated constructor stub } public ParserException(String arg0) { super(arg0); // TODO Auto-generated constructor stub } public ParserException(Throwable arg0) { super(arg0); // TODO Auto-generated constructor stub } public ParserException(String arg0, Throwable arg1) { super(arg0, arg1); // TODO Auto-generated constructor stub } public ParserException(String arg0, Throwable arg1, boolean arg2, boolean arg3) { super(arg0, arg1, arg2, arg3); // TODO Auto-generated constructor stub } }
true
0d44d421385388c1317e24bb7c2aa1aeb7edac81
Java
deimos21/DodatekSzkodliwy
/src/logika/Wyszukaj.java
WINDOWS-1250
1,277
3.15625
3
[]
no_license
package logika; import java.sql.*; import java.util.*; public class Wyszukaj{ private ArrayList<Object[]> tabela; private ResultSet rs;; private ResultSetMetaData rsmd; public Wyszukaj(BazaDanych bd, String query){ try{ Connection connect = bd.getConnect(); if(bd.isConnected()){ Statement stat = connect.createStatement(); rs = stat.executeQuery(query); rsmd = rs.getMetaData(); int iloscKolumn = rsmd.getColumnCount(); Object kolumny[]; tabela = new ArrayList<Object[]>(); try { while(rs.next()){ kolumny = new Object[iloscKolumn]; if(rs.getObject(1)!=null){ for(int i=0;i<iloscKolumn;i++) kolumny[i] = rs.getObject(i+1); tabela.add(kolumny); } } } catch (SQLException e){ System.out.println("Blad podczas zapytania do bazy w klasie Wyszukaj: "+e); } stat.close(); //connect.close(); } } catch(SQLException e){ System.out.println("Bd w klasie wyszukaj: [" + e.getMessage() + "]"); } } public ArrayList<Object[]> getArrayList(){ return tabela; } }
true
6b8d8601a88b101bac5c58e151af2c28b1b36337
Java
mir333/spring-portlet-example
/basic-spring-portlet/basic-spring-portlet/src/main/java/eu/ibacz/sample/portlet/bascispring/pto/PersonPto.java
UTF-8
1,062
2.21875
2
[]
no_license
/* =========================================================================== * IBA CZ Confidential * * (c) Copyright IBA CZ 2011 ALL RIGHTS RESERVED * The source code for this program is not published or otherwise * divested of its trade secrets. * * =========================================================================== */ package eu.ibacz.sample.portlet.bascispring.pto; import org.joda.time.DateTime; /** * @author Miroslav Ligas <miroslav.ligas@ibacz.eu> */ public class PersonPto { private String name; private DateTime dateOfBirth; public DateTime getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(DateTime dateOfBirth) { this.dateOfBirth = dateOfBirth; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "PersonPto{" + "dateOfBirth=" + dateOfBirth + ", name='" + name + '\'' + "} " + super.toString(); } }
true
a4eb1d798095333b9a84b424af4e9db66cd4bb85
Java
cuckoo20100401/persistence-proxy
/src/main/java/org/cuckoo/persistence/callback/CriteriaCallback.java
UTF-8
273
1.90625
2
[]
no_license
package org.cuckoo.persistence.callback; import org.hibernate.Criteria; /** * Hibernate Criteria回调接口 */ public interface CriteriaCallback { /** * 执行自定义代码 * @param criteria */ public void executeCustom(Criteria criteria); }
true
0b3ebe86b2255a7102c3e6c3a89dc2686b372e9b
Java
FifiTeklemedhin/IB-1-Programming-Projects
/MulticlientChat/src/multiclientchat/Transcript.java
UTF-8
1,475
2.84375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package multiclientchat; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; /** * * @author fifiteklemedhin */ public class Transcript{ private String str; private File file; public Transcript(){ this.file = new File("./localhost-transcript.txt"); getTranscript(); } public void add (String more){ str += more +"\n"; writeToFile(more); } public String toString(){ return str; } public void writeToFile(String newLine) { FileWriter writer; try { writer = new FileWriter(this.file, true); writer.write(newLine+"\n"); writer.close(); } catch(IOException e) { System.out.println("io exception when instantiating to writer: "); } } public void getTranscript() { Scanner reader; try { reader = new Scanner(this.file); while(reader.hasNextLine()) str += reader.nextLine() + "\n"; } catch (FileNotFoundException ex) { System.out.println("no file found to read -- print transcript"); return; } } }
true
9473afd356e0ce648a5142c27aee4232564270d6
Java
Elsa1024/leetcode_java
/163_missing_ranges.java
UTF-8
986
3.0625
3
[]
no_license
class Solution { public String generateRange(long lower, long upper) { if (upper == lower) return upper + ""; return lower + "->" + upper; } public List<String> findMissingRanges(int[] nums, int lower, int upper) { List<String> rangeList = new ArrayList<>(); if (nums == null || nums.length == 0) { rangeList.add(generateRange(lower, upper)); return rangeList; } for (int i = 0; i < nums.length; i++) { if (i == 0) { if (nums[i] > lower) rangeList.add(generateRange(lower, nums[i]-1)); } else if ((long)nums[i] - (long)nums[i-1] > 1) { rangeList.add(generateRange((long)nums[i-1]+1, (long)nums[i]-1)); } } if (upper > (long)nums[nums.length - 1]) rangeList.add(generateRange((long)nums[nums.length - 1]+1, upper)); return rangeList; } }
true
89a2e60c0a0e2834ce65c902edb80d93ef40c1b5
Java
verginiaa/Leetcode
/Leetcode8/src/DistributeCandies.java
UTF-8
377
3.078125
3
[]
no_license
import java.util.HashSet; public class DistributeCandies { public int distributeCandies(int[] candies) { HashSet<Integer>hashSet=new HashSet<>(); for(int i=0;i<candies.length;i++) hashSet.add(candies[i]); if(hashSet.size()>(candies.length/2)) return candies.length/2; else return hashSet.size(); } }
true
01f304de57f999886e2cde4706c91d39a7cc8fef
Java
fermadeiral/StyleErrors
/intuit-Tank/16ef0447b064b08b7c61aa76cc665255a0723127/378/ViewFilterTypeCpTest.java
UTF-8
4,169
2.0625
2
[]
no_license
package com.intuit.tank.view.filter; /* * #%L * Intuit Tank Api * %% * Copyright (C) 2011 - 2015 Intuit Inc. * %% * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * #L% */ import java.text.DateFormat; import java.util.Date; import org.junit.*; import com.intuit.tank.view.filter.ViewFilterType; import static org.junit.Assert.*; /** * The class <code>ViewFilterTypeCpTest</code> contains tests for the class <code>{@link ViewFilterType}</code>. * * @generatedBy CodePro at 9/3/14 3:41 PM */ public class ViewFilterTypeCpTest { /** * Run the ViewFilterType(String) constructor test. * * @throws Exception * * @generatedBy CodePro at 9/3/14 3:41 PM */ @Test public void testViewFilterType_1() throws Exception { String display = ""; ViewFilterType result = ViewFilterType.LAST_60_DAYS; // An unexpected exception was thrown in user code while executing this test: // java.lang.NoSuchMethodException: com.intuit.tank.view.filter.ViewFilterType.<init>(java.lang.String) // at java.lang.Class.getConstructor0(Class.java:2810) // at java.lang.Class.getDeclaredConstructor(Class.java:2053) // at // com.instantiations.eclipse.analysis.expression.model.InstanceCreationExpression.findConstructor(InstanceCreationExpression.java:572) // at // com.instantiations.eclipse.analysis.expression.model.InstanceCreationExpression.execute(InstanceCreationExpression.java:452) // at com.instantiations.assist.eclipse.junit.execution.core.ExecutionRequest.execute(ExecutionRequest.java:286) // at // com.instantiations.assist.eclipse.junit.execution.communication.LocalExecutionClient$1.run(LocalExecutionClient.java:158) // at java.lang.Thread.run(Thread.java:745) assertNotNull(result); assertEquals("Last 60 Days", result.getDisplay()); } /** * Run the String getDisplay() method test. * * @throws Exception * * @generatedBy CodePro at 9/3/14 3:41 PM */ @Test public void testGetDisplay_1() throws Exception { ViewFilterType fixture = ViewFilterType.ALL; String result = fixture.getDisplay(); assertEquals("All", result); } /** * Run the Date getViewFilterDate(ViewFilterType) method test. * * @throws Exception * * @generatedBy CodePro at 9/3/14 3:41 PM */ @Test public void testGetViewFilterDate_1() throws Exception { ViewFilterType viewFilter = ViewFilterType.ALL; Date result = ViewFilterType.getViewFilterDate(viewFilter); assertNotNull(result); } /** * Run the Date getViewFilterDate(ViewFilterType) method test. * * @throws Exception * * @generatedBy CodePro at 9/3/14 3:41 PM */ @Test public void testGetViewFilterDate_2() throws Exception { ViewFilterType viewFilter = ViewFilterType.ALL; Date result = ViewFilterType.getViewFilterDate(viewFilter); assertNotNull(result); } /** * Run the Date getViewFilterDate(ViewFilterType) method test. * * @throws Exception * * @generatedBy CodePro at 9/3/14 3:41 PM */ @Test public void testGetViewFilterDate_3() throws Exception { ViewFilterType viewFilter = ViewFilterType.ALL; Date result = ViewFilterType.getViewFilterDate(viewFilter); assertNotNull(result); } /** * Run the Date getViewFilterDate(ViewFilterType) method test. * * @throws Exception * * @generatedBy CodePro at 9/3/14 3:41 PM */ @Test public void testGetViewFilterDate_4() throws Exception { ViewFilterType viewFilter = ViewFilterType.ALL; Date result = ViewFilterType.getViewFilterDate(viewFilter); assertNotNull(result); } }
true
3a96516140911827a7818ad41eda88d4fd0977ba
Java
2301887641/java-44time-backend
/time-core/src/main/java/com/time/article/core/controller/config/FrontConfigurerAdapter.java
UTF-8
964
2.28125
2
[]
no_license
package com.time.article.core.controller.config; import com.time.article.core.controller.converter.FrontEnumConverterFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import org.springframework.format.FormatterRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * 前端枚举处理配置 * @author suiguozhen on 18/07/17 */ @Configuration @Lazy public class FrontConfigurerAdapter extends WebMvcConfigurerAdapter { @Override public void addFormatters(FormatterRegistry registry) { // 接收枚举转换 registry.addConverterFactory(frontEnumConverterFactory()); } /** * 统一前台枚举转换 * @return */ @Bean public FrontEnumConverterFactory frontEnumConverterFactory(){ return new FrontEnumConverterFactory(); } }
true
3af761d7347f105fd50946186b8ad9f997e312d0
Java
dyfloveslife/LeetCodeAndSwordToOffer
/src/LeetCodeSolution/DataStructure/_02_String/_409_LongestPalindrome/Solution.java
UTF-8
1,349
4.09375
4
[]
no_license
package LeetCodeSolution.DataStructure._02_String._409_LongestPalindrome; /* * 最长回文串 * * 题目描述: * 给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串。 * 在构造过程中,请注意区分大小写。比如 "Aa" 不能当做一个回文字符串。 * * 思路: * 1. 使用 58 大小的数组存储 s 中每个字母出现的次数,如果每个字母出现的次数都是偶数个,则可以构成回文串; * 2. 如果有单独的字符,可以将该字符放在回文串的中间; * 3. A 与 a 的 ASCII 相差 32,因此 32 + 26 = 58。 */ public class Solution { public int longestPalindrome(String s) { if (s == null || s.length() == 0) { return 0; } int[] nums = new int[58]; for (char c : s.toCharArray()) { nums[c - 'A']++; } int res = 0; int odd = 0; for (int num : nums) { res += num % 2 == 0 ? num : num - 1; if (num % 2 == 1) { odd = 1; } } res += odd; return res; } public static void main(String[] args) { Solution solution = new Solution(); String s = "abccccdd"; System.out.println(solution.longestPalindrome(s)); } }
true
cc69ee8662c3b79ec33b29c38b04d3b6252d77b8
Java
GdI-Projekt/Workspace
/Gruppe032/src/de/tudarmstadt/gdi1/project/Factory.java
UTF-8
7,623
2.390625
2
[]
no_license
package de.tudarmstadt.gdi1.project; import java.util.Collection; import java.util.List; import de.tudarmstadt.gdi1.project.alphabet.Alphabet; import de.tudarmstadt.gdi1.project.alphabet.Dictionary; import de.tudarmstadt.gdi1.project.alphabet.Distribution; import de.tudarmstadt.gdi1.project.analysis.ValidateDecryptionOracle; import de.tudarmstadt.gdi1.project.analysis.caeser.CaesarCryptanalysis; import de.tudarmstadt.gdi1.project.analysis.monoalphabetic.Individual; import de.tudarmstadt.gdi1.project.analysis.monoalphabetic.MonoalphabeticCpaNpaCryptanalysis; import de.tudarmstadt.gdi1.project.analysis.monoalphabetic.MonoalphabeticCribCryptanalysis; import de.tudarmstadt.gdi1.project.analysis.monoalphabetic.MonoalphabeticKnownCiphertextCryptanalysis; import de.tudarmstadt.gdi1.project.analysis.vigenere.VigenereCryptanalysis; import de.tudarmstadt.gdi1.project.cipher.enigma.Enigma; import de.tudarmstadt.gdi1.project.cipher.enigma.PinBoard; import de.tudarmstadt.gdi1.project.cipher.enigma.ReverseRotor; import de.tudarmstadt.gdi1.project.cipher.enigma.Rotor; import de.tudarmstadt.gdi1.project.cipher.substitution.SubstitutionCipher; import de.tudarmstadt.gdi1.project.cipher.substitution.monoalphabetic.Caesar; import de.tudarmstadt.gdi1.project.cipher.substitution.monoalphabetic.KeywordMonoalphabeticCipher; import de.tudarmstadt.gdi1.project.cipher.substitution.monoalphabetic.MonoalphabeticCipher; import de.tudarmstadt.gdi1.project.cipher.substitution.polyalphabetic.PolyalphabeticCipher; import de.tudarmstadt.gdi1.project.cipher.substitution.polyalphabetic.Vigenere; import de.tudarmstadt.gdi1.project.utils.Utils; /** * TODO: Denote, when paramters should be final, unchangable values (e.g., * Alphabet) -- i.e., implementing those via some empty constructor + * setParameter method should be considered wrong. */ public interface Factory { /** * Constructs a {@link Distribution} from the given text for all ngrams of * size 1 to ngramsize. Only characters available in the alphabet should be * taken into consideration {@link Alphabet#normalize(String)}. * * @param source * the alphabet * @param text * the text to base the distribution on * @param ngramsize * the maximum n-gram size * @return a distribution object */ public Distribution getDistributionInstance(Alphabet source, String text, int ngramsize); /** * Constructs an {@link Alphabet} based on the (ordered) collection of * characters * * @param characters * an ordered collection of characters * * @return an alphabet based on the given collection of characters */ public Alphabet getAlphabetInstance(Collection<Character> characters); /** * Loads all valid words from the input into the dictionary. <br \> * A word is the character sequence that stands between a space and/or one * of the following characters: ',' '!' '?' '.'<br \> * A word is valid if it contains only characters that are part of the given * alphabet. * * @param alphabet * the source alphabet * @param text * the text where the words should be extracted from */ public Dictionary getDictionaryInstance(Alphabet alphabet, String text); /** * Constructs a {@link MonoalphabeticCipher} mapping from a source alphabet * to a target alphabet. * * @param source * the source alphabet * @param dest * the destination (target) alphabet * @return */ public MonoalphabeticCipher getMonoalphabeticCipherInstance(Alphabet source, Alphabet dest); /** * Constructs a Caesar cipher over the given alphabet and with a shift * specified by key. * * @param key * the shift * @param alphabet * the alphabet * @return */ public Caesar getCaesarInstance(int key, Alphabet alphabet); /** * Constructs a {@link KeywordMonoalphabeticCipher} over the given alphabet * and with the given keyword * * @param key * the keyword * @param alphabet * the alphabet * @return */ public KeywordMonoalphabeticCipher getKeywordMonoalphabeticCipherInstance(String key, Alphabet alphabet); /** * Constructs a generic {@link PolyalphabeticCipher} from one source * alphabet and at least a single target alphabet. * * @param source * the source alphabet * @param dest * an arary (vararg) of target alphabets * @return */ public PolyalphabeticCipher getPolyalphabeticCipherInstance(Alphabet source, Alphabet... dest); /** * Constructs a {@link Vigenere} Ciphere for a given key and alphabet * * @param key * the key * @param alphabet * the alphabet * @return */ public Vigenere getVigenereCipherInstance(String key, Alphabet alphabet); /** * Returns an isntance of a {@link CaesarCryptanalysis}. * * @return */ public CaesarCryptanalysis getCaesarCryptanalysisInstance(); /** * Returns an instance of {@link MonoalphabeticCpaNpaCryptanalysis}. * * @return */ public MonoalphabeticCpaNpaCryptanalysis getMonoalphabeticCpaNpaCryptanalysis(); /** * Returns an instance of {@link MonoalphabeticCribCryptanalysis}. * * @return */ public MonoalphabeticCribCryptanalysis getMonoalphabeticCribCryptanalysisInstance(); /** * returns an instance of {@link MonoalphabeticKnownCiphertextCryptanalysis} * . * * @return */ public MonoalphabeticKnownCiphertextCryptanalysis getMonoalphabeticKnownCiphertextCryptanalysisInstance(); /** * returns an instance of {@link VigenereCryptanalysis} * * * @return */ public VigenereCryptanalysis getVigenereCryptanalysisInstance(); /** * returns an instance of {@link Utils}. * * @return */ public Utils getUtilsInstance(); /** * Constructs an {@link Enigma} with the given rotors, pinboard and a * {@link ReverseRotor}. * * @param rotors * The (ordered) list of rotors * @param pinboard * the pinboard * @param reverseRotor * the reverse rotor * @return */ public Enigma getEnigmaInstance(List<Rotor> rotors, PinBoard pinboard, ReverseRotor reverseRotor); /** * Constructs a {@link PinBoard} from a source alphabet and a destiniation * alphabet * * @param source * the input alphabet * @param destination * the mapping of the output * @return */ public PinBoard getPinBoardInstance(Alphabet source, Alphabet destination); /** * Constructs a rotor from an two alphabets (ingoing and exit) and a * position. * * @param entryAlph * @param exitAlph * @param startPosition * @return */ public Rotor getRotorInstance(Alphabet entryAlph, Alphabet exitAlph, int startPosition); /** * Constructs a reverse rotor from two alphabets (ingoing and exit). * * @param entryAlph * @param exitAlph * @return */ public ReverseRotor getReverseRotatorInstance(Alphabet entryAlph, Alphabet exitAlph); /** * * @return The class implementing {@link SubstitutionCipher} */ public Class<? extends SubstitutionCipher> getAbstractSubstitutionCipherClass(); /** * Constructs a {@link ValidateDecryptionOracle} from a distribution and a * dictionary * * @param distribution * @param dictionary * @return */ public ValidateDecryptionOracle getValidateDecryptionOracle(Distribution distribution, Dictionary dictionary); /** * Constructs an {@link Individual} * * @param alphabet * @param fitness * @return */ public Individual getIndividualInstance(Alphabet alphabet, double fitness); }
true
a10adeb615cf84f9aadc4354d8f71181e7557b05
Java
Dholness2/train-graph-solution
/train-route-app/src/main/java/com/holness/app/displays/CommandLineDisplay.java
UTF-8
225
2.15625
2
[]
no_license
package com.holness.app.displays; import com.holness.app.displays.ReportDisplay; public class CommandLineDisplay implements ReportDisplay { public void writeOutput(String output) { System.out.println(output); } }
true
7b0ba0619b0fb7c769c888a283cb6a45d4fcd28c
Java
Ardemius/scjp6-training
/src/tsc/scjp6/exercices/exercice9_2/ThreadSynchronizeTest.java
UTF-8
806
3.546875
4
[]
no_license
package tsc.scjp6.exercices.exercice9_2; public class ThreadSynchronizeTest extends Thread { private StringBuffer data; public ThreadSynchronizeTest(StringBuffer sb) { super(); this.data = sb; } @Override public void run() { synchronized (data) { // synchronized (ThreadSynchronizeTest.class) { for (int i = 0; i < 100; i++) { System.out.print(data); } // increment the letter char c = data.charAt(0); data.setCharAt(0, ++c); System.out.println(" -- fin -- "); } } /** * @param args */ public static void main(String[] args) { StringBuffer sb = new StringBuffer("A"); Thread t1 = new ThreadSynchronizeTest(sb); Thread t2 = new ThreadSynchronizeTest(sb); Thread t3 = new ThreadSynchronizeTest(sb); t1.start(); t2.start(); t3.start(); } }
true
94f2ae1ed05125903edde637947c79dcf901a8a6
Java
Pro-100Evhen/ikube
/code/core/src/test/java/ikube/application/GCAnalyzerTest.java
UTF-8
6,962
1.625
2
[ "Apache-2.0" ]
permissive
package ikube.application; import com.sun.management.GarbageCollectorMXBean; import ikube.AbstractTest; import ikube.toolkit.THREAD; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Spy; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import javax.management.MBeanServerConnection; import javax.management.remote.JMXConnector; import java.lang.management.OperatingSystemMXBean; import java.lang.management.ThreadMXBean; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import static java.lang.System.currentTimeMillis; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MINUTES; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; /** * @author Michael Couck * @version 01.00 * @since 23-10-2014 */ public class GCAnalyzerTest extends AbstractTest { private int port = 8600; private List<GarbageCollectorMXBean> garbageCollectorMXBeans; @Spy @InjectMocks private GCAnalyzer gcAnalyzer; @Mock private GCSmoother gcSmoother; @Mock private GCCollector oldCollector; @Mock private ThreadMXBean threadMXBean; @Mock private GCCollector edenCollector; @Mock private JMXConnector jmxConnector; @Mock private GCCollector permCollector; @Mock private MBeanServerConnection mBeanConnectionServer; @Mock private OperatingSystemMXBean operatingSystemMXBean; @Mock private GarbageCollectorMXBean garbageCollectorMXBean; @Before public void before() { garbageCollectorMXBeans = new ArrayList<>(); garbageCollectorMXBeans.add(garbageCollectorMXBean); } @Test public void registerCollectors() throws Exception { doAnswer(new Answer() { @Override public Object answer(final InvocationOnMock invocation) throws Throwable { return null; } }).when(gcAnalyzer).registerCollector(any(String.class), anyInt()); // No way to verify anything in here! Just must pass... gcAnalyzer.registerCollectors("192.168.1.0/28"); } @Test public void registerCollector() throws Exception { doAnswer(new Answer() { @Override public Object answer(final InvocationOnMock invocation) throws Throwable { return jmxConnector; } }).when(gcAnalyzer).getJMXConnector(any(String.class)); when(jmxConnector.getMBeanServerConnection()).thenReturn(mBeanConnectionServer); doAnswer(new Answer() { @Override public Object answer(final InvocationOnMock invocation) throws Throwable { return threadMXBean; } }).when(gcAnalyzer).getThreadMXBean(mBeanConnectionServer); doAnswer(new Answer() { @Override public Object answer(final InvocationOnMock invocation) throws Throwable { return operatingSystemMXBean; } }).when(gcAnalyzer).getOperatingSystemMXBean(mBeanConnectionServer); doAnswer(new Answer() { @Override public Object answer(final InvocationOnMock invocation) throws Throwable { return garbageCollectorMXBeans; } }).when(gcAnalyzer).getGarbageCollectorMXBeans(mBeanConnectionServer); gcAnalyzer.registerCollector(address, port); assertTrue(gcAnalyzer.gcCollectorMap.size() == 1); assertEquals(GCAnalyzer.MEMORY_BLOCKS.length, gcAnalyzer.gcCollectorMap.values().iterator().next().size()); } @Test @SuppressWarnings({"NullArgumentToVariableArgMethod", "unchecked", "ResultOfMethodCallIgnored"}) public void getGcData() { List<GCSnapshot> smoothGcSnapshots = Arrays.asList(getGcSnapshot(), getGcSnapshot(), getGcSnapshot()); when(gcSmoother.getSmoothedSnapshots(any(List.class))).thenReturn(smoothGcSnapshots); gcAnalyzer.gcCollectorMap.put(gcAnalyzer.getAddressAndPort(address, port), Arrays.asList(edenCollector, permCollector, oldCollector)); Object[][][] gcData = gcAnalyzer.getGcData(address, port); for (final Object[][] matrix : gcData) { for (int i = 0; i < matrix.length; i++) { Object[] vector = matrix[i]; GCSnapshot gcSnapshot = smoothGcSnapshots.get(i); assertTrue(vector[0].equals(new Date(gcSnapshot.start))); assertTrue(vector[1].equals(gcSnapshot.delta)); assertTrue(vector[2].equals(gcSnapshot.duration)); assertTrue(vector[3].equals(gcSnapshot.interval)); assertTrue(vector[4].equals(gcSnapshot.perCoreLoad)); assertTrue(vector[5].equals(gcSnapshot.runsPerTimeUnit)); assertTrue(vector[6].equals(gcSnapshot.usedToMaxRatio)); } } } GCSnapshot getGcSnapshot() { GCSnapshot gcSnapshot = new GCSnapshot(); gcSnapshot.available = 6; gcSnapshot.cpuLoad = 4.32; gcSnapshot.delta = -0.23; gcSnapshot.duration = 213l; gcSnapshot.end = 0; gcSnapshot.perCoreLoad = 0.581; gcSnapshot.runsPerTimeUnit = 3; gcSnapshot.start = 0; gcSnapshot.threads = 28; gcSnapshot.usedToMaxRatio = 0.568; return gcSnapshot; } @Test public void checkTimeUnitConversion() { // Check whether the time unit conversion rounds the time unit // on overflow, or truncates the excess seconds for the minute to // the lower bound for (int i = 0; i < 90; i++) { long nextSecond = currentTimeMillis() + (i * 1000); Date current = new Date(nextSecond); long millisToSeconds = MILLISECONDS.toSeconds(nextSecond); long millisToMinutes = MILLISECONDS.toMinutes(nextSecond); long minutesToMillis = MINUTES.toMillis(millisToMinutes); Date minutesToMillisDate = new Date(minutesToMillis); logger.debug(current.toString()); logger.debug(Long.toString(millisToSeconds)); logger.debug(Long.toString(millisToMinutes)); logger.debug(minutesToMillisDate.toString()); logger.debug(""); long excessSeconds = millisToSeconds % 60l; long truncatedSeconds = millisToSeconds - excessSeconds; long truncatedMillis = truncatedSeconds * 1000; // And the time is truncated in the TimeUnit enumeration logic Assert.assertTrue(new Date(truncatedMillis).equals(minutesToMillisDate)); } } }
true
f7eb472df94fafdc096c0929d7b6a8b168fe95aa
Java
BasudevBharatBhushan/DS-Algo
/oops/finalKeyword/MainClass.java
UTF-8
1,788
3.9375
4
[ "Apache-2.0" ]
permissive
package oops.finalKeyword; public class MainClass extends Student { int rollNo; // final int SandleNo; //This is not possible because,if we are using final keyword then we must initialize it here only //but this thing can be possible in the local variable but we have to assign some value after it otherwise while printing it it will show error // public void getDescription() { //This will show compile time error because this method cannot be overridden further after the use of final keyword in parent's method // System.out.println("The student name is "+NAME); // } final int SANDLE_NO =4; //final variable should be named in caps for more convenience public static void main(String[] args) { final String NAME="Anuj"; // name = "Aman"; //Cannot be updated due to final keyword or re-assigned final int BUS_NO; //This final variable is not initialized while declaration...so it is called as blank variable //System.out.println(BUS_NO); //this will show compile time error because the busNo variable is not initialized or not assigned with any value which become a mandatory thing after using the final keyword. final Student obj = new Student(); Student obj2 = new Student(); Student obj3 = new Student(); obj2=obj3; //this can be done...reference of obj3 is given to obj2 //obj=obj2; //this will show compile time error because in case of reference final variable, internal state of the object pointed by that reference variable cannot be changed //obj.sec= "A"; //but this can be done for a final object variable //FINAL METHOD ILLUSTRATION MainClass object = new MainClass(); object.getDescription(); //final class---if final keyword is used before a class then it cannot be extended } }
true
39a22c174962ce7062cfd61f1408d7323b867459
Java
AY2021S1-CS2103T-W11-1/tp
/src/test/java/seedu/address/logic/parser/AppointmentScheduleCommandParserTest.java
UTF-8
2,428
2.171875
2
[ "LicenseRef-scancode-other-permissive", "MIT" ]
permissive
package seedu.address.logic.parser; import static seedu.address.logic.commands.appointmentcommands.AppointmentCommandTestUtil.DESCRIPTION_DESC_ONE; import static seedu.address.logic.commands.appointmentcommands.AppointmentCommandTestUtil.END_DESC_ONE; import static seedu.address.logic.commands.appointmentcommands.AppointmentCommandTestUtil.PATIENT_DESC_ONE; import static seedu.address.logic.commands.appointmentcommands.AppointmentCommandTestUtil.PREAMBLE_WHITESPACE; import static seedu.address.logic.commands.appointmentcommands.AppointmentCommandTestUtil.START_DESC_ONE; import static seedu.address.logic.commands.appointmentcommands.AppointmentCommandTestUtil.TAG_DESC_ONE; import static seedu.address.logic.commands.appointmentcommands.AppointmentCommandTestUtil.VALID_PATIENT_ONE; import static seedu.address.logic.commands.appointmentcommands.AppointmentCommandTestUtil.VALID_TAG_ONE; import static seedu.address.logic.parser.CommandParserTestUtil.assertParseSuccess; import static seedu.address.testutil.TypicalPatients.getTypicalAddressBook; import org.junit.jupiter.api.Test; import seedu.address.logic.commands.appointmentcommands.AppointmentScheduleCommand; import seedu.address.logic.parser.appointmentparser.AppointmentScheduleCommandParser; import seedu.address.model.Model; import seedu.address.model.ModelManager; import seedu.address.model.UserPrefs; import seedu.address.model.appointment.Appointment; import seedu.address.testutil.AppointmentBuilder; public class AppointmentScheduleCommandParserTest { private AppointmentScheduleCommandParser parser = new AppointmentScheduleCommandParser(); private Model model = new ModelManager(getTypicalAddressBook(), new UserPrefs()); @Test public void parse_allFieldsPresent_success() { String expectedPatientString = VALID_PATIENT_ONE; Appointment expectedAppointment = new AppointmentBuilder() .withPatientString(expectedPatientString) .withTags(VALID_TAG_ONE).buildAppointmentWithPatientString(); AppointmentScheduleCommand appointmentScheduleCommand = new AppointmentScheduleCommand(expectedAppointment); // whitespace only preamble assertParseSuccess(parser, PREAMBLE_WHITESPACE + START_DESC_ONE + END_DESC_ONE + PATIENT_DESC_ONE + DESCRIPTION_DESC_ONE + TAG_DESC_ONE, appointmentScheduleCommand); } }
true
865abd4d40a835f0a33bad1da6812c6c6d34e351
Java
gyh03/mySpringCloud
/my-testApp2/src/main/java/com/gyh/feign/FirstFeignService.java
UTF-8
380
1.601563
2
[]
no_license
package com.gyh.feign; //import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; /** * @author guoyanhong * @date 2018/10/17 16:01 */ @FeignClient("myTestApp") public interface FirstFeignService { @GetMapping("getSomeMsg") Object getSomeMsg() ; }
true
c48df7d01ea547fb925f4c5701e75c3a0f5d7b83
Java
Iryna-Yermalovich/HomeTasks
/src/Tasks/JavaTask8.java
UTF-8
831
3.84375
4
[]
no_license
package Tasks; import java.util.Scanner; public class JavaTask8 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int k; int[] mas = new int[3]; while (true) { try { System.out.println("Enter three numbers: "); for (int i = 0; i < mas.length; i++) { if (sc.hasNextDouble()) { mas[i] = Integer.parseInt(sc.nextLine()); } } System.out.println("Enter k: "); k = Integer.parseInt(sc.nextLine()); break; } catch (NumberFormatException e) { System.out.println("Incorrect number!\n"); continue; } } getSum(mas, k); sc.close(); } public static void getSum(int[] mas, int k) { int sum = 0; for (int i = 0; i < mas.length; i++) { if (mas[i] % k == 0) { sum += mas[i]; } } System.out.println("Sum = " + sum); } }
true
eeecc85c881af8eae923d21d2bea26d71a70a297
Java
jaehong0721/Driver
/app/src/main/java/com/rena21/driver/view/adapter/EstimateItemAdapter.java
UTF-8
2,355
2.453125
2
[]
no_license
package com.rena21.driver.view.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.rena21.driver.R; import com.rena21.driver.models.RepliedEstimateItem; import com.rena21.driver.models.RequestedEstimateItem; import com.rena21.driver.view.widget.CurrencyFormatTextView; import java.util.ArrayList; public class EstimateItemAdapter extends RecyclerView.Adapter<EstimateItemAdapter.EstimateItemViewHolder> { ArrayList<? extends RequestedEstimateItem> estimateItems; boolean isReplied; class EstimateItemViewHolder extends RecyclerView.ViewHolder { TextView tvItemInfo; CurrencyFormatTextView tvPrice; public EstimateItemViewHolder(View itemView) { super(itemView); tvItemInfo = (TextView) itemView.findViewById(R.id.tvItemInfo); tvPrice = (CurrencyFormatTextView) itemView.findViewById(R.id.tvPrice); } public void setChildVisibility() { if(isReplied) tvPrice.setVisibility(View.VISIBLE); else tvPrice.setVisibility(View.GONE); } public void bind(RequestedEstimateItem requestedEstimateItem) { String itemName = requestedEstimateItem.itemName; String itemNum = requestedEstimateItem.itemNum; tvItemInfo.setText(itemName + ", " + itemNum); if(isReplied) tvPrice.setWon(((RepliedEstimateItem) requestedEstimateItem).price); } } public EstimateItemAdapter(ArrayList<? extends RequestedEstimateItem> estimateItems, boolean isReplied) { this.estimateItems = estimateItems; this.isReplied = isReplied; } @Override public EstimateItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycler_estimate_item, parent, false); return new EstimateItemViewHolder(view); } @Override public void onBindViewHolder(EstimateItemViewHolder holder, int position) { holder.setChildVisibility(); holder.bind(estimateItems.get(position)); } @Override public int getItemCount() { return estimateItems.size(); } }
true
639cbd1bddd397a0ff1c924d93fd29a3b2653961
Java
ManikyaSabharwal/Playground
/Finding the Maximum sum subsequence/Main.java
UTF-8
590
3.203125
3
[]
no_license
import java.util.Scanner; class Main { public static void main(String args[]) { // your code here Scanner sc= new Scanner(System.in); int size = sc.nextInt(); int arr[] = new int[size]; for(int i = 0 ; i < size ; i++) arr[i] = sc.nextInt(); int maxsum =0; int sum = arr[0]; for(int i =1 ; i < size ; i++){ if(arr[i-1] < arr[i]){ sum+= arr[i]; if(sum > maxsum) maxsum = sum; } else { sum = arr[i]; if(sum > maxsum) maxsum = sum; } } System.out.print(maxsum); } }
true
8ba62af2b884336b1227b8557927b205a69cdcd3
Java
MichaelKilleenSandbox/nytd-s
/src/main/java/gov/hhs/acf/cb/nytds/persistence/entity/helper/ExtSecondaryUserRole.java
UTF-8
1,845
2.328125
2
[]
no_license
package gov.hhs.acf.cb.nytds.persistence.entity.helper; import gov.hhs.acf.cb.nytds.persistence.entity.DerivedRole; import gov.hhs.acf.cb.nytds.persistence.entity.SecondaryUserRole; import gov.hhs.acf.cb.nytds.persistence.entity.SiteUserSecondaryUserRole; import java.io.Serializable; import java.util.Set; public class ExtSecondaryUserRole implements Serializable, SecondaryUserRole.Client { /** * */ private static final long serialVersionUID = 1L; private SecondaryUserRole baseModel; private enum SecondaryRole { MANAGER("Manager", "(state users only)"), DATA_ANALYST("Data Analyst", "(federal users only)"), STATE_AUTH_OFF("State Authorized Official", "(state users only)"); public final String roleName; public final String descriptor; private SecondaryRole (String roleName, String descriptor) { this.roleName = roleName; this.descriptor = descriptor; } public static SecondaryRole resolveRoleName(String roleName) { SecondaryRole resolved = null; for (SecondaryRole sr : SecondaryRole.values() ) { if (roleName.equalsIgnoreCase(sr.roleName)) { resolved = sr; break; } } return resolved; } } public ExtSecondaryUserRole(SecondaryUserRole baseModel) { this.baseModel = baseModel; } public String getLabel() { StringBuilder label = new StringBuilder(baseModel.getName()); SecondaryRole sr = SecondaryRole.resolveRoleName(baseModel.getName()); if (sr != null) label.append(" ").append(sr.descriptor); return label.toString(); } @Override public String getName() { return baseModel.getName(); } @Override public Set<DerivedRole> getDerivedRoles() { return baseModel.getDerivedRoles(); } @Override public Set<SiteUserSecondaryUserRole> getSiteUserSecondaryUserRoles() { return baseModel.getSiteUserSecondaryUserRoles(); } }
true
7d86fdf3f23ef5db47319d1f88b0c1aa7032fc92
Java
motubuyu/New-Datang
/DatangTelecom/src/main/java/pers/deng/DatangTelecom/web/util/StaffFrom.java
GB18030
1,036
2.1875
2
[]
no_license
package pers.deng.DatangTelecom.web.util; import java.util.List; import pers.deng.DatangTelecom.data.bean.Employee; import pers.deng.DatangTelecom.data.bean.Plan; import pers.deng.DatangTelecom.data.bean.Task; public class StaffFrom { private Employee emp;//ڶеķIDѯϢ private Task task;//һʵʩ˵һ private List<Plan> plans;//еIDѯµмƻ public StaffFrom() { super(); // TODO Auto-generated constructor stub } public StaffFrom(Employee emp, Task task, List<Plan> plans) { super(); this.emp = emp; this.task = task; this.plans = plans; } public Employee getEmp() { return emp; } public void setEmp(Employee emp) { this.emp = emp; } public Task getTask() { return task; } public void setTask(Task task) { this.task = task; } public List<Plan> getPlans() { return plans; } public void setPlans(List<Plan> plans) { this.plans = plans; } }
true
c3d3381b025dbda5c48c9181f511ede5c896ca7e
Java
KaPrimov/JavaTasksProgrammingFundamentals
/LINQMoreExercisesExtended/src/f_BankingSystem.java
UTF-8
2,654
3.4375
3
[]
no_license
import java.math.BigDecimal; import java.text.DecimalFormat; import java.util.LinkedHashMap; import java.util.Map; import java.util.Scanner; public class f_BankingSystem { public static void main(String[] args) { LinkedHashMap<String, LinkedHashMap<String, BigDecimal>> customers = new LinkedHashMap<>(); Scanner scanner = new Scanner(System.in); String[] tokens = scanner.nextLine().split(" -> "); while (!"end".equals(tokens[0])) { String bank = tokens[0]; String account = tokens[1]; BigDecimal balance = new BigDecimal(tokens[2]); customers.putIfAbsent(bank, new LinkedHashMap<>()); customers.get(bank).putIfAbsent(account, BigDecimal.ZERO); customers.get(bank).put(account, customers.get(bank).get(account).add(balance)); tokens = scanner.nextLine().split(" -> "); } DecimalFormat df = new DecimalFormat(); df.setMaximumFractionDigits(20); customers.entrySet().stream() .sorted((a, b) -> { BigDecimal aValue = a.getValue().entrySet() .stream() .map(Map.Entry::getValue) .reduce(BigDecimal.ZERO, BigDecimal::add); BigDecimal bValue = b.getValue().entrySet() .stream() .map(Map.Entry::getValue) .reduce(BigDecimal.ZERO, BigDecimal::add); int index = bValue.compareTo(aValue); if (index == 0) { BigDecimal maxAValue = a.getValue().entrySet() .stream() .map(Map.Entry::getValue) .max(BigDecimal::compareTo).get(); BigDecimal maxBValue = b.getValue().entrySet() .stream() .map(Map.Entry::getValue) .max(BigDecimal::compareTo).get(); index = maxBValue.compareTo(maxAValue); } return index; }) .forEach(b -> { b.getValue().entrySet() .stream() .sorted((a1, a2) -> a2.getValue().compareTo(a1.getValue())) .forEach(a -> { System.out.printf("%s -> %s (%s)%n", a.getKey(), a.getValue(), b.getKey()); }); }); } }
true
6d5be4a86b98ecc66bc60fb8c3301aec6d31acac
Java
Floppy777/WebServiceBook
/WebServiceBook/src/esipe/mobi/controllers/BookController.java
UTF-8
2,503
2.609375
3
[]
no_license
package esipe.mobi.controllers; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import com.sun.jersey.spi.resource.Singleton; import esipe.mobi.beans.Book; import esipe.mobi.daos.BookDao; @Path("/book") @Singleton public class BookController { public BookController(){ } @GET @Path("test") @Produces(MediaType.TEXT_PLAIN) public String test(@Context HttpServletRequest info){ return "Hello World"; } @GET @Produces(MediaType.APPLICATION_JSON) public Response getBooks(){ List<Book> listBook = null; listBook = BookDao.getAllBooks(); System.out.println("GetAllBook from Mysql Database : "+ listBook.size()); return Response.status(Status.OK).entity(listBook).build(); } @GET @Path("isbn/{isbn}") @Produces(MediaType.APPLICATION_JSON) public Response getBookByID(@PathParam("isbn") int isbn) { Book book = BookDao.getBookByIsbn(isbn); System.out.println("Get book from Mysql Database with isbn = " + isbn); return Response.status(Status.OK).entity(book).build(); } @GET @Path("author/{author}") @Produces(MediaType.APPLICATION_JSON) public Response getBookByAuthor(@PathParam("author") String author) { List<Book> books; books = BookDao.getBookByAuthor(author); System.out.println("Get books from Mysql Database with author = "+author); return Response.status(Status.OK).entity(books).build(); } @POST @Consumes(MediaType.APPLICATION_JSON) public Response postBookByElements(Book b) { BookDao.save(b); System.out.println("Book save in Mysql Database"); return Response.status(Status.CREATED).build(); } @PUT @Path("isbn/{isbn}") @Consumes(MediaType.APPLICATION_JSON) public Response updateBookByIsbn(Book b, @PathParam("isbn") int isbn){ BookDao.update(b, isbn); System.out.println("Book with isbn = " + isbn + " update in Mysql Database"); return Response.status(Status.OK).build(); } @DELETE @Path("isbn/{isbn}") public Response deleteBokoById(@PathParam("isbn") int isbn){ BookDao.delete(isbn); System.out.println("Book with isbn = " + isbn + " was delete in Mysql Database"); return Response.status(Status.OK).build(); } }
true
43bceca7e1660b0bc8f3f43c593f85c3264c7770
Java
Aleks-Ya/yaal_examples
/Java+/JSE+/Core/test/nio/buffer/CharBufferTest.java
UTF-8
357
2.484375
2
[]
no_license
package nio.buffer; import org.junit.jupiter.api.Test; import java.nio.CharBuffer; import static org.assertj.core.api.Assertions.assertThat; class CharBufferTest { @Test void allocate() { var cb = CharBuffer.allocate(3); var data = "abc"; cb.put(data); assertThat(new String(cb.array())).isEqualTo(data); } }
true
6f7c51c55db1165c786b47e0c8b83c0629bad178
Java
ismailyurtdakal/JavaBasics
/src/com/syntax/class07/Class7Slide8ScannerAndLoops.java
UTF-8
430
3.515625
4
[]
no_license
package com.syntax.class07; import java.util.Scanner; public class Class7Slide8ScannerAndLoops { public static void main(String[] args) { //we want to ask user's name and print Good afternoon ____; int num = 1; Scanner input=new Scanner(System.in); while(num<=5) { System.out.println("What is your name"); String name=input.nextLine(); System.out.println("Good afternoon "+name); num++; } } }
true
b4db389e9e022192d3e1c6c7912db3471e87741d
Java
rexfilius/CryptoWatch
/app/src/main/java/com/ifyosakwe/cryptowatch/activities/TrackingActivity.java
UTF-8
476
1.8125
2
[]
no_license
package com.ifyosakwe.cryptowatch.activities; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.ifyosakwe.cryptowatch.tracking.Tracker; public class TrackingActivity extends AppCompatActivity { protected Tracker mTracker; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mTracker = new Tracker(this); } }
true
58fc09143b41175d97ab4c25554dcd74a186b21f
Java
Chener-Zhang/BookShelf-App
/Assignment6/app/src/main/java/edu/temple/assignment6/CanvasFragment.java
UTF-8
1,974
2.5625
3
[]
no_license
package edu.temple.assignment6; import android.graphics.Color; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.HashMap; import java.util.Map; public class CanvasFragment extends Fragment { private String[] MYCOLORLIST; private String[] MYCOLORLIST_HEX; private int LENGTH_OF_COLOR; private Map MY_COLOR_MAP; public static CanvasFragment newInstance(String color, String color_hex){ CanvasFragment canvasFragment = new CanvasFragment(); Bundle binder = new Bundle(); binder.putString("color",color); binder.putString("color_hex",color_hex); canvasFragment.setArguments(binder); return canvasFragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View myview = inflater.inflate(R.layout.fragment_canvas, container, false); map_setup(); Bundle bundle = getArguments(); if(bundle!=null){ String color = bundle.getString("color"); System.out.println("i received " + color); String hex = (String) MY_COLOR_MAP.get(color); myview.setBackgroundColor(Color.parseColor(hex)); }else{ System.out.println("there is nothing"); } return myview; } public void map_setup(){ //Get the list MYCOLORLIST = getResources().getStringArray(R.array.color_list); MYCOLORLIST_HEX = getResources().getStringArray(R.array.color_hex); Map<String, String> Color_map = new HashMap<String, String>(); int len = MYCOLORLIST.length; LENGTH_OF_COLOR = len; for (int i = 0; i < len; i++) { Color_map.put(MYCOLORLIST[i], MYCOLORLIST_HEX[i]); } MY_COLOR_MAP = Color_map; } }
true
512a65f4a7b8a983d51f56b54a012812e1e343b2
Java
jia-ying09/3U-Assignment-5
/src/HangmanGame.java
UTF-8
12,329
2.8125
3
[]
no_license
import java.awt.GraphicsConfiguration; import java.util.Scanner; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author linj4653 */ public class HangmanGame extends javax.swing.JFrame { /** * Creates new form HangmanGame */ public HangmanGame() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { word = new javax.swing.JLabel(); wordInput = new javax.swing.JTextField(); enter = new javax.swing.JButton(); enterGuess = new javax.swing.JButton(); guessInput = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); output = new javax.swing.JTextArea(); guess = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); word.setText("Player 1 Enter Word:"); wordInput.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { wordInputActionPerformed(evt); } }); enter.setText("Enter"); enter.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { enterActionPerformed(evt); } }); enterGuess.setText("Enter Guess"); enterGuess.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { enterGuessActionPerformed(evt); } }); guessInput.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { guessInputActionPerformed(evt); } }); output.setColumns(20); output.setRows(5); jScrollPane1.setViewportView(output); guess.setText("Player 2 Guess a letter:"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(enterGuess) .addGroup(layout.createSequentialGroup() .addComponent(word, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(wordInput, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addComponent(enter, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(6, 6, 6) .addComponent(guess, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(guessInput, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 424, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(44, 44, 44) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(word, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(wordInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(enter)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(guess, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(guessInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(20, 20, 20) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE) .addGap(18, 18, 18) .addComponent(enterGuess) .addGap(8, 8, 8)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void wordInputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_wordInputActionPerformed }//GEN-LAST:event_wordInputActionPerformed private void enterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enterActionPerformed //insert Scanner Scanner input = new Scanner(System.in); int right = 0; int wrong = 0; //input the word String word = wordInput.getText(); String words = word; //clear the screen wordInput.setText(word + " "); //get the length of the word int length = word.length(); //print out a line for each letter for (int i = 0; i < length; i++) { String one = word.substring(i, i + 1); //get character char character = word.charAt(i); word = word.replace(character, '-'); output.setText(word); } StringBuilder dash = new StringBuilder(word); }//GEN-LAST:event_enterActionPerformed private void enterGuessActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enterGuessActionPerformed //insert Scanner Scanner input = new Scanner(System.in); int right = 0; int wrong = 0; //input the word String word = wordInput.getText(); String words = word; //clear the screen wordInput.setText(word + " "); //get the length of the word int length = word.length(); //print out a line for each letter for (int i = 0; i < length; i++) { String one = word.substring(i, i + 1); //get character char character = word.charAt(i); word = word.replace(character, '-'); output.setText(word); } StringBuilder dash = new StringBuilder(word); while ((wrong < 6) && (right < length)) { int x = 0; // showing the start of the gallows if (wrong == 0) //showing the word with their current correctly guessed letters and asking for a guess { System.out.println(dash); } output.setText("Enter your guess"); //next letter typed is your guess String guess = input.nextLine(); char guesses = guess.charAt(0); //comparing guess against each letter in the word and if it correct replace the dash with the letter for (int i = 0; i < length;) { char letter = words.charAt(i); if (guesses == letter) { right++; x++; dash.setCharAt(i, guesses); } i++; } //tell the plyer how many lives they have left if (x < 1) { wrong++; if (wrong == 1) { output.setText("You have 5 lives left"); } if (wrong == 2) { output.setText("You have 4 lives left"); } if (wrong == 3) { output.setText("You have 3 lives left"); } if (wrong == 4) { output.setText("You have 2 lives left"); } if (wrong == 5) { output.setText("You have 1 life left"); } if (wrong == 6) { output.setText("You have no lives left"); } } } //telling them they won if (right == length) { String dashes = dash.toString(); output.setText(dashes); output.setText("YOU WIN!"); //telling them they lost and telling them what the word was } else { output.setText("GAME OVER"); output.setText("The word was " + words); } }//GEN-LAST:event_enterGuessActionPerformed private void guessInputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guessInputActionPerformed // TODO add your handling code here: }//GEN-LAST:event_guessInputActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(HangmanGame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(HangmanGame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(HangmanGame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(HangmanGame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new HangmanGame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton enter; private javax.swing.JButton enterGuess; private javax.swing.JLabel guess; private javax.swing.JTextField guessInput; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea output; private javax.swing.JLabel word; private javax.swing.JTextField wordInput; // End of variables declaration//GEN-END:variables }
true
265fd4ff4fab526edc0f6d4df6493963db191a33
Java
ccjavadozent/oca_162982
/Projekte/Objektorientiert/src/vererbung/B01_extends_fuer_IS_A_Beziehung.java
UTF-8
1,847
3.46875
3
[]
no_license
package vererbung; /* * Basisklasse Fahrzeug */ class Fahrzeug { private String hersteller, modell; public Fahrzeug(String hersteller, String modell) { this.hersteller = hersteller; this.modell = modell; } public String getModell() { return modell; } @Override public String toString() { return hersteller + " " + modell; } } /* * Abgeleitete Klasse PKW */ class PKW extends Fahrzeug { public PKW(String hersteller, String modell) { super(hersteller, modell); // this.hersteller = hersteller; // this.modell = modell; } public void automatischEinparken() { System.out.println("Parkassistent wird aktiviert..."); } } /* * Abgeleitete Klasse LKW */ class LKW extends Fahrzeug { private int last; public LKW(String hersteller, String modell) { super(hersteller, modell); // this.hersteller = hersteller; // this.modell = modell; } public void beladen(int last) { this.last = last; } } /* * Aufgabe 1. In einem neuen Klassendiagramm 'Fahrzeuge_Version1.uxf' aktuelle PKW und LKW darstellen */ public class B01_extends_fuer_IS_A_Beziehung { public static void main(String[] args) { PKW pkw = new PKW("Opel", "Corsa"); System.out.println("pkw: " + pkw); System.out.println("Modell von pkw: " + pkw.getModell()); pkw.automatischEinparken(); // pkw.beladen(20); // darf nicht kompilieren LKW lkw = new LKW("MAN", "M1"); System.out.println("lkw: " + lkw); System.out.println("Modell von lkw: " + lkw.getModell()); // lkw.automatischEinparken(); // darf nicht kompilieren lkw.beladen(20); // PKW var = new LKW("MAN", "M2"); // darf nicht kompilieren // var.automatischEinparken(); // LKW var2 = new PKW("VW", "Golf"); // darf nicht kompilieren // var2.beladen(33); } }
true
543fd580b777da8add42ca22e4f04acf8bf3cd92
Java
btshoutn/es_search
/IndexInfo.java
UTF-8
1,394
1.875
2
[]
no_license
package com.elastic.service.impl; import java.util.Date; import java.util.Map; /** * Created by xiaotian on 2017/12/15. */ public class IndexInfo { private String name; private Integer age; private Date create_date; private String message; private String tel; private String[] attr_name; private Map<String,Object> attrMap; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Date getCreate_date() { return create_date; } public void setCreate_date(Date create_date) { this.create_date = create_date; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String[] getAttr_name() { return attr_name; } public void setAttr_name(String[] attr_name) { this.attr_name = attr_name; } public Map<String, Object> getAttrMap() { return attrMap; } public void setAttrMap(Map<String, Object> attrMap) { this.attrMap = attrMap; } }
true
e0c23cd9935920914a94c13e3871049a92759436
Java
Beckkhan/job4j
/junior_input_output/src/main/java/ru/job4j/inputoutput/socket/oraclebot/client/ClientOracle.java
UTF-8
1,603
3.046875
3
[ "Apache-2.0" ]
permissive
package ru.job4j.inputoutput.socket.oraclebot.client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.util.Scanner; /** * @author Khan Vyacheslav (mailto: beckkhan@mail.ru) * @version 2.0 * @since 21.02.2019 */ public class ClientOracle { private Socket socket; private static final int PORT = 5000; private static final String IP = "127.0.0.1"; public ClientOracle(Socket socket) throws IOException { this.socket = socket; } public void start() throws IOException { PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); Scanner scanner = new Scanner(System.in); String request = null; String response = null; do { //sending message to server request = scanner.nextLine(); out.println(request); //reading from inputstream if (!"exit".equals(request)) { response = in.readLine(); while (!response.isEmpty()) { System.out.println(response); response = in.readLine(); } } } while (!("exit".equals(request))); } public static void main(String[] args) throws IOException { try (Socket socket = new Socket(InetAddress.getByName(IP), PORT)) { new ClientOracle(socket).start(); } } }
true
e7408ceffabb75338475d3c26af94323fad30e39
Java
sayalija/unix-tools
/src/sayalija/UnixTools/cli/CutClient.java
UTF-8
772
2.71875
3
[]
no_license
package sayalija.UnixTools.cli; import sayalija.UnixTools.Cut; import sayalija.fs.FileSystem; public class CutClient { public static void main(String[] args) { try { String fileName = args[0]; int fieldNumber = Integer.parseInt(args[1].substring(2, args[1].length())); String delimitor = " "; if(args.length == 3 && args[2].contains("-d")) delimitor = (args[2].substring(2, args[2].length())); FileSystem fs = new FileSystem(); String text = fs.readFile(fileName); Cut c = new Cut(delimitor); System.out.println(c.cutLines(text,fieldNumber)); } catch (Exception ex) { System.err.println("Exception " + ex); } } }
true