blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
1123b3841398ee4c91661efd3fcb174bfb01ca82
14,224,931,684,672
7ae84a027db6f32d4538c47f2b29279c997dc4b4
/Applet/awt/PanelDemo1.java
958dfc76985d161d19d3ca171b04ce43418d4a17
[]
no_license
uttarwarsandesh33/JAVA-Examples
https://github.com/uttarwarsandesh33/JAVA-Examples
b020883f48636c0619ba8ce5dadd662404474426
af7f4fae8941325f509345b5465354435bb27b02
refs/heads/master
2021-01-20T03:17:18.243000
2017-08-24T12:01:12
2017-08-24T12:01:12
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// 2005, Set 2 import java.awt.*; public class PanelDemo1 extends Frame { public PanelDemo1() { Panel p1 = new Panel(); Panel p2 = new Panel(); p1.setLayout(new GridLayout(2, 2, 10, 10)); p1.add(new Label("User ID")); p1.add(new TextField(15)); p1.add(new Label("Password")); p1.add(new TextField(15)); p2.add(new Button("OK")); add(p1, "North"); add(p2, "Center"); setTitle("Panels by SNRao"); setSize(300,300); setVisible(true); } public static void main(String args[]) { new PanelDemo1(); } }
UTF-8
Java
668
java
PanelDemo1.java
Java
[]
null
[]
// 2005, Set 2 import java.awt.*; public class PanelDemo1 extends Frame { public PanelDemo1() { Panel p1 = new Panel(); Panel p2 = new Panel(); p1.setLayout(new GridLayout(2, 2, 10, 10)); p1.add(new Label("User ID")); p1.add(new TextField(15)); p1.add(new Label("Password")); p1.add(new TextField(15)); p2.add(new Button("OK")); add(p1, "North"); add(p2, "Center"); setTitle("Panels by SNRao"); setSize(300,300); setVisible(true); } public static void main(String args[]) { new PanelDemo1(); } }
668
0.502994
0.452096
30
21.166666
16.12262
45
false
false
0
0
0
0
0
0
0.733333
false
false
11
39dd7ec25dcdb49279441199f3b54e7e663192b7
7,645,041,789,695
2805f34ecea0d92b201ee45e86e0056718d609fe
/Engine.java
d75939496f2a2e7f71cad03f04b4c27e1a395de6
[]
no_license
simonba/Tower-Defence-Project
https://github.com/simonba/Tower-Defence-Project
255f146a702fc428670b5a5558a07894b4c1b04d
0184eeb692a70cd58c25ab2709e75e78a6d96430
refs/heads/master
2016-09-13T06:20:10.043000
2016-06-09T15:24:55
2016-06-09T15:24:55
58,051,670
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Iterator; import java.util.List; public class Engine { int counter; /** * Constructor for Engine. */ public Engine() { counter = 0; } /** * A counter that counts all the enemies that has managed to go * through the board. * @return An int number of enemies. */ public int getCounter() { return counter; } /** * Method that Game class use to move all enemies in the board. * @param enemies the enemies that are being moved. */ public void act(List<Enemy> enemies) { moveEnemies(enemies); } /** * Moves all enemies that exist. * * @param enemies the enemies that are being moved. */ private void moveEnemies(List<Enemy> enemies) { for (Enemy enemy : enemies) { enemy.move(); } } /** * This method removes the surviving enemies that managed to get through * the board in one piece. An iterator is used to scan through the Lists and * will remove enemies that are at the end Points. * @param enemies The List of enemies that will get iterated. */ public void removeSurvivors(List<Enemy> enemies) { Iterator<Enemy> enemyIterator = enemies.iterator(); while (enemyIterator.hasNext()) { Enemy enemy = enemyIterator.next(); if (enemy.isSurvivor()) { enemyIterator.remove(); counter++; } } } }
UTF-8
Java
1,508
java
Engine.java
Java
[]
null
[]
import java.util.Iterator; import java.util.List; public class Engine { int counter; /** * Constructor for Engine. */ public Engine() { counter = 0; } /** * A counter that counts all the enemies that has managed to go * through the board. * @return An int number of enemies. */ public int getCounter() { return counter; } /** * Method that Game class use to move all enemies in the board. * @param enemies the enemies that are being moved. */ public void act(List<Enemy> enemies) { moveEnemies(enemies); } /** * Moves all enemies that exist. * * @param enemies the enemies that are being moved. */ private void moveEnemies(List<Enemy> enemies) { for (Enemy enemy : enemies) { enemy.move(); } } /** * This method removes the surviving enemies that managed to get through * the board in one piece. An iterator is used to scan through the Lists and * will remove enemies that are at the end Points. * @param enemies The List of enemies that will get iterated. */ public void removeSurvivors(List<Enemy> enemies) { Iterator<Enemy> enemyIterator = enemies.iterator(); while (enemyIterator.hasNext()) { Enemy enemy = enemyIterator.next(); if (enemy.isSurvivor()) { enemyIterator.remove(); counter++; } } } }
1,508
0.578249
0.577586
59
24.559322
22.319918
80
false
false
0
0
0
0
0
0
0.186441
false
false
11
5ee5f43da656f0c5c60295c830efa2cb5a72acf8
9,792,525,479,590
1d1a10f383159b7552e2a77b2b2de2308d845d00
/src/com/lm/common/util/encoding/Main.java
092954b230c6abb1052384834590efceba23c26f
[]
no_license
xxlbq/lmcommon
https://github.com/xxlbq/lmcommon
4d3385d5a5c87d28648cabc00531bfbeaa5bdb5d
512df63830cdc3317370ed2477b4d00ae3443059
refs/heads/master
2016-09-06T06:55:10.860000
2012-12-04T06:26:06
2012-12-04T06:26:06
32,705,917
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lm.common.util.encoding; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.UnsupportedEncodingException; import java.util.Random; import sun.io.ByteToCharConverter; import sun.io.CharToByteConverter; import sun.io.MalformedInputException; public class Main { private static byte[] byteStr; /** * 转换编码 将ISO-8859-1 传换为GBK */ public static String toGBK(String str) { try { if (str == null) { str = ""; } else { byte[] gbt = str.getBytes("ISO-8859-1"); str = new String(gbt, "GBK"); for(int i=0;i<gbt.length;i++){ System.out.println("--------" + gbt[i]); } } } catch (Exception e) { System.out.println("DealString::toGBK(String)运行时出错:错误为:" + e); } return str; } /** * 字符串转换为ASCII */ public static String toASCII(String str) { try { if(str==null) str = ""; else str=new String(str.getBytes("GBK"),"ISO-8859-1"); }catch (Exception e) { System.out.println("DealString::toGBK(String)运行时出错:错误为:"+e); } return str; } /** * 字符串转化为字符串 * */ @SuppressWarnings("deprecation") public static String stringToAscii(String s) { try { CharToByteConverter toByte = CharToByteConverter.getConverter("UTF-8"); byte[] orig = toByte.convertAll(s.toCharArray()); char[] dest = new char[orig.length]; for (int i=0;i<orig.length;i++) { dest[i] = (char)(orig[i] & 0xFF); System.out.println(Integer.toHexString(dest[i])); } return new String(dest); }catch (Exception e) { System.out.println("DealString::ChineseStringToAscii(String)运行时出错:"+e); return s; } } /** * 字符串转化为字符串 * */ @SuppressWarnings("deprecation") public static String byteToAscii(byte[] s,String encodeName) { try { char[] dest = new char[s.length]; for (int i=0;i<s.length;i++) { dest[i] = (char)(s[i] & 0xFF); } // CharToByteConverter toByte = CharToByteConverter.getConverter(encodeName); // toByte.convertAll(dest); return new String(dest); }catch (Exception e) { e.printStackTrace(); return "0"; } } /** * ASCII转化为字符串 * */ @SuppressWarnings("deprecation") public static String asciiToString(String s,String encodeName) { char[] orig = s.toCharArray(); byte[] dest = new byte[orig.length]; for (int i=0;i<orig.length;i++) { dest[i] = (byte)(orig[i]&0xFF); } try { ByteToCharConverter toChar = ByteToCharConverter.getConverter(encodeName); return new String(toChar.convertAll(dest)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; } catch (MalformedInputException e) { e.printStackTrace(); return ""; } } /** * * @param bt * @return */ public static byte[] unicodeToUTF8(byte[] bt){ if(bt.length!=2){ //exception; } int lowH = bt[0]&0x0f; int hightH = (bt[0]<<4)&0x0f; int lowL = bt[1]&0x0f; int lowLL = lowL&0x03; int lowLH = (lowL<<2)&0x03; int hightL = bt[1]&0x0f; byte[] b = new byte[3]; b[0] = (byte)(hightH|0xe0); b[1] = (byte)(0x80|lowH>>2|lowLH); b[2] = (byte)(0x80|lowLL>>4|hightL); return b; } /** * * @param bt * @param encodeName * @return */ @SuppressWarnings("deprecation") public static char[] byteToChar(byte[] bt,String encodeName){ char[] cr = new char[2]; try { ByteToCharConverter convertor = ByteToCharConverter.getConverter(encodeName); cr = convertor.convertAll(bt); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (MalformedInputException e) { e.printStackTrace(); } return cr; } /** * 你"的gb码是:0xC4E3 ,unicode是0x4F60 * 1 1 1 0 _ _ _ _ 1 0 _ _ _ _ _ _ 1 0 _ _ _ _ _ _ * 1110 0100 10 1111 01 10 10 0000 * * e4 bd a0 * 0000 1000 00 00 0000 * 1110 0000 10 1000 00 10 00 0000 * e0 a0 80 * 1110 1000 10 1000 11 10 10 1010 * 1000 1000 1110 1010 88eb * e8b3aa * @throws MalformedInputException */ @SuppressWarnings("deprecation") public static String aa() { Random rand = new Random(); String encoding = "UTF-8"; String reStr = ""; // byte b[] = { (byte) '\u00c4', (byte) '\u00E3' }; //e8b3aa e5958f e382bf e382a4 e38388 e383ab byte b[] = { (byte) '\u00e8', (byte) '\u00b3', (byte) '\u00ab' }; ByteToCharConverter convertor; char[] c = new char[b.length]; try { convertor = ByteToCharConverter.getConverter(encoding); // c = convertor.convertAll((byte)aa[rand.nextInt(aa.length)]); c = convertor.convertAll(b); reStr = new String(convertor.convertAll(b)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (MalformedInputException e) { e.printStackTrace(); } for (int i = 0; i < c.length; i++) { System.out.println(Integer.toHexString(c[i])); } return reStr; } /** * 以下是Unicode和UTF-8之间的转换关系表: * U-00000000 - U-0000007F: 0xxxxxxx * U-00000080 - U-000007FF: 110xxxxx 10xxxxxx * 1100-0000(c0) 1101-1111(df) 1000-0000(80) 1010-1111(bf) * U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx * e0-ef 80-bf 80-bf * U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx * f0-f7 80-bf 80-bf 80-bf * U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx * U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx * f9 88 a7 be * * e4 b8 ad e6 96 87 * 1110-0010 1011-1000 1010-1011 1110-0110 1001-0110 1000-0111 * 中文的范围:\u4e00 - \u9fa5,日文在\u0800 - \u4e00,韩文为\u9fa5以上。 */ /** * utf8 Converter to byte array */ @SuppressWarnings("deprecation") public static String randomStringUTF8(String encodeName){ Random rand = new Random(); int c = rand.nextInt(4); c = 2; byte[] bStr = new byte[c+1]; switch(c){ case 0: //[\x01-\x7f] bStr[0] = stringToByte("01","7f"); break; case 1: //[\xc0-\xdf][\x80-\xbf] //1100-0000 1101-1111 1000-0000 1010-1111 //[\xc0-\xdf] //[\x80-\xbf] bStr[0] = stringToByte("c0","df"); bStr[1] = stringToByte("80","bf"); break; case 2: //[\xe0-\xef][\x80-\xbf]{2} bStr[0] = stringToByte("e0","ef"); bStr[1] = stringToByte("80","bf"); bStr[2] = stringToByte("80","bf"); break; case 3: //[\xf0-\xf7][\x80-\xbf]{3} bStr[0] = stringToByte("f0","f7"); bStr[1] = stringToByte("80","bf"); bStr[2] = stringToByte("80","bf"); bStr[3] = stringToByte("80","bf"); break; } try { ByteToCharConverter toChar = ByteToCharConverter.getConverter(encodeName); char[] bToC = toChar.convertAll(bStr); return new String(bToC); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; } catch (MalformedInputException e) { e.printStackTrace(); return ""; } } /** * * @param start * @param end * @return */ public static byte stringToByte(String start ,String end){ Random rand = new Random(); int[] rang; if(isBlank(start)&&isBlank(end)){ return 0; } if(isBlank(start)){ start = "0"; } if(isBlank(end)){ end = "0"; } if(fromHexStringToByte(start)>fromHexStringToByte(end)){ String m; m = start; start = end; end = m; } rang = getRang(fromHexStringToByte(start),fromHexStringToByte(end)); return (byte)rang[rand.nextInt(rang.length)]; } /** * * @param str * @return */ public static boolean isBlank(String str){ if(str==null){ return true; }else { if((str.trim()).equals("")){ return true; }else{ return false; } } } /** * Convert a hex string to a byte array. Permits upper or lower case hex. * * @param s * String must have even number of characters. and be formed only * of digits 0-9 A-F or a-f. No spaces, minus or plus signs. * @return corresponding byte array. */ public static byte[] fromHexString(String s) { int stringLength = s.length(); if ((stringLength & 0x1) != 0) { throw new IllegalArgumentException( "fromHexString requires an even number of hex characters"); } byte[] b = new byte[stringLength / 2]; for (int i = 0, j = 0; i < stringLength; i += 2, j++) { int high = charToNibble(s.charAt(i)); int low = charToNibble(s.charAt(i + 1)); b[j] = (byte) ((high << 4) | low); } return b; } /** * Convert a hex string to a byte . Permits upper or lower case hex. * * @param s * String must have even number of characters. and be formed only * of digits 0-9 A-F or a-f. No spaces, minus or plus signs. * @return corresponding byte. */ public static byte fromHexStringToByte(String s) { int stringLength = s.length(); if ((stringLength & 0x1) != 0) { throw new IllegalArgumentException( "fromHexString requires an even number of hex characters"); } if (s.length() != 2) { throw new IllegalArgumentException("Invalid hex character: " + s); } byte b = 0; int high = charToNibble(s.charAt(0)); int low = charToNibble(s.charAt(1)); b = (byte) ((high << 4) | low); return b; } /** * Convert a hex string to a byte . Permits upper or lower case hex. * * @param s * String must have even number of characters. and be formed only * of digits 0-9 A-F or a-f. No spaces, minus or plus signs. * @return corresponding byte. */ public static byte[] fromHexStringToByteArray(String s) { int stringLength = s.length(); if ((stringLength & 0x1) != 0) { throw new IllegalArgumentException( "fromHexString requires an even number of hex characters"); } if (s.length()%2!=0) { throw new IllegalArgumentException("Invalid hex character: " + s); } byte[] b = new byte[s.length()/2]; for(int i=0;i<b.length;i++){ int high = charToNibble(s.charAt(i*2)); int low = charToNibble(s.charAt(i*2+1)); b[i] = (byte) ((high << 4) | low); } return b; } /** * convert a single char to corresponding nibble. * * @param c * char to convert. must be 0-9 a-f A-F, no spaces, plus or minus * signs. * * @return corresponding integer */ private static int charToNibble(char c) { if ('0' <= c && c <= '9') { return c - '0'; } else if ('a' <= c && c <= 'f') { return c - 'a' + 0xa; } else if ('A' <= c && c <= 'F') { return c - 'A' + 0xa; } else { throw new IllegalArgumentException("Invalid hex character: " + c); } } /** * * @param start * @param end * @return */ public static int[] getRang(byte start,byte end){ if(start==end){ int[] rang = new int[1]; rang[0] = start; return rang; } int[] rang = new int[end-start]; for(int i=0;i<end-start;i++){ rang[i]=start+i; } return rang; } /** * @param args */ @SuppressWarnings("deprecation") public static void main(String[] args) { String encodeName = "UTF-8"; // [code][\x01-\x7f]|[\xc0-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}[/code] //[\xb0-\xcf][\xa0-\xd3]|[\xd0-\xf4][\xa0-\xfe]|[\xB0-\xF3] //[\xA1-\xFE]|[\xF4][\xA1-\xA6]|[\xA4][\xA1-\xF3]|[\xA5][\xA1-\xF6]|[\xA1][\xBC-\xBE] // System.out.println(main.aa()); System.out.println(asciiToString(stringToAscii("質問タイトル"),encodeName)); //System.out.print(aa()); String s = "88eb"; byte[] b = fromHexStringToByteArray(s); char[] c = byteToChar(unicodeToUTF8(b), encodeName); for (int i = 0; i < c.length; i++) { System.out.println(Integer.toHexString(c[i])); } ByteToCharConverter toChar; try { toChar = ByteToCharConverter.getConverter(encodeName); c = toChar.convertAll(b); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (MalformedInputException e) { e.printStackTrace(); } System.out.println(new String(c)); } /** * */ @SuppressWarnings("deprecation") public static String randomStringUTF8Test(){ //[\xb0-\xcf][\xa0-\xd3] //[code]\xa4[\xa1-\xf3][/code] //[code][\xa1-\xa2][\xa0-\xfe][/code] byte[] bStr = new byte[3]; bStr[0] = stringToByte("e4","e4"); bStr[1] = stringToByte("b8","b8"); bStr[2] = stringToByte("ad","ad"); ByteToCharConverter toChar; try { toChar = ByteToCharConverter.getConverter("UTF-8"); return new String(toChar.convertAll(bStr)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; } catch (MalformedInputException e) { e.printStackTrace(); return ""; } } /** * * @param path * @return */ public static String writeFile(String path){ File f = new File(path); //stream image file BufferedOutputStream bout = null; //@TODO 调整图片的大小后再保存 try { bout = new BufferedOutputStream(new FileOutputStream(f)); byte[] data = new byte[1024]; int length = 0; data = byteStr; bout.write(data, 0, length); } catch (Exception e) { e.printStackTrace(); } finally { if (bout != null) { try { bout.close(); } catch (Exception e) { } } } return ""; } }
UTF-8
Java
14,808
java
Main.java
Java
[]
null
[]
package com.lm.common.util.encoding; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.UnsupportedEncodingException; import java.util.Random; import sun.io.ByteToCharConverter; import sun.io.CharToByteConverter; import sun.io.MalformedInputException; public class Main { private static byte[] byteStr; /** * 转换编码 将ISO-8859-1 传换为GBK */ public static String toGBK(String str) { try { if (str == null) { str = ""; } else { byte[] gbt = str.getBytes("ISO-8859-1"); str = new String(gbt, "GBK"); for(int i=0;i<gbt.length;i++){ System.out.println("--------" + gbt[i]); } } } catch (Exception e) { System.out.println("DealString::toGBK(String)运行时出错:错误为:" + e); } return str; } /** * 字符串转换为ASCII */ public static String toASCII(String str) { try { if(str==null) str = ""; else str=new String(str.getBytes("GBK"),"ISO-8859-1"); }catch (Exception e) { System.out.println("DealString::toGBK(String)运行时出错:错误为:"+e); } return str; } /** * 字符串转化为字符串 * */ @SuppressWarnings("deprecation") public static String stringToAscii(String s) { try { CharToByteConverter toByte = CharToByteConverter.getConverter("UTF-8"); byte[] orig = toByte.convertAll(s.toCharArray()); char[] dest = new char[orig.length]; for (int i=0;i<orig.length;i++) { dest[i] = (char)(orig[i] & 0xFF); System.out.println(Integer.toHexString(dest[i])); } return new String(dest); }catch (Exception e) { System.out.println("DealString::ChineseStringToAscii(String)运行时出错:"+e); return s; } } /** * 字符串转化为字符串 * */ @SuppressWarnings("deprecation") public static String byteToAscii(byte[] s,String encodeName) { try { char[] dest = new char[s.length]; for (int i=0;i<s.length;i++) { dest[i] = (char)(s[i] & 0xFF); } // CharToByteConverter toByte = CharToByteConverter.getConverter(encodeName); // toByte.convertAll(dest); return new String(dest); }catch (Exception e) { e.printStackTrace(); return "0"; } } /** * ASCII转化为字符串 * */ @SuppressWarnings("deprecation") public static String asciiToString(String s,String encodeName) { char[] orig = s.toCharArray(); byte[] dest = new byte[orig.length]; for (int i=0;i<orig.length;i++) { dest[i] = (byte)(orig[i]&0xFF); } try { ByteToCharConverter toChar = ByteToCharConverter.getConverter(encodeName); return new String(toChar.convertAll(dest)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; } catch (MalformedInputException e) { e.printStackTrace(); return ""; } } /** * * @param bt * @return */ public static byte[] unicodeToUTF8(byte[] bt){ if(bt.length!=2){ //exception; } int lowH = bt[0]&0x0f; int hightH = (bt[0]<<4)&0x0f; int lowL = bt[1]&0x0f; int lowLL = lowL&0x03; int lowLH = (lowL<<2)&0x03; int hightL = bt[1]&0x0f; byte[] b = new byte[3]; b[0] = (byte)(hightH|0xe0); b[1] = (byte)(0x80|lowH>>2|lowLH); b[2] = (byte)(0x80|lowLL>>4|hightL); return b; } /** * * @param bt * @param encodeName * @return */ @SuppressWarnings("deprecation") public static char[] byteToChar(byte[] bt,String encodeName){ char[] cr = new char[2]; try { ByteToCharConverter convertor = ByteToCharConverter.getConverter(encodeName); cr = convertor.convertAll(bt); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (MalformedInputException e) { e.printStackTrace(); } return cr; } /** * 你"的gb码是:0xC4E3 ,unicode是0x4F60 * 1 1 1 0 _ _ _ _ 1 0 _ _ _ _ _ _ 1 0 _ _ _ _ _ _ * 1110 0100 10 1111 01 10 10 0000 * * e4 bd a0 * 0000 1000 00 00 0000 * 1110 0000 10 1000 00 10 00 0000 * e0 a0 80 * 1110 1000 10 1000 11 10 10 1010 * 1000 1000 1110 1010 88eb * e8b3aa * @throws MalformedInputException */ @SuppressWarnings("deprecation") public static String aa() { Random rand = new Random(); String encoding = "UTF-8"; String reStr = ""; // byte b[] = { (byte) '\u00c4', (byte) '\u00E3' }; //e8b3aa e5958f e382bf e382a4 e38388 e383ab byte b[] = { (byte) '\u00e8', (byte) '\u00b3', (byte) '\u00ab' }; ByteToCharConverter convertor; char[] c = new char[b.length]; try { convertor = ByteToCharConverter.getConverter(encoding); // c = convertor.convertAll((byte)aa[rand.nextInt(aa.length)]); c = convertor.convertAll(b); reStr = new String(convertor.convertAll(b)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (MalformedInputException e) { e.printStackTrace(); } for (int i = 0; i < c.length; i++) { System.out.println(Integer.toHexString(c[i])); } return reStr; } /** * 以下是Unicode和UTF-8之间的转换关系表: * U-00000000 - U-0000007F: 0xxxxxxx * U-00000080 - U-000007FF: 110xxxxx 10xxxxxx * 1100-0000(c0) 1101-1111(df) 1000-0000(80) 1010-1111(bf) * U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx * e0-ef 80-bf 80-bf * U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx * f0-f7 80-bf 80-bf 80-bf * U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx * U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx * f9 88 a7 be * * e4 b8 ad e6 96 87 * 1110-0010 1011-1000 1010-1011 1110-0110 1001-0110 1000-0111 * 中文的范围:\u4e00 - \u9fa5,日文在\u0800 - \u4e00,韩文为\u9fa5以上。 */ /** * utf8 Converter to byte array */ @SuppressWarnings("deprecation") public static String randomStringUTF8(String encodeName){ Random rand = new Random(); int c = rand.nextInt(4); c = 2; byte[] bStr = new byte[c+1]; switch(c){ case 0: //[\x01-\x7f] bStr[0] = stringToByte("01","7f"); break; case 1: //[\xc0-\xdf][\x80-\xbf] //1100-0000 1101-1111 1000-0000 1010-1111 //[\xc0-\xdf] //[\x80-\xbf] bStr[0] = stringToByte("c0","df"); bStr[1] = stringToByte("80","bf"); break; case 2: //[\xe0-\xef][\x80-\xbf]{2} bStr[0] = stringToByte("e0","ef"); bStr[1] = stringToByte("80","bf"); bStr[2] = stringToByte("80","bf"); break; case 3: //[\xf0-\xf7][\x80-\xbf]{3} bStr[0] = stringToByte("f0","f7"); bStr[1] = stringToByte("80","bf"); bStr[2] = stringToByte("80","bf"); bStr[3] = stringToByte("80","bf"); break; } try { ByteToCharConverter toChar = ByteToCharConverter.getConverter(encodeName); char[] bToC = toChar.convertAll(bStr); return new String(bToC); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; } catch (MalformedInputException e) { e.printStackTrace(); return ""; } } /** * * @param start * @param end * @return */ public static byte stringToByte(String start ,String end){ Random rand = new Random(); int[] rang; if(isBlank(start)&&isBlank(end)){ return 0; } if(isBlank(start)){ start = "0"; } if(isBlank(end)){ end = "0"; } if(fromHexStringToByte(start)>fromHexStringToByte(end)){ String m; m = start; start = end; end = m; } rang = getRang(fromHexStringToByte(start),fromHexStringToByte(end)); return (byte)rang[rand.nextInt(rang.length)]; } /** * * @param str * @return */ public static boolean isBlank(String str){ if(str==null){ return true; }else { if((str.trim()).equals("")){ return true; }else{ return false; } } } /** * Convert a hex string to a byte array. Permits upper or lower case hex. * * @param s * String must have even number of characters. and be formed only * of digits 0-9 A-F or a-f. No spaces, minus or plus signs. * @return corresponding byte array. */ public static byte[] fromHexString(String s) { int stringLength = s.length(); if ((stringLength & 0x1) != 0) { throw new IllegalArgumentException( "fromHexString requires an even number of hex characters"); } byte[] b = new byte[stringLength / 2]; for (int i = 0, j = 0; i < stringLength; i += 2, j++) { int high = charToNibble(s.charAt(i)); int low = charToNibble(s.charAt(i + 1)); b[j] = (byte) ((high << 4) | low); } return b; } /** * Convert a hex string to a byte . Permits upper or lower case hex. * * @param s * String must have even number of characters. and be formed only * of digits 0-9 A-F or a-f. No spaces, minus or plus signs. * @return corresponding byte. */ public static byte fromHexStringToByte(String s) { int stringLength = s.length(); if ((stringLength & 0x1) != 0) { throw new IllegalArgumentException( "fromHexString requires an even number of hex characters"); } if (s.length() != 2) { throw new IllegalArgumentException("Invalid hex character: " + s); } byte b = 0; int high = charToNibble(s.charAt(0)); int low = charToNibble(s.charAt(1)); b = (byte) ((high << 4) | low); return b; } /** * Convert a hex string to a byte . Permits upper or lower case hex. * * @param s * String must have even number of characters. and be formed only * of digits 0-9 A-F or a-f. No spaces, minus or plus signs. * @return corresponding byte. */ public static byte[] fromHexStringToByteArray(String s) { int stringLength = s.length(); if ((stringLength & 0x1) != 0) { throw new IllegalArgumentException( "fromHexString requires an even number of hex characters"); } if (s.length()%2!=0) { throw new IllegalArgumentException("Invalid hex character: " + s); } byte[] b = new byte[s.length()/2]; for(int i=0;i<b.length;i++){ int high = charToNibble(s.charAt(i*2)); int low = charToNibble(s.charAt(i*2+1)); b[i] = (byte) ((high << 4) | low); } return b; } /** * convert a single char to corresponding nibble. * * @param c * char to convert. must be 0-9 a-f A-F, no spaces, plus or minus * signs. * * @return corresponding integer */ private static int charToNibble(char c) { if ('0' <= c && c <= '9') { return c - '0'; } else if ('a' <= c && c <= 'f') { return c - 'a' + 0xa; } else if ('A' <= c && c <= 'F') { return c - 'A' + 0xa; } else { throw new IllegalArgumentException("Invalid hex character: " + c); } } /** * * @param start * @param end * @return */ public static int[] getRang(byte start,byte end){ if(start==end){ int[] rang = new int[1]; rang[0] = start; return rang; } int[] rang = new int[end-start]; for(int i=0;i<end-start;i++){ rang[i]=start+i; } return rang; } /** * @param args */ @SuppressWarnings("deprecation") public static void main(String[] args) { String encodeName = "UTF-8"; // [code][\x01-\x7f]|[\xc0-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}[/code] //[\xb0-\xcf][\xa0-\xd3]|[\xd0-\xf4][\xa0-\xfe]|[\xB0-\xF3] //[\xA1-\xFE]|[\xF4][\xA1-\xA6]|[\xA4][\xA1-\xF3]|[\xA5][\xA1-\xF6]|[\xA1][\xBC-\xBE] // System.out.println(main.aa()); System.out.println(asciiToString(stringToAscii("質問タイトル"),encodeName)); //System.out.print(aa()); String s = "88eb"; byte[] b = fromHexStringToByteArray(s); char[] c = byteToChar(unicodeToUTF8(b), encodeName); for (int i = 0; i < c.length; i++) { System.out.println(Integer.toHexString(c[i])); } ByteToCharConverter toChar; try { toChar = ByteToCharConverter.getConverter(encodeName); c = toChar.convertAll(b); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (MalformedInputException e) { e.printStackTrace(); } System.out.println(new String(c)); } /** * */ @SuppressWarnings("deprecation") public static String randomStringUTF8Test(){ //[\xb0-\xcf][\xa0-\xd3] //[code]\xa4[\xa1-\xf3][/code] //[code][\xa1-\xa2][\xa0-\xfe][/code] byte[] bStr = new byte[3]; bStr[0] = stringToByte("e4","e4"); bStr[1] = stringToByte("b8","b8"); bStr[2] = stringToByte("ad","ad"); ByteToCharConverter toChar; try { toChar = ByteToCharConverter.getConverter("UTF-8"); return new String(toChar.convertAll(bStr)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; } catch (MalformedInputException e) { e.printStackTrace(); return ""; } } /** * * @param path * @return */ public static String writeFile(String path){ File f = new File(path); //stream image file BufferedOutputStream bout = null; //@TODO 调整图片的大小后再保存 try { bout = new BufferedOutputStream(new FileOutputStream(f)); byte[] data = new byte[1024]; int length = 0; data = byteStr; bout.write(data, 0, length); } catch (Exception e) { e.printStackTrace(); } finally { if (bout != null) { try { bout.close(); } catch (Exception e) { } } } return ""; } }
14,808
0.543165
0.496912
536
25.186567
20.672163
102
false
false
0
0
0
0
0
0
1.738806
false
false
11
1f5e78fc0c777d604daf27c5ec44d407e111a8a6
25,675,314,523,871
d5b1beab4cd257001ba8d9812d8d3aee8e4f1a1d
/polymonitor/com.siteview.kernel.core/src/main/java/com/dragonflow/SiteView/ExchangeWMIToolBase.java
bc2c8c362c3c98945e7597b4b45615a3fb4598fe
[]
no_license
liuyaoao/polymer-project
https://github.com/liuyaoao/polymer-project
65e6ace94b150c16a93ac9cfe559b35529192232
0b10de5658b059ad544f48a856fca8c452b65ef4
refs/heads/master
2021-01-24T18:25:50.899000
2017-12-18T02:13:02
2017-12-18T02:13:02
84,430,279
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * * Created on 2014-2-16 15:10:17 * * ExchangeWMIToolBase.java * * History: * */ package com.dragonflow.SiteView; /** * Comment for <code>ExchangeWMIToolBase</code> * * @author * @version 0.0 * * */ import java.util.HashMap; import java.util.Vector; import com.dragonflow.Log.LogManager; import com.dragonflow.Properties.ServerProperty; import com.dragonflow.Properties.StringProperty; import com.dragonflow.Utils.WMIUtils; //import com.dragonflow.WMIMonitor.xdr.property_pair; //import com.dragonflow.WMIMonitor.xdr.property_pair_seq; //import com.dragonflow.WMIMonitor.xdr.wmi_connect; //import com.dragonflow.WMIMonitor.xdr.wmi_instance_result; //import com.dragonflow.WMIMonitor.xdr.wmi_instance_seq; //import com.dragonflow.WMIMonitor.xdr.wmi_run_query; // Referenced classes of package com.dragonflow.SiteView: // ExchangeToolBase, IServerPropMonitor public class ExchangeWMIToolBase extends ExchangeToolBase implements IServerPropMonitor { protected static ServerProperty pHost; protected static StringProperty pUsername; protected static StringProperty pPassword; protected static StringProperty pTimeout; private static final int DEFAULT_TIMEOUT_SECONDS = 60; public ExchangeWMIToolBase() { } protected Vector executeQuery(String s) { // wmi_instance_seq wmi_instance_seq1 = new wmi_instance_seq(); StringBuffer stringbuffer = new StringBuffer(); int i = getPropertyAsInteger(pTimeout); if (i == 0) { i = 60; } // if (!WMIUtils.sendWmiRequest(5, new wmi_run_query(getConnectionInfo(), // s), wmi_instance_seq1, stringbuffer, i)) { // setProperty(pStatus, "error"); // setProperty(pStateString, "Query failed: " + stringbuffer); // LogManager.log("Error", "ExchangeWMIToolBase: " + getFullID() // + " failed, output:\n" + stringbuffer); // return null; // } Vector vector = new Vector(); // for (int j = 0; j < wmi_instance_seq1.size(); j++) { // wmi_instance_result wmi_instance_result1 = wmi_instance_seq1.get(j); // HashMap hashmap = new HashMap(); // vector.add(hashmap); // property_pair_seq property_pair_seq1 = wmi_instance_result1 // .get_properties(); // for (int k = 0; k < property_pair_seq1.size(); k++) { // property_pair property_pair1 = property_pair_seq1.get(k); // hashmap.put(property_pair1.get_prop_key(), property_pair1 // .get_prop_value()); // } // // } return vector; } public String getHostname() { return getProperty(pHost); } // protected wmi_connect getConnectionInfo() { // return new wmi_connect(getProperty(pHost) // + "\\root\\MicrosoftExchangeV2", getProperty(pUsername), // getProperty(pPassword)); // } public StringProperty getServerProperty() { return pHost; } public boolean remoteCommandLineAllowed() { return false; } static { String s = (com.dragonflow.SiteView.ExchangeWMIToolBase.class) .getName(); pHost = new ServerProperty("_server"); pHost.setDisplayText("Server", ""); pHost.setParameterOptions(true, 1, false); pUsername = new StringProperty("_username"); pUsername.setDisplayText("Username", "For accessing WMI statistics on host"); pUsername.setParameterOptions(true, 2, false); pPassword = new StringProperty("_password"); pPassword.setDisplayText("Password", "For accessing WMI statistics on host"); pPassword.setParameterOptions(true, 3, false); pPassword.isPassword = true; pTimeout = new StringProperty("_timeout", "60"); pTimeout.setDisplayText("Timeout", "timeout in seconds for monitor to update"); pTimeout.setParameterOptions(true, 5, true); StringProperty astringproperty[] = { pHost, pUsername, pPassword, pTimeout }; addProperties(s, astringproperty); } }
UTF-8
Java
4,227
java
ExchangeWMIToolBase.java
Java
[ { "context": " 1, false);\n pUsername = new StringProperty(\"_username\");\n pUsername.setDisplayText(\"Username\",\n ", "end": 3452, "score": 0.9241760969161987, "start": 3444, "tag": "USERNAME", "value": "username" }, { "context": "y(\"_username\");\n pUsername.setDisplayText(\"Username\",\n \"For accessing WMI statistics o", "end": 3498, "score": 0.6433871984481812, "start": 3490, "tag": "USERNAME", "value": "Username" } ]
null
[]
/* * * Created on 2014-2-16 15:10:17 * * ExchangeWMIToolBase.java * * History: * */ package com.dragonflow.SiteView; /** * Comment for <code>ExchangeWMIToolBase</code> * * @author * @version 0.0 * * */ import java.util.HashMap; import java.util.Vector; import com.dragonflow.Log.LogManager; import com.dragonflow.Properties.ServerProperty; import com.dragonflow.Properties.StringProperty; import com.dragonflow.Utils.WMIUtils; //import com.dragonflow.WMIMonitor.xdr.property_pair; //import com.dragonflow.WMIMonitor.xdr.property_pair_seq; //import com.dragonflow.WMIMonitor.xdr.wmi_connect; //import com.dragonflow.WMIMonitor.xdr.wmi_instance_result; //import com.dragonflow.WMIMonitor.xdr.wmi_instance_seq; //import com.dragonflow.WMIMonitor.xdr.wmi_run_query; // Referenced classes of package com.dragonflow.SiteView: // ExchangeToolBase, IServerPropMonitor public class ExchangeWMIToolBase extends ExchangeToolBase implements IServerPropMonitor { protected static ServerProperty pHost; protected static StringProperty pUsername; protected static StringProperty pPassword; protected static StringProperty pTimeout; private static final int DEFAULT_TIMEOUT_SECONDS = 60; public ExchangeWMIToolBase() { } protected Vector executeQuery(String s) { // wmi_instance_seq wmi_instance_seq1 = new wmi_instance_seq(); StringBuffer stringbuffer = new StringBuffer(); int i = getPropertyAsInteger(pTimeout); if (i == 0) { i = 60; } // if (!WMIUtils.sendWmiRequest(5, new wmi_run_query(getConnectionInfo(), // s), wmi_instance_seq1, stringbuffer, i)) { // setProperty(pStatus, "error"); // setProperty(pStateString, "Query failed: " + stringbuffer); // LogManager.log("Error", "ExchangeWMIToolBase: " + getFullID() // + " failed, output:\n" + stringbuffer); // return null; // } Vector vector = new Vector(); // for (int j = 0; j < wmi_instance_seq1.size(); j++) { // wmi_instance_result wmi_instance_result1 = wmi_instance_seq1.get(j); // HashMap hashmap = new HashMap(); // vector.add(hashmap); // property_pair_seq property_pair_seq1 = wmi_instance_result1 // .get_properties(); // for (int k = 0; k < property_pair_seq1.size(); k++) { // property_pair property_pair1 = property_pair_seq1.get(k); // hashmap.put(property_pair1.get_prop_key(), property_pair1 // .get_prop_value()); // } // // } return vector; } public String getHostname() { return getProperty(pHost); } // protected wmi_connect getConnectionInfo() { // return new wmi_connect(getProperty(pHost) // + "\\root\\MicrosoftExchangeV2", getProperty(pUsername), // getProperty(pPassword)); // } public StringProperty getServerProperty() { return pHost; } public boolean remoteCommandLineAllowed() { return false; } static { String s = (com.dragonflow.SiteView.ExchangeWMIToolBase.class) .getName(); pHost = new ServerProperty("_server"); pHost.setDisplayText("Server", ""); pHost.setParameterOptions(true, 1, false); pUsername = new StringProperty("_username"); pUsername.setDisplayText("Username", "For accessing WMI statistics on host"); pUsername.setParameterOptions(true, 2, false); pPassword = new StringProperty("_password"); pPassword.setDisplayText("Password", "For accessing WMI statistics on host"); pPassword.setParameterOptions(true, 3, false); pPassword.isPassword = true; pTimeout = new StringProperty("_timeout", "60"); pTimeout.setDisplayText("Timeout", "timeout in seconds for monitor to update"); pTimeout.setParameterOptions(true, 5, true); StringProperty astringproperty[] = { pHost, pUsername, pPassword, pTimeout }; addProperties(s, astringproperty); } }
4,227
0.628342
0.618405
127
32.283466
24.709938
82
false
false
0
0
0
0
0
0
0.692913
false
false
11
8364a162c84324ca807f3915121888030f586243
25,159,918,445,701
d9adc2173e53a91bf2c6d15fe745fb265c87b45f
/src/main/java/cn/maidao/hanlin/api/course/model/CourseSchool.java
92f10be6a27082bad18a0c0f5859f282860c0b83
[]
no_license
cpwk/hanlin-api
https://github.com/cpwk/hanlin-api
53c310cfe8538044d9b9d7e63a02592ae75ea0d9
f885e8b73fba2a3713d07c751d888e71c15c75af
refs/heads/master
2023-03-08T23:22:46.027000
2021-01-06T09:48:14
2021-01-06T09:48:14
299,149,630
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.maidao.hanlin.api.course.model; import cn.maidao.hanlin.api.trainer.model.Trainer; import javax.persistence.*; @Entity @Table(name = "course_school") public class CourseSchool { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private Integer courseId; private Integer schoolId; private Integer categoryId = 0; private Integer trainerId = 0; private String name; private Long createdAt; private Integer priority; private Byte status; private Integer starNum = 0; private Integer visitNum = 0; private Integer buyNum = 0; @Transient private Course course; @Transient private Trainer trainer; public CourseSchool() { } public CourseSchool(Integer courseId, Integer schoolId, Integer categoryId, Integer trainerId, String name) { this.courseId = courseId; this.schoolId = schoolId; this.categoryId = categoryId; this.trainerId = trainerId; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getCourseId() { return courseId; } public void setCourseId(Integer courseId) { this.courseId = courseId; } public Integer getSchoolId() { return schoolId; } public void setSchoolId(Integer schoolId) { this.schoolId = schoolId; } public Long getCreatedAt() { return createdAt; } public void setCreatedAt(Long createdAt) { this.createdAt = createdAt; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } public Integer getPriority() { return priority; } public void setPriority(Integer priority) { this.priority = priority; } public Byte getStatus() { return status; } public void setStatus(Byte status) { this.status = status; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public Integer getTrainerId() { return trainerId; } public void setTrainerId(Integer trainerId) { this.trainerId = trainerId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getVisitNum() { return visitNum; } public void setVisitNum(Integer visitNum) { this.visitNum = visitNum; } public Integer getBuyNum() { return buyNum; } public void setBuyNum(Integer buyNum) { this.buyNum = buyNum; } public Trainer getTrainer() { return trainer; } public void setTrainer(Trainer trainer) { this.trainer = trainer; } public Integer getStarNum() { return starNum; } public void setStarNum(Integer starNum) { this.starNum = starNum; } }
UTF-8
Java
3,129
java
CourseSchool.java
Java
[]
null
[]
package cn.maidao.hanlin.api.course.model; import cn.maidao.hanlin.api.trainer.model.Trainer; import javax.persistence.*; @Entity @Table(name = "course_school") public class CourseSchool { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private Integer courseId; private Integer schoolId; private Integer categoryId = 0; private Integer trainerId = 0; private String name; private Long createdAt; private Integer priority; private Byte status; private Integer starNum = 0; private Integer visitNum = 0; private Integer buyNum = 0; @Transient private Course course; @Transient private Trainer trainer; public CourseSchool() { } public CourseSchool(Integer courseId, Integer schoolId, Integer categoryId, Integer trainerId, String name) { this.courseId = courseId; this.schoolId = schoolId; this.categoryId = categoryId; this.trainerId = trainerId; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getCourseId() { return courseId; } public void setCourseId(Integer courseId) { this.courseId = courseId; } public Integer getSchoolId() { return schoolId; } public void setSchoolId(Integer schoolId) { this.schoolId = schoolId; } public Long getCreatedAt() { return createdAt; } public void setCreatedAt(Long createdAt) { this.createdAt = createdAt; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } public Integer getPriority() { return priority; } public void setPriority(Integer priority) { this.priority = priority; } public Byte getStatus() { return status; } public void setStatus(Byte status) { this.status = status; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public Integer getTrainerId() { return trainerId; } public void setTrainerId(Integer trainerId) { this.trainerId = trainerId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getVisitNum() { return visitNum; } public void setVisitNum(Integer visitNum) { this.visitNum = visitNum; } public Integer getBuyNum() { return buyNum; } public void setBuyNum(Integer buyNum) { this.buyNum = buyNum; } public Trainer getTrainer() { return trainer; } public void setTrainer(Trainer trainer) { this.trainer = trainer; } public Integer getStarNum() { return starNum; } public void setStarNum(Integer starNum) { this.starNum = starNum; } }
3,129
0.615852
0.614254
166
17.849398
17.796919
113
false
false
0
0
0
0
0
0
0.325301
false
false
11
6982bd57f2f93182f6d25306efe316e02ec60d6b
28,552,942,609,428
858bcc58d515f3394bca14b21cd58aedb0608dd1
/algorithm/SelectionHeuristic.java
99b75cd8715d19cbe452984db8e96bc5151c05a2
[]
no_license
EricChang1/P_1.3
https://github.com/EricChang1/P_1.3
c73f3442153ec80010e7bc04538b3bf6dd8bc502
dcaebb54d24806c84341684017a4fb0e31c221ce
refs/heads/master
2021-01-10T17:15:34.792000
2016-02-20T11:41:35
2016-02-20T11:41:35
49,083,781
2
3
null
false
2016-02-04T12:42:36
2016-01-05T18:14:20
2016-01-11T10:16:56
2016-02-04T12:42:36
106
2
3
0
Java
null
null
package algorithm; import java.util.ArrayList; public interface SelectionHeuristic { public int getBestBlock(ArrayList<Resource> list); }
UTF-8
Java
144
java
SelectionHeuristic.java
Java
[]
null
[]
package algorithm; import java.util.ArrayList; public interface SelectionHeuristic { public int getBestBlock(ArrayList<Resource> list); }
144
0.791667
0.791667
9
15
18.257418
51
false
false
0
0
0
0
0
0
0.555556
false
false
11
b603f4010b6ed4cf478c98b56952f09d859c85a5
4,672,924,444,899
41c8afeec4d1444828ecf454e8cd982372638226
/src/main/java/mall/order/service/Impl/AdressServiceImpl.java
171b9a9323f4e7bcc30c4a64b3084ecd6909aced
[]
no_license
YinJinKai/mall
https://github.com/YinJinKai/mall
dc98d2ecaa7f5c0bd0f5b5593466022d0cdd2368
938a683d1baca1ab38d98c1e2db52d7498097286
refs/heads/master
2021-05-04T16:44:28.063000
2018-02-05T06:41:27
2018-02-05T06:41:27
120,258,852
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mall.order.service.Impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import mall.order.mapper.AdressMapper; import mall.order.model.AdressModel; import mall.order.service.AdressService; import mall.utill.Tools; @Service("AdressServiceImpl") public class AdressServiceImpl implements AdressService{ @Autowired private AdressMapper adressMapper; public int insert(AdressModel adress) { // TODO Auto-generated method stub int add = adressMapper.insert(adress); if(add!=0) { return 1;//succeed } return 0; } public List<AdressModel> selectIdAdress(AdressModel adress) { // TODO Auto-generated method stub List<AdressModel> iDaddress = adressMapper.selectIdAdress(adress); return iDaddress; } public int delete(AdressModel adress) { // TODO Auto-generated method stub int del = adressMapper.delete(adress); if(del!=0) { return 1; } return 0; } public int update(AdressModel adress) { // TODO Auto-generated method stub int ua = adressMapper.update(adress); if(ua!=0) { return 1; } return 0; } }
UTF-8
Java
1,195
java
AdressServiceImpl.java
Java
[]
null
[]
package mall.order.service.Impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import mall.order.mapper.AdressMapper; import mall.order.model.AdressModel; import mall.order.service.AdressService; import mall.utill.Tools; @Service("AdressServiceImpl") public class AdressServiceImpl implements AdressService{ @Autowired private AdressMapper adressMapper; public int insert(AdressModel adress) { // TODO Auto-generated method stub int add = adressMapper.insert(adress); if(add!=0) { return 1;//succeed } return 0; } public List<AdressModel> selectIdAdress(AdressModel adress) { // TODO Auto-generated method stub List<AdressModel> iDaddress = adressMapper.selectIdAdress(adress); return iDaddress; } public int delete(AdressModel adress) { // TODO Auto-generated method stub int del = adressMapper.delete(adress); if(del!=0) { return 1; } return 0; } public int update(AdressModel adress) { // TODO Auto-generated method stub int ua = adressMapper.update(adress); if(ua!=0) { return 1; } return 0; } }
1,195
0.717155
0.709623
46
23.97826
19.058821
68
false
false
0
0
0
0
0
0
1.608696
false
false
11
781bdbed748b7ba20f4be428e5693218f331b7f4
2,997,887,203,398
ab38e98fa90191564e1b77a2a88a5ccb93ac6b6e
/server/src/main/java/io/kroki/server/service/ServiceVersion.java
3c715b6eb94efcbb29a728e55a1d6e7c6f4fdd10
[ "MIT" ]
permissive
yuzutech/kroki
https://github.com/yuzutech/kroki
1e8046e485349914a7766d7f1793289cad02ba5f
5ca4e56f3ec080d7ff7063daf795ce35d4375c3c
refs/heads/main
2023-09-04T08:12:44.050000
2023-08-29T13:34:12
2023-08-29T13:34:12
165,063,056
2,218
182
MIT
false
2023-08-31T02:12:35
2019-01-10T13:17:19
2023-08-29T12:56:33
2023-08-31T02:12:35
48,216
2,268
166
89
JavaScript
false
false
package io.kroki.server.service; import java.util.Objects; public class ServiceVersion { private String service; private String version; public ServiceVersion(String service, String version) { this.service = service; this.version = version; } public String getService() { return service; } public String getVersion() { return version; } public String toHTML(String template) { return template .replace("{service}", service) .replace("{version}", version); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ServiceVersion that = (ServiceVersion) o; return Objects.equals(service, that.service) && Objects.equals(version, that.version); } @Override public int hashCode() { return Objects.hash(service, version); } }
UTF-8
Java
896
java
ServiceVersion.java
Java
[]
null
[]
package io.kroki.server.service; import java.util.Objects; public class ServiceVersion { private String service; private String version; public ServiceVersion(String service, String version) { this.service = service; this.version = version; } public String getService() { return service; } public String getVersion() { return version; } public String toHTML(String template) { return template .replace("{service}", service) .replace("{version}", version); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ServiceVersion that = (ServiceVersion) o; return Objects.equals(service, that.service) && Objects.equals(version, that.version); } @Override public int hashCode() { return Objects.hash(service, version); } }
896
0.665179
0.665179
42
20.333334
17.98765
62
false
false
0
0
0
0
0
0
0.52381
false
false
11
00a03a1a182c0cb4aeb3113e9458bb284967d3bf
25,494,925,902,170
90bd2560e0e3f418b58d073390d8daae43f125eb
/project_board_wijmo/src/main/java/com/igo/board/model/cho/dto/ReplyDTO.java
a470eff9e22f0bb33d889b9c285ae3fb5efc1d50
[]
no_license
KyumPaKa/igoSpringStudy
https://github.com/KyumPaKa/igoSpringStudy
bd183f8b3c856d548b4f4e8295b334f652776eaf
5eb365b7322565274bdd7dfa1faf87a394e3708e
refs/heads/master
2022-05-19T04:21:22.843000
2020-01-07T09:04:58
2020-01-07T09:04:58
222,856,360
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.igo.board.model.cho.dto; import java.util.Date; public class ReplyDTO { private int idx; private int refIdx; private int groupIdx; private int groupNo; private int depth; private String content; private String refWriter; private Date regDate; private Date updateDate; private int deleteCheck; public int getIdx() { return idx; } public void setIdx(int idx) { this.idx = idx; } public int getRefIdx() { return refIdx; } public void setRefIdx(int refIdx) { this.refIdx = refIdx; } public int getGroupIdx() { return groupIdx; } public void setGroupIdx(int groupIdx) { this.groupIdx = groupIdx; } public int getGroupNo() { return groupNo; } public void setGroupNo(int groupNo) { this.groupNo = groupNo; } public int getDepth() { return depth; } public void setDepth(int depth) { this.depth = depth; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getrefWriter() { return refWriter; } public void setrefWriter(String refWriter) { this.refWriter = refWriter; } public Date getRegDate() { return regDate; } public void setRegDate(Date regDate) { this.regDate = regDate; } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public int getDeleteCheck() { return deleteCheck; } public void setDeleteCheck(int deleteCheck) { this.deleteCheck = deleteCheck; } @Override public String toString() { return "ReplyDTO [idx=" + idx + ", refIdx=" + refIdx + ", groupIdx=" + groupIdx + ", groupNo=" + groupNo + ", depth=" + depth + ", content=" + content + ", refWriter=" + refWriter + ", regDate=" + regDate + ", updateDate=" + updateDate + ", deleteCheck=" + deleteCheck + "]"; } }
UTF-8
Java
1,846
java
ReplyDTO.java
Java
[]
null
[]
package com.igo.board.model.cho.dto; import java.util.Date; public class ReplyDTO { private int idx; private int refIdx; private int groupIdx; private int groupNo; private int depth; private String content; private String refWriter; private Date regDate; private Date updateDate; private int deleteCheck; public int getIdx() { return idx; } public void setIdx(int idx) { this.idx = idx; } public int getRefIdx() { return refIdx; } public void setRefIdx(int refIdx) { this.refIdx = refIdx; } public int getGroupIdx() { return groupIdx; } public void setGroupIdx(int groupIdx) { this.groupIdx = groupIdx; } public int getGroupNo() { return groupNo; } public void setGroupNo(int groupNo) { this.groupNo = groupNo; } public int getDepth() { return depth; } public void setDepth(int depth) { this.depth = depth; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getrefWriter() { return refWriter; } public void setrefWriter(String refWriter) { this.refWriter = refWriter; } public Date getRegDate() { return regDate; } public void setRegDate(Date regDate) { this.regDate = regDate; } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public int getDeleteCheck() { return deleteCheck; } public void setDeleteCheck(int deleteCheck) { this.deleteCheck = deleteCheck; } @Override public String toString() { return "ReplyDTO [idx=" + idx + ", refIdx=" + refIdx + ", groupIdx=" + groupIdx + ", groupNo=" + groupNo + ", depth=" + depth + ", content=" + content + ", refWriter=" + refWriter + ", regDate=" + regDate + ", updateDate=" + updateDate + ", deleteCheck=" + deleteCheck + "]"; } }
1,846
0.687432
0.687432
85
20.717648
19.404434
106
false
false
0
0
0
0
0
0
1.729412
false
false
11
898c9fd7b02528d6fda85ca3f6392b3b68d990ac
14,783,277,463,593
8a01731637b7d98427e290e9ae0e4b74dc2d86f1
/src/com/zzw/java1000000/z1166166/erasure/ListTest.java
faaa617791aba56abaa74aec5c899de4284fc4a0
[]
no_license
zhengzewang/1000000study
https://github.com/zhengzewang/1000000study
a2629ceff34f2083ab211c6eb64c939248c6d31d
93b0f2d30e36f6653316aec8077b6fd424b099a2
refs/heads/master
2020-04-12T15:55:52.586000
2019-09-02T12:24:07
2019-09-02T12:24:09
162,595,667
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zzw.java1000000.z1166166.erasure; import java.util.ArrayList; import java.util.List; /** * @author zhengzewang on 2019/4/25. */ public class ListTest { public static void main(String[] args) { // List<String> list = new ArrayList<Number>(); List list = new ArrayList<Number>(); List list2 = list; List<String> objects = list2; } }
UTF-8
Java
388
java
ListTest.java
Java
[ { "context": ".ArrayList;\nimport java.util.List;\n\n/**\n * @author zhengzewang on 2019/4/25.\n */\npublic class ListTest {\n\n pu", "end": 125, "score": 0.99922114610672, "start": 114, "tag": "USERNAME", "value": "zhengzewang" } ]
null
[]
package com.zzw.java1000000.z1166166.erasure; import java.util.ArrayList; import java.util.List; /** * @author zhengzewang on 2019/4/25. */ public class ListTest { public static void main(String[] args) { // List<String> list = new ArrayList<Number>(); List list = new ArrayList<Number>(); List list2 = list; List<String> objects = list2; } }
388
0.639175
0.579897
18
20.555555
18.759359
54
false
false
0
0
0
0
0
0
0.388889
false
false
11
dd8ff6b32f88037556e310f3b47143e72931d871
14,783,277,465,178
5584a86a509510c4d8b34b1775c8fb33ad83ae77
/opentach-tools/opentach-tools-common/src/main/java/com/opentach/common/util/concurrent/PriorityThreadPoolExecutor.java
7365f9a621edeed75bee7760cd590f60aa20d822
[]
no_license
bellmit/practicas_empresa
https://github.com/bellmit/practicas_empresa
9413899042984516d63a0eb016de59eb3906234b
c48ed754503cbe2e03ad9f94b48449e92b431e5e
refs/heads/master
2023-07-25T20:49:59.247000
2020-07-31T10:00:24
2020-07-31T10:00:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.opentach.common.util.concurrent; import java.util.Comparator; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.RunnableFuture; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class PriorityThreadPoolExecutor extends ThreadPoolExecutor { public PriorityThreadPoolExecutor(String name, int poolSize, long keepAliveTime, TimeUnit unit) { super(poolSize, poolSize, keepAliveTime, unit, new PriorityBlockingQueue<Runnable>(11, new PriorityTaskComparator()), new NamedThreadFactory(name)); this.allowCoreThreadTimeOut(true); } @Override protected <T> RunnableFuture<T> newTaskFor(final Callable<T> callable) { if (callable instanceof Priorizable) { return new PriorityTask<T>(((Priorizable) callable).getPriority(), callable); } return new PriorityTask<T>(0, callable); } @Override protected <T> RunnableFuture<T> newTaskFor(final Runnable runnable, final T value) { if (runnable instanceof Priorizable) { return new PriorityTask<T>(((Priorizable) runnable).getPriority(), runnable, value); } return new PriorityTask<T>(0, runnable, value); } public interface Priorizable { int getPriority(); } public static final class PriorityTask<T> extends FutureTask<T> implements Comparable<PriorityTask<T>> { private final int priority; private final Object callable; public PriorityTask(final int priority, final Callable<T> tCallable) { super(tCallable); this.callable = tCallable; this.priority = priority; } public PriorityTask(final int priority, final Runnable runnable, final T result) { super(runnable, result); this.callable = runnable; this.priority = priority; } /** * Gets the callable. * * @return the callable */ public Object getWrappedObject() { return this.callable; } @Override public int compareTo(final PriorityTask<T> o) { return o.priority - this.priority; } } private static class PriorityTaskComparator implements Comparator<Runnable> { @Override public int compare(final Runnable left, final Runnable right) { return ((PriorityTask) left).compareTo((PriorityTask) right); } } }
UTF-8
Java
2,346
java
PriorityThreadPoolExecutor.java
Java
[]
null
[]
package com.opentach.common.util.concurrent; import java.util.Comparator; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.RunnableFuture; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class PriorityThreadPoolExecutor extends ThreadPoolExecutor { public PriorityThreadPoolExecutor(String name, int poolSize, long keepAliveTime, TimeUnit unit) { super(poolSize, poolSize, keepAliveTime, unit, new PriorityBlockingQueue<Runnable>(11, new PriorityTaskComparator()), new NamedThreadFactory(name)); this.allowCoreThreadTimeOut(true); } @Override protected <T> RunnableFuture<T> newTaskFor(final Callable<T> callable) { if (callable instanceof Priorizable) { return new PriorityTask<T>(((Priorizable) callable).getPriority(), callable); } return new PriorityTask<T>(0, callable); } @Override protected <T> RunnableFuture<T> newTaskFor(final Runnable runnable, final T value) { if (runnable instanceof Priorizable) { return new PriorityTask<T>(((Priorizable) runnable).getPriority(), runnable, value); } return new PriorityTask<T>(0, runnable, value); } public interface Priorizable { int getPriority(); } public static final class PriorityTask<T> extends FutureTask<T> implements Comparable<PriorityTask<T>> { private final int priority; private final Object callable; public PriorityTask(final int priority, final Callable<T> tCallable) { super(tCallable); this.callable = tCallable; this.priority = priority; } public PriorityTask(final int priority, final Runnable runnable, final T result) { super(runnable, result); this.callable = runnable; this.priority = priority; } /** * Gets the callable. * * @return the callable */ public Object getWrappedObject() { return this.callable; } @Override public int compareTo(final PriorityTask<T> o) { return o.priority - this.priority; } } private static class PriorityTaskComparator implements Comparator<Runnable> { @Override public int compare(final Runnable left, final Runnable right) { return ((PriorityTask) left).compareTo((PriorityTask) right); } } }
2,346
0.730179
0.728474
75
29.306667
31.347929
150
false
false
0
0
0
0
0
0
2.04
false
false
11
dd9b87aec22f530c412c034736ff55909fdfec15
17,678,085,422,888
c4a1317ef17fdcbe37f05801c1d3dc44767b1a25
/src/test/java/com/qsci/database/metadata/entities/TestEntities.java
f36a72b316f20a0dfcf33974707e7fc41ab64389
[]
no_license
maksymSkulinets/Database-metadata-collector
https://github.com/maksymSkulinets/Database-metadata-collector
353f2a17473bb28141bb81a0ce948c6d537faf3c
e330aa32b206af3cb9588075a93dc836fea1ffc0
refs/heads/master
2021-01-10T23:38:39.073000
2016-02-11T00:21:10
2016-02-11T00:21:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qsci.database.metadata.entities; import com.qsci.database.metadata.entities.model.Table; import java.io.FileReader; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayDeque; import java.util.List; import java.util.Properties; import java.util.Queue; public abstract class TestEntities { public Properties getConfig() throws IOException { Properties testConfig = new Properties(); testConfig.load(new FileReader("resources/testSQLite.properties")); return testConfig; } public Queue<String> getTablesNames(List<Table> actual){ Queue<String> tablesNames = new ArrayDeque<String>(); for (Table actualTable : actual ){ if (!actualTable.getName().startsWith("sqlite")) { tablesNames.add(actualTable.getName()); } } return tablesNames; } public abstract List<Table> getExpected(); public abstract List<Table> getActual() throws SQLException, IOException, ClassNotFoundException; }
UTF-8
Java
1,079
java
TestEntities.java
Java
[]
null
[]
package com.qsci.database.metadata.entities; import com.qsci.database.metadata.entities.model.Table; import java.io.FileReader; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayDeque; import java.util.List; import java.util.Properties; import java.util.Queue; public abstract class TestEntities { public Properties getConfig() throws IOException { Properties testConfig = new Properties(); testConfig.load(new FileReader("resources/testSQLite.properties")); return testConfig; } public Queue<String> getTablesNames(List<Table> actual){ Queue<String> tablesNames = new ArrayDeque<String>(); for (Table actualTable : actual ){ if (!actualTable.getName().startsWith("sqlite")) { tablesNames.add(actualTable.getName()); } } return tablesNames; } public abstract List<Table> getExpected(); public abstract List<Table> getActual() throws SQLException, IOException, ClassNotFoundException; }
1,079
0.678406
0.678406
35
28.828571
25.58737
101
false
false
0
0
0
0
0
0
0.542857
false
false
11
ea181248193db5c498c80748fb1fde69609d778f
21,680,994,938,183
1c878a396b69537c8d62586f3443735f3dca4118
/app/src/main/java/com/splitshare/splitshare/Cycle.java
d2cdc21ed7586c0e21b2ae1be34366d221ab8cb3
[]
no_license
dklug/SplitShare
https://github.com/dklug/SplitShare
10b9994e63633a87808d7b736fdbb983e1b7971c
d5aa68a3503ca5c05ec849d69682c72089c46698
refs/heads/master
2021-08-30T22:59:18.650000
2017-12-19T18:55:43
2017-12-19T18:55:43
105,173,801
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.splitshare.splitshare; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; /** * Created by emmanuel on 10/9/17. * Initial implementation by dklug on 10/16/17. */ public class Cycle { enum cycleType { ONE_TIME, DAILY, WEEKLY, MONTHLY, YEARLY } enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } // A Cycle's cycleType reflects it's behaviour public cycleType type; // For use with WEEKLY cycles, relevant days of week. public ArrayList<Boolean> daysOfWeek = new ArrayList<Boolean>(); /** * spacing represents number of days between each event for daily events (every n days) * or number of weeks between weekly events (monday and tuesday every n weeks). Finally, * represents spacing in months for monthly events. * occurrence * Spacing 1 means every, spacing 0 is undefined! spacing 2 means every other. */ public int spacing; /** * If true, is nth day of month for MONTHLY events, marked by dayOfMonth. * If false, is nthOccurrence of first true daysOfWeek day (e.g., 2nd wednesday) */ public boolean isNthDay; public int dayOfMonth; public int nthOccurrence; // Default constructor makes a ONE_TIME cycle public Cycle() { type = cycleType.ONE_TIME; } // Constructor for a DAILY cycle public Cycle(final int s) { type = cycleType.DAILY; setSpacing(s); } // Constructor for a MONTHLY cycle every nth day public Cycle(final int d, final int s) { type = cycleType.MONTHLY; isNthDay = true; dayOfMonth = d; setSpacing(s); } // Constructor for a MONTHLY cycle every dayOfWeek day of the weekOfMonth week public Cycle(final int dayOfWeek, final int weekOfMonth, final int s) { type = cycleType.MONTHLY; isNthDay = false; dayOfMonth = dayOfWeek; nthOccurrence = weekOfMonth; setSpacing(s); } // Constructor for a WEEKLY cycle public Cycle(final boolean[] customWeek, final int s) { type = cycleType.WEEKLY; isNthDay = false; for (int i = 0; i < 7; i++) { daysOfWeek.add(i, customWeek[i]); } setSpacing(s); } // Constructor for a YEARLY cycle // IS_YEARLY is a dummy variable for overloaded constructor to be unique public Cycle(final int month, final int day, final boolean IS_YEARLY) { type = cycleType.YEARLY; dayOfMonth = day; // nthOccurrence = month (0 index) nthOccurrence = month; } public boolean isOnDayWithStart(Calendar start, Calendar thisDay) { Calendar temp = (Calendar)start.clone(); thisDay.set(Calendar.HOUR_OF_DAY, 0); thisDay.set(Calendar.MINUTE, 0); thisDay.set(Calendar.SECOND, 0); thisDay.set(Calendar.MILLISECOND, 0); // always false if this event begins after the day we're checking if (thisDay.before(start)) return false; // else check based on type if (type == cycleType.ONE_TIME) { if (temp.equals(thisDay)) return true; } else if (type == cycleType.DAILY) { /* // OLD METHOD // add spacing until we equal or overshoot while (temp.before(thisDay)) temp.add(Calendar.DATE, spacing); // if equal, it's on thisDay. if (temp.equals(thisDay)) return true; */ long days = (thisDay.getTimeInMillis() - start.getTimeInMillis())/86400000; //(1000*60*60*24) if (days % spacing == 0) return true; } else if (type == cycleType.WEEKLY) { if(daysOfWeek.get(thisDay.get(Calendar.DAY_OF_WEEK)-1)) { // Normalize both days to Sunday Calendar temp2 = (Calendar)thisDay.clone(); temp2.add(Calendar.DATE, 1 - temp2.get(Calendar.DAY_OF_WEEK)); temp.add(Calendar.DATE, 1 - temp.get(Calendar.DAY_OF_WEEK)); // count number of weeks between the normalized weeks long numWeeks = (temp2.getTimeInMillis() - temp.getTimeInMillis())/(7*86400000); // if same week, or "spacing" weeks later, return true if (numWeeks % spacing == 0) return true; } } else if (type == cycleType.MONTHLY) { if (isNthDay) { if (thisDay.get(Calendar.DAY_OF_MONTH) == dayOfMonth) { int numMonths1 = start.get(Calendar.MONTH)+12*start.get(Calendar.YEAR); int numMonths2 = thisDay.get(Calendar.MONTH)+12*thisDay.get(Calendar.YEAR); int diff = numMonths2-numMonths1; if (diff % spacing == 0) return true; } } else { if (nthOccurrence == thisDay.get(Calendar.WEEK_OF_MONTH) && dayOfMonth == thisDay.get(Calendar.DAY_OF_WEEK)) { int numMonths1 = start.get(Calendar.MONTH)+12*start.get(Calendar.YEAR); int numMonths2 = thisDay.get(Calendar.MONTH)+12*thisDay.get(Calendar.YEAR); int diff = numMonths2-numMonths1; if (diff % spacing == 0) return true; //TODO: first monday, but week starts on thurs? FIX! } } } else if (type == cycleType.YEARLY) { if (nthOccurrence == thisDay.get(Calendar.MONTH) && dayOfMonth == thisDay.get(Calendar.DAY_OF_MONTH)) return true; } return false; } public int numOcurrencesSinceStart(Calendar start, Calendar thisDay) { Calendar normalizedStart = (Calendar)start.clone(); normalizedStart.set(Calendar.HOUR_OF_DAY, 0); normalizedStart.set(Calendar.MINUTE, 0); normalizedStart.set(Calendar.SECOND, 0); normalizedStart.set(Calendar.MILLISECOND, 0); Calendar normalizedThisDay = (Calendar)thisDay.clone(); normalizedThisDay.set(Calendar.HOUR_OF_DAY, 0); normalizedThisDay.set(Calendar.MINUTE, 0); normalizedThisDay.set(Calendar.SECOND, 0); normalizedThisDay.set(Calendar.MILLISECOND, 0); // always 0 if this begins after the day we're checking if (thisDay.before(start)) { return 0; } else if (type == cycleType.ONE_TIME) { // DONE if (thisDay.after(start)) return 1; else return 0; } else if (type == cycleType.DAILY) { // DONE long days = (normalizedThisDay.getTimeInMillis() - normalizedStart.getTimeInMillis())/86400000; //(1000*60*60*24) return (int)days / spacing; } else if (type == cycleType.WEEKLY) { // TODO // case thisDay is on the same week as start date if (normalizedStart.get(Calendar.WEEK_OF_YEAR) == normalizedThisDay.get(Calendar.WEEK_OF_YEAR) && (normalizedStart.get(Calendar.YEAR) == normalizedThisDay.get(Calendar.YEAR))) { int daysInFirstWeek = 0; // count number of days in first week for (int i = normalizedStart.get(Calendar.DAY_OF_WEEK) - 1; i < normalizedThisDay.get(Calendar.DAY_OF_WEEK) - 1; i++) { if (daysOfWeek.get(i)) { daysInFirstWeek++; } } return daysInFirstWeek; } // CASE: not same week int daysInFirstWeek = 0; // count number of days in first week for (int i = normalizedStart.get(Calendar.DAY_OF_WEEK) - 1; i < 7; i++) { if (daysOfWeek.get(i)) { daysInFirstWeek++; } } int daysInFinalWeek = 0; // count number of days in end week for (int i = 0; i < thisDay.get(Calendar.DAY_OF_WEEK) - 1; i++) { if (daysOfWeek.get(i)) { daysInFinalWeek++; } } int daysPerWeek = 0; // count days per week for (int i = 0; i < 7; i++) { if (daysOfWeek.get(i)) { daysPerWeek++; } } // Normalize both days to Sunday normalizedThisDay.add(Calendar.DATE, 1 - normalizedThisDay.get(Calendar.DAY_OF_WEEK)); normalizedStart.add(Calendar.DATE, 1 - normalizedStart.get(Calendar.DAY_OF_WEEK)); // count number of weeks between the normalized weeks long numWeeks = (normalizedThisDay.getTimeInMillis() - normalizedStart.getTimeInMillis())/(7*86400000); long weeksBetween = (numWeeks-1)/spacing; // don't count first week long midCount = weeksBetween*daysPerWeek; long totalCount = daysInFirstWeek + midCount; if (numWeeks % spacing == 0) { return (int) (totalCount + daysInFinalWeek); } else { return (int) totalCount; } } else if (type == cycleType.MONTHLY) { int monthDiff = normalizedThisDay.get(Calendar.MONTH) - normalizedStart.get(Calendar.MONTH); int yearDiff = normalizedThisDay.get(Calendar.YEAR) - normalizedStart.get(Calendar.YEAR); int monthsBetween = yearDiff*12 + monthDiff; if (isNthDay) { // if happened this month, +1 // normalize to first day, count months if (normalizedThisDay.get(Calendar.DAY_OF_MONTH) > dayOfMonth) { monthsBetween++; } } else { if (nthOccurrence >= normalizedThisDay.get(Calendar.WEEK_OF_MONTH) && dayOfMonth > normalizedThisDay.get(Calendar.DAY_OF_WEEK)) { monthsBetween++; //TODO: first monday, but week starts on thurs? FIX! } } return monthsBetween; } else if (type == cycleType.YEARLY) { int yearsBetween = normalizedThisDay.get(Calendar.YEAR) - normalizedStart.get(Calendar.YEAR); if (nthOccurrence >= thisDay.get(Calendar.MONTH) && dayOfMonth > thisDay.get(Calendar.DAY_OF_MONTH)) yearsBetween++; return yearsBetween; } return 0; } private void setSpacing(int n) { if (n > 0) spacing = n; else spacing = 1; } }
UTF-8
Java
10,742
java
Cycle.java
Java
[ { "context": "rt java.util.GregorianCalendar;\n\n/**\n * Created by emmanuel on 10/9/17.\n * Initial implementation by dklug on", "end": 154, "score": 0.9953789710998535, "start": 146, "tag": "USERNAME", "value": "emmanuel" }, { "context": " emmanuel on 10/9/17.\n * Initial implementation by dklug on 10/16/17.\n */\n\npublic class Cycle {\n enum c", "end": 201, "score": 0.9996368288993835, "start": 196, "tag": "USERNAME", "value": "dklug" } ]
null
[]
package com.splitshare.splitshare; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; /** * Created by emmanuel on 10/9/17. * Initial implementation by dklug on 10/16/17. */ public class Cycle { enum cycleType { ONE_TIME, DAILY, WEEKLY, MONTHLY, YEARLY } enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } // A Cycle's cycleType reflects it's behaviour public cycleType type; // For use with WEEKLY cycles, relevant days of week. public ArrayList<Boolean> daysOfWeek = new ArrayList<Boolean>(); /** * spacing represents number of days between each event for daily events (every n days) * or number of weeks between weekly events (monday and tuesday every n weeks). Finally, * represents spacing in months for monthly events. * occurrence * Spacing 1 means every, spacing 0 is undefined! spacing 2 means every other. */ public int spacing; /** * If true, is nth day of month for MONTHLY events, marked by dayOfMonth. * If false, is nthOccurrence of first true daysOfWeek day (e.g., 2nd wednesday) */ public boolean isNthDay; public int dayOfMonth; public int nthOccurrence; // Default constructor makes a ONE_TIME cycle public Cycle() { type = cycleType.ONE_TIME; } // Constructor for a DAILY cycle public Cycle(final int s) { type = cycleType.DAILY; setSpacing(s); } // Constructor for a MONTHLY cycle every nth day public Cycle(final int d, final int s) { type = cycleType.MONTHLY; isNthDay = true; dayOfMonth = d; setSpacing(s); } // Constructor for a MONTHLY cycle every dayOfWeek day of the weekOfMonth week public Cycle(final int dayOfWeek, final int weekOfMonth, final int s) { type = cycleType.MONTHLY; isNthDay = false; dayOfMonth = dayOfWeek; nthOccurrence = weekOfMonth; setSpacing(s); } // Constructor for a WEEKLY cycle public Cycle(final boolean[] customWeek, final int s) { type = cycleType.WEEKLY; isNthDay = false; for (int i = 0; i < 7; i++) { daysOfWeek.add(i, customWeek[i]); } setSpacing(s); } // Constructor for a YEARLY cycle // IS_YEARLY is a dummy variable for overloaded constructor to be unique public Cycle(final int month, final int day, final boolean IS_YEARLY) { type = cycleType.YEARLY; dayOfMonth = day; // nthOccurrence = month (0 index) nthOccurrence = month; } public boolean isOnDayWithStart(Calendar start, Calendar thisDay) { Calendar temp = (Calendar)start.clone(); thisDay.set(Calendar.HOUR_OF_DAY, 0); thisDay.set(Calendar.MINUTE, 0); thisDay.set(Calendar.SECOND, 0); thisDay.set(Calendar.MILLISECOND, 0); // always false if this event begins after the day we're checking if (thisDay.before(start)) return false; // else check based on type if (type == cycleType.ONE_TIME) { if (temp.equals(thisDay)) return true; } else if (type == cycleType.DAILY) { /* // OLD METHOD // add spacing until we equal or overshoot while (temp.before(thisDay)) temp.add(Calendar.DATE, spacing); // if equal, it's on thisDay. if (temp.equals(thisDay)) return true; */ long days = (thisDay.getTimeInMillis() - start.getTimeInMillis())/86400000; //(1000*60*60*24) if (days % spacing == 0) return true; } else if (type == cycleType.WEEKLY) { if(daysOfWeek.get(thisDay.get(Calendar.DAY_OF_WEEK)-1)) { // Normalize both days to Sunday Calendar temp2 = (Calendar)thisDay.clone(); temp2.add(Calendar.DATE, 1 - temp2.get(Calendar.DAY_OF_WEEK)); temp.add(Calendar.DATE, 1 - temp.get(Calendar.DAY_OF_WEEK)); // count number of weeks between the normalized weeks long numWeeks = (temp2.getTimeInMillis() - temp.getTimeInMillis())/(7*86400000); // if same week, or "spacing" weeks later, return true if (numWeeks % spacing == 0) return true; } } else if (type == cycleType.MONTHLY) { if (isNthDay) { if (thisDay.get(Calendar.DAY_OF_MONTH) == dayOfMonth) { int numMonths1 = start.get(Calendar.MONTH)+12*start.get(Calendar.YEAR); int numMonths2 = thisDay.get(Calendar.MONTH)+12*thisDay.get(Calendar.YEAR); int diff = numMonths2-numMonths1; if (diff % spacing == 0) return true; } } else { if (nthOccurrence == thisDay.get(Calendar.WEEK_OF_MONTH) && dayOfMonth == thisDay.get(Calendar.DAY_OF_WEEK)) { int numMonths1 = start.get(Calendar.MONTH)+12*start.get(Calendar.YEAR); int numMonths2 = thisDay.get(Calendar.MONTH)+12*thisDay.get(Calendar.YEAR); int diff = numMonths2-numMonths1; if (diff % spacing == 0) return true; //TODO: first monday, but week starts on thurs? FIX! } } } else if (type == cycleType.YEARLY) { if (nthOccurrence == thisDay.get(Calendar.MONTH) && dayOfMonth == thisDay.get(Calendar.DAY_OF_MONTH)) return true; } return false; } public int numOcurrencesSinceStart(Calendar start, Calendar thisDay) { Calendar normalizedStart = (Calendar)start.clone(); normalizedStart.set(Calendar.HOUR_OF_DAY, 0); normalizedStart.set(Calendar.MINUTE, 0); normalizedStart.set(Calendar.SECOND, 0); normalizedStart.set(Calendar.MILLISECOND, 0); Calendar normalizedThisDay = (Calendar)thisDay.clone(); normalizedThisDay.set(Calendar.HOUR_OF_DAY, 0); normalizedThisDay.set(Calendar.MINUTE, 0); normalizedThisDay.set(Calendar.SECOND, 0); normalizedThisDay.set(Calendar.MILLISECOND, 0); // always 0 if this begins after the day we're checking if (thisDay.before(start)) { return 0; } else if (type == cycleType.ONE_TIME) { // DONE if (thisDay.after(start)) return 1; else return 0; } else if (type == cycleType.DAILY) { // DONE long days = (normalizedThisDay.getTimeInMillis() - normalizedStart.getTimeInMillis())/86400000; //(1000*60*60*24) return (int)days / spacing; } else if (type == cycleType.WEEKLY) { // TODO // case thisDay is on the same week as start date if (normalizedStart.get(Calendar.WEEK_OF_YEAR) == normalizedThisDay.get(Calendar.WEEK_OF_YEAR) && (normalizedStart.get(Calendar.YEAR) == normalizedThisDay.get(Calendar.YEAR))) { int daysInFirstWeek = 0; // count number of days in first week for (int i = normalizedStart.get(Calendar.DAY_OF_WEEK) - 1; i < normalizedThisDay.get(Calendar.DAY_OF_WEEK) - 1; i++) { if (daysOfWeek.get(i)) { daysInFirstWeek++; } } return daysInFirstWeek; } // CASE: not same week int daysInFirstWeek = 0; // count number of days in first week for (int i = normalizedStart.get(Calendar.DAY_OF_WEEK) - 1; i < 7; i++) { if (daysOfWeek.get(i)) { daysInFirstWeek++; } } int daysInFinalWeek = 0; // count number of days in end week for (int i = 0; i < thisDay.get(Calendar.DAY_OF_WEEK) - 1; i++) { if (daysOfWeek.get(i)) { daysInFinalWeek++; } } int daysPerWeek = 0; // count days per week for (int i = 0; i < 7; i++) { if (daysOfWeek.get(i)) { daysPerWeek++; } } // Normalize both days to Sunday normalizedThisDay.add(Calendar.DATE, 1 - normalizedThisDay.get(Calendar.DAY_OF_WEEK)); normalizedStart.add(Calendar.DATE, 1 - normalizedStart.get(Calendar.DAY_OF_WEEK)); // count number of weeks between the normalized weeks long numWeeks = (normalizedThisDay.getTimeInMillis() - normalizedStart.getTimeInMillis())/(7*86400000); long weeksBetween = (numWeeks-1)/spacing; // don't count first week long midCount = weeksBetween*daysPerWeek; long totalCount = daysInFirstWeek + midCount; if (numWeeks % spacing == 0) { return (int) (totalCount + daysInFinalWeek); } else { return (int) totalCount; } } else if (type == cycleType.MONTHLY) { int monthDiff = normalizedThisDay.get(Calendar.MONTH) - normalizedStart.get(Calendar.MONTH); int yearDiff = normalizedThisDay.get(Calendar.YEAR) - normalizedStart.get(Calendar.YEAR); int monthsBetween = yearDiff*12 + monthDiff; if (isNthDay) { // if happened this month, +1 // normalize to first day, count months if (normalizedThisDay.get(Calendar.DAY_OF_MONTH) > dayOfMonth) { monthsBetween++; } } else { if (nthOccurrence >= normalizedThisDay.get(Calendar.WEEK_OF_MONTH) && dayOfMonth > normalizedThisDay.get(Calendar.DAY_OF_WEEK)) { monthsBetween++; //TODO: first monday, but week starts on thurs? FIX! } } return monthsBetween; } else if (type == cycleType.YEARLY) { int yearsBetween = normalizedThisDay.get(Calendar.YEAR) - normalizedStart.get(Calendar.YEAR); if (nthOccurrence >= thisDay.get(Calendar.MONTH) && dayOfMonth > thisDay.get(Calendar.DAY_OF_MONTH)) yearsBetween++; return yearsBetween; } return 0; } private void setSpacing(int n) { if (n > 0) spacing = n; else spacing = 1; } }
10,742
0.559672
0.546919
283
36.961132
28.611481
135
false
false
0
0
0
0
0
0
0.561837
false
false
11
24fd25fbb1c998d87f441deab5400927d487f74b
26,482,768,371,128
2dca8455c190f6c41f75a3892905c6dd73e3307e
/app/src/main/java/com/isaacapps/unitconverterapp/dao/api/ApiRequester.java
af0e808a8d95889d62b4fc48773bc2a937f68565
[]
no_license
isaaclafrance/UnitManagerAndConverter
https://github.com/isaaclafrance/UnitManagerAndConverter
b60b793b526ce1e30271e72583a982b43ca16920
2a35f60569533cb0acda57f810ea907ee1a43aaa
refs/heads/master
2020-05-09T13:30:24.424000
2019-02-03T23:02:44
2019-02-03T23:02:44
20,048,402
0
0
null
false
2019-02-03T23:02:45
2014-05-22T04:56:53
2019-02-01T14:11:17
2019-02-03T23:02:45
1,955
0
0
20
Java
false
null
package com.isaacapps.unitconverterapp.dao.api; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.Random; import javax.net.ssl.HttpsURLConnection; public class ApiRequester { private static final Random random = new Random(); public HttpsURLConnection createHttpsURLConnection(String requestURL, String userAgent) throws IOException { HttpsURLConnection requestHttpsURLConnection = (HttpsURLConnection) new URL(requestURL).openConnection(); requestHttpsURLConnection.setRequestProperty("User-Agent", userAgent); return requestHttpsURLConnection; } public HttpsURLConnection createHttpURLConnection(String requestURI) throws IOException { return createHttpsURLConnection(requestURI, createRandomUserAgent()); } private String createRandomUserAgent(){ return String.format("%d@gmail.com", random.nextInt(1000000)); } public String retrieveResponseString(HttpsURLConnection httpsURLConnection) { StringBuilder responseBuilder = new StringBuilder(); try { InputStream bufferedInputStream = new BufferedInputStream(httpsURLConnection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream)); String readLine; while ((readLine = bufferedReader.readLine()) != null) { responseBuilder.append(readLine); } } catch (Exception e) { e.printStackTrace(); } finally { httpsURLConnection.disconnect(); } return responseBuilder.toString(); } }
UTF-8
Java
1,764
java
ApiRequester.java
Java
[ { "context": "ateRandomUserAgent(){\n return String.format(\"%d@gmail.com\", random.nextInt(1000000));\n }\n\n public Str", "end": 999, "score": 0.9462494850158691, "start": 987, "tag": "EMAIL", "value": "%d@gmail.com" } ]
null
[]
package com.isaacapps.unitconverterapp.dao.api; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.Random; import javax.net.ssl.HttpsURLConnection; public class ApiRequester { private static final Random random = new Random(); public HttpsURLConnection createHttpsURLConnection(String requestURL, String userAgent) throws IOException { HttpsURLConnection requestHttpsURLConnection = (HttpsURLConnection) new URL(requestURL).openConnection(); requestHttpsURLConnection.setRequestProperty("User-Agent", userAgent); return requestHttpsURLConnection; } public HttpsURLConnection createHttpURLConnection(String requestURI) throws IOException { return createHttpsURLConnection(requestURI, createRandomUserAgent()); } private String createRandomUserAgent(){ return String.format("<EMAIL>", random.nextInt(1000000)); } public String retrieveResponseString(HttpsURLConnection httpsURLConnection) { StringBuilder responseBuilder = new StringBuilder(); try { InputStream bufferedInputStream = new BufferedInputStream(httpsURLConnection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream)); String readLine; while ((readLine = bufferedReader.readLine()) != null) { responseBuilder.append(readLine); } } catch (Exception e) { e.printStackTrace(); } finally { httpsURLConnection.disconnect(); } return responseBuilder.toString(); } }
1,759
0.719388
0.71542
49
35
33.477375
113
false
false
0
0
0
0
0
0
0.55102
false
false
11
880941683c8af523b00fde6a9f0c8ecabffcdb89
9,629,316,713,051
5d2ac24c2558718c32fe62ff0898080a5921581d
/HttpServer/src/LooluServer/ConfigPort.java
f89e5ccdbcbd86d7e359166d0e995355989ec499
[]
no_license
ChoelWu/LooluServer
https://github.com/ChoelWu/LooluServer
d68d31943152b727cb820987a8a755ba68b445e8
0b526b69d5857b40295d0424c47369239141e83a
refs/heads/master
2020-03-12T13:56:41.588000
2018-04-23T11:12:14
2018-04-23T11:12:14
130,654,437
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package LooluServer; import java.io.*; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.*; public class ConfigPort { private static final String CONF_FILE_NAME = "src/resources/conf/server.conf"; /** * 端口设置 * @param port */ public boolean SetPort(String port) { try { Scanner in = new Scanner(new FileInputStream(CONF_FILE_NAME), "UTF-8"); List<String> ConfContent = new ArrayList<>(); for (int i = 0; i < 10000 ; i ++) { ConfContent.add(in.nextLine().trim()); if (!in.hasNext()) { break; } } String outPrintText = ""; for(int i = 0; i < ConfContent.size();i ++) { String[] arr = ConfContent.get(i).split("="); if(arr[0].trim().equals("PORT") || arr[0].trim().equals("port")) { ConfContent.set(i, "port = " + port); } outPrintText += ConfContent.get(i) + "\n"; } PrintWriter out = new PrintWriter(new FileWriter(CONF_FILE_NAME, false), true); out.println(outPrintText); out.close(); return true; } catch(Exception e) { return false; } } /** * 检查端口是否可用 * @param host * @param port * @return * @throws UnknownHostException */ public static boolean isPortUsing(String host,int port) throws UnknownHostException { boolean flag = false; InetAddress theAddress = InetAddress.getByName(host); try { Socket socket = new Socket(theAddress,port); flag = true; socket.close(); } catch (IOException e) { } return flag; } }
UTF-8
Java
1,876
java
ConfigPort.java
Java
[]
null
[]
package LooluServer; import java.io.*; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.*; public class ConfigPort { private static final String CONF_FILE_NAME = "src/resources/conf/server.conf"; /** * 端口设置 * @param port */ public boolean SetPort(String port) { try { Scanner in = new Scanner(new FileInputStream(CONF_FILE_NAME), "UTF-8"); List<String> ConfContent = new ArrayList<>(); for (int i = 0; i < 10000 ; i ++) { ConfContent.add(in.nextLine().trim()); if (!in.hasNext()) { break; } } String outPrintText = ""; for(int i = 0; i < ConfContent.size();i ++) { String[] arr = ConfContent.get(i).split("="); if(arr[0].trim().equals("PORT") || arr[0].trim().equals("port")) { ConfContent.set(i, "port = " + port); } outPrintText += ConfContent.get(i) + "\n"; } PrintWriter out = new PrintWriter(new FileWriter(CONF_FILE_NAME, false), true); out.println(outPrintText); out.close(); return true; } catch(Exception e) { return false; } } /** * 检查端口是否可用 * @param host * @param port * @return * @throws UnknownHostException */ public static boolean isPortUsing(String host,int port) throws UnknownHostException { boolean flag = false; InetAddress theAddress = InetAddress.getByName(host); try { Socket socket = new Socket(theAddress,port); flag = true; socket.close(); } catch (IOException e) { } return flag; } }
1,876
0.517819
0.512419
62
28.870968
23.831047
91
false
false
0
0
0
0
0
0
0.612903
false
false
11
ba3eb215d77cae1c34264d2b31736666a971120c
4,509,715,673,234
a42905e51b99d8070df11c1a7b47884c8a76425c
/app/src/main/java/net/eebv/choralecentraleeebv/Views/WebViewElement.java
ac7e573ac1cb2cf88a858b26515aba2036244356
[]
no_license
Grafritz/Chant-Chorale-Et-Groupe
https://github.com/Grafritz/Chant-Chorale-Et-Groupe
20fc60fc3bb4f5b1555ca09654adc85efd7e4969
8c2d66eb16f7b62e3b87cfed8ea42da18c6b7afe
refs/heads/master
2018-02-08T20:55:17.953000
2017-06-29T17:21:08
2017-06-29T17:21:08
95,220,107
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.eebv.choralecentraleeebv.Views; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import net.eebv.choralecentraleeebv.R; import net.eebv.choralecentraleeebv.Utilities.Constant; import net.eebv.choralecentraleeebv.Utilities.Tools; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by JeanFritz on 5/8/2016. */ public class WebViewElement extends AppCompatActivity { public Context context = WebViewElement.this; private WebView webView; private ProgressDialog progressDialog; @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web_view); initControls(); } @Override protected void onPause() { super.onPause(); this.overridePendingTransition(0, 0); } private void initControls() { Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar); setSupportActionBar(toolbar); Intent intent = this.getIntent(); String title = intent.getStringExtra(Constant.titleInfo); setTitle(title); String urlAccount = intent.getStringExtra(Constant.urlApi); webView = (WebView) this.findViewById(R.id.webView); progressDialog = new ProgressDialog(this); progressDialog.setMessage(getString(R.string.connection_Wait)); progressDialog.setIndeterminate(false); progressDialog.setCancelable(false); progressDialog.show(); //webView.setWebViewClient(new MyWebClientBrowser(urlAccount)); webView.setWebChromeClient(new MyWebChromeClient(urlAccount)); new NetCheck(urlAccount).execute(); }// //region NetCheck public class NetCheck extends AsyncTask<String, String, Boolean> { private ProgressDialog nDialog; private String urlApi = ""; NetCheck(String urlApi) { this.urlApi = urlApi; } @Override protected void onPreExecute() { super.onPreExecute(); nDialog = new ProgressDialog(context); nDialog.setMessage(getString(R.string.connection_Wait)); nDialog.setIndeterminate(false); nDialog.setCancelable(false); nDialog.show(); } @Override protected Boolean doInBackground(String... params) { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) { try { URL url = new URL(Constant.url_Server_API); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setConnectTimeout(3000); urlc.connect(); if (urlc.getResponseCode() == 200) { Tools.LogCat(context, "urlApi:" + urlApi); return true; } } catch (MalformedURLException e1) { Tools.LogCat(context, "MalformedURLException:" + e1.getMessage()); //webView.loadData(getResources().getString(R.string.connection_error) + "<br />" + e1.getMessage().toString(), "text/html", null); e1.printStackTrace(); } catch (IOException ex) { Tools.LogCat(context, "IOException:" + ex.getMessage()); //webView.loadData(getResources().getString(R.string.connection_error) + "<br />" + ex.getMessage().toString(), "text/html", null); ex.printStackTrace(); } } return false; } @SuppressLint("SetJavaScriptEnabled") @Override protected void onPostExecute(Boolean th) { if (th == true) { webView.setWebViewClient(new WebViewClient()); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl(urlApi); Tools.LogCat(context, "AFTER webView.loadUrl / urlApi:" + urlApi); nDialog.dismiss(); } else { nDialog.dismiss(); webView.loadData(getResources().getString(R.string.msg_connection_error), "text/html", null); Tools.LogCat(context, getResources().getString(R.string.connection_error)); Tools.ShowAlerDialog(context, getResources().getString(R.string.connection_error_titre), getResources().getString(R.string.msg_connection_error)); } } }// //endregion private class MyWebChromeClient extends WebChromeClient { private String urlAccount; public MyWebChromeClient(String urlAccount) { this.urlAccount = urlAccount; } @Override public void onProgressChanged(WebView view, int newProgress) { Tools.LogCat(context, "INSIDE MyWebChromeClient | onProgressChanged / newProgress1:" + newProgress); if (newProgress < 100 && !progressDialog.isShowing()) { progressDialog.show(); } if (newProgress == 100) { progressDialog.dismiss(); } } }// //region MyWebClientBrowser private class MyWebClientBrowser extends WebViewClient { private String urlAccount; public MyWebClientBrowser(String urlAccount) { this.urlAccount = urlAccount; } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (Uri.parse(url).getHost().endsWith(urlAccount)) { return false; } Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); view.getContext().startActivity(intent); //view.loadUrl(url); Tools.LogCat(context, "INSIDE shouldOverrideUrlLoading / urlApi:" + url); if (!progressDialog.isShowing()) { progressDialog.show(); } return true; }// @Override public void onPageFinished(WebView view, String url) { Tools.LogCat(context, "INSIDE onPageFinished / urlApi:" + url); if (progressDialog.isShowing()) { progressDialog.dismiss(); } } }// //endregion }
UTF-8
Java
7,009
java
WebViewElement.java
Java
[ { "context": "Exception;\nimport java.net.URL;\n\n/**\n * Created by JeanFritz on 5/8/2016.\n */\npublic class WebViewElement exte", "end": 833, "score": 0.9938198924064636, "start": 824, "tag": "NAME", "value": "JeanFritz" } ]
null
[]
package net.eebv.choralecentraleeebv.Views; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.webkit.WebViewClient; import net.eebv.choralecentraleeebv.R; import net.eebv.choralecentraleeebv.Utilities.Constant; import net.eebv.choralecentraleeebv.Utilities.Tools; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by JeanFritz on 5/8/2016. */ public class WebViewElement extends AppCompatActivity { public Context context = WebViewElement.this; private WebView webView; private ProgressDialog progressDialog; @SuppressLint("SetJavaScriptEnabled") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_web_view); initControls(); } @Override protected void onPause() { super.onPause(); this.overridePendingTransition(0, 0); } private void initControls() { Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar); setSupportActionBar(toolbar); Intent intent = this.getIntent(); String title = intent.getStringExtra(Constant.titleInfo); setTitle(title); String urlAccount = intent.getStringExtra(Constant.urlApi); webView = (WebView) this.findViewById(R.id.webView); progressDialog = new ProgressDialog(this); progressDialog.setMessage(getString(R.string.connection_Wait)); progressDialog.setIndeterminate(false); progressDialog.setCancelable(false); progressDialog.show(); //webView.setWebViewClient(new MyWebClientBrowser(urlAccount)); webView.setWebChromeClient(new MyWebChromeClient(urlAccount)); new NetCheck(urlAccount).execute(); }// //region NetCheck public class NetCheck extends AsyncTask<String, String, Boolean> { private ProgressDialog nDialog; private String urlApi = ""; NetCheck(String urlApi) { this.urlApi = urlApi; } @Override protected void onPreExecute() { super.onPreExecute(); nDialog = new ProgressDialog(context); nDialog.setMessage(getString(R.string.connection_Wait)); nDialog.setIndeterminate(false); nDialog.setCancelable(false); nDialog.show(); } @Override protected Boolean doInBackground(String... params) { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnected()) { try { URL url = new URL(Constant.url_Server_API); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setConnectTimeout(3000); urlc.connect(); if (urlc.getResponseCode() == 200) { Tools.LogCat(context, "urlApi:" + urlApi); return true; } } catch (MalformedURLException e1) { Tools.LogCat(context, "MalformedURLException:" + e1.getMessage()); //webView.loadData(getResources().getString(R.string.connection_error) + "<br />" + e1.getMessage().toString(), "text/html", null); e1.printStackTrace(); } catch (IOException ex) { Tools.LogCat(context, "IOException:" + ex.getMessage()); //webView.loadData(getResources().getString(R.string.connection_error) + "<br />" + ex.getMessage().toString(), "text/html", null); ex.printStackTrace(); } } return false; } @SuppressLint("SetJavaScriptEnabled") @Override protected void onPostExecute(Boolean th) { if (th == true) { webView.setWebViewClient(new WebViewClient()); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl(urlApi); Tools.LogCat(context, "AFTER webView.loadUrl / urlApi:" + urlApi); nDialog.dismiss(); } else { nDialog.dismiss(); webView.loadData(getResources().getString(R.string.msg_connection_error), "text/html", null); Tools.LogCat(context, getResources().getString(R.string.connection_error)); Tools.ShowAlerDialog(context, getResources().getString(R.string.connection_error_titre), getResources().getString(R.string.msg_connection_error)); } } }// //endregion private class MyWebChromeClient extends WebChromeClient { private String urlAccount; public MyWebChromeClient(String urlAccount) { this.urlAccount = urlAccount; } @Override public void onProgressChanged(WebView view, int newProgress) { Tools.LogCat(context, "INSIDE MyWebChromeClient | onProgressChanged / newProgress1:" + newProgress); if (newProgress < 100 && !progressDialog.isShowing()) { progressDialog.show(); } if (newProgress == 100) { progressDialog.dismiss(); } } }// //region MyWebClientBrowser private class MyWebClientBrowser extends WebViewClient { private String urlAccount; public MyWebClientBrowser(String urlAccount) { this.urlAccount = urlAccount; } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (Uri.parse(url).getHost().endsWith(urlAccount)) { return false; } Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); view.getContext().startActivity(intent); //view.loadUrl(url); Tools.LogCat(context, "INSIDE shouldOverrideUrlLoading / urlApi:" + url); if (!progressDialog.isShowing()) { progressDialog.show(); } return true; }// @Override public void onPageFinished(WebView view, String url) { Tools.LogCat(context, "INSIDE onPageFinished / urlApi:" + url); if (progressDialog.isShowing()) { progressDialog.dismiss(); } } }// //endregion }
7,009
0.614068
0.610073
191
35.696335
27.833309
151
false
false
0
0
0
0
0
0
0.617801
false
false
11
5e990c4266d5200ff31ad3b8a9d8313d63285653
22,806,276,388,364
f27f645f24ad5837982dc20b426bddc1f68ae8d0
/src/ro/cuzma/picturemgt/ui/PicturePanel.java
a20a24744740f0fa63b0bbcaa8e464fa44633c3c
[]
no_license
lolcutus/picturemgt
https://github.com/lolcutus/picturemgt
6771f1b97583d89f8d90dc5e8fda24e458d62649
eb326c24f444f84099686c49a29c6c0fb197e9ba
refs/heads/master
2020-05-17T11:11:56.734000
2013-06-25T11:39:42
2013-06-25T11:39:42
32,133,210
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Created on 22.06.2005 * by Laurian Cuzma */ package ro.cuzma.picturemgt.ui; import java.awt.GridLayout; import java.util.Vector; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.WindowConstants; import ro.cuzma.picturemgt.PictureTableModel; import ro.cuzma.tools.FileTools; //import java.awt.Dimension; /** * @author Laurian Cuzma * * 22.06.2005 */ public class PicturePanel extends JPanel { JTable table = null; public static void main(String[] args) { JFrame frame = new JFrame(); frame.getContentPane().add( new PicturePanel(FileTools.getFilesInDir("F:\\Multimedia\\Picture\\2005\\2005.04-02 La Nasa","jpg"))); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); frame.pack(); frame.show(); } public PicturePanel(Vector files) { super(new GridLayout(1, 0)); table = new JTable(new PictureTableModel(files)); //table.getColumnModel().getColumn(1).setPreferredWidth(1000); //table.setPreferredScrollableViewportSize(new Dimension(500, 70)); //Create the scroll pane and add the table to it. JScrollPane scrollPane = new JScrollPane(table); //Add the scroll pane to this panel. add(scrollPane); } public JTable getTable(){ return table; } private static void createAndShowGUI() { //Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true); //Create and set up the window. JFrame frame = new JFrame("DirsTable"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Display the window. frame.pack(); frame.setVisible(true); } }
UTF-8
Java
1,712
java
PicturePanel.java
Java
[ { "context": "/*\r\n * Created on 22.06.2005\r\n * by Laurian Cuzma\r\n */\r\npackage ro.cuzma.picturemgt.ui;\r\n\r\nimport j", "end": 49, "score": 0.9998809695243835, "start": 36, "tag": "NAME", "value": "Laurian Cuzma" }, { "context": "\n//import java.awt.Dimension;\r\n\r\n\r\n/**\r\n * @author Laurian Cuzma\r\n *\r\n * 22.06.2005\r\n */\r\npublic class PicturePane", "end": 454, "score": 0.9998820424079895, "start": 441, "tag": "NAME", "value": "Laurian Cuzma" } ]
null
[]
/* * Created on 22.06.2005 * by <NAME> */ package ro.cuzma.picturemgt.ui; import java.awt.GridLayout; import java.util.Vector; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.WindowConstants; import ro.cuzma.picturemgt.PictureTableModel; import ro.cuzma.tools.FileTools; //import java.awt.Dimension; /** * @author <NAME> * * 22.06.2005 */ public class PicturePanel extends JPanel { JTable table = null; public static void main(String[] args) { JFrame frame = new JFrame(); frame.getContentPane().add( new PicturePanel(FileTools.getFilesInDir("F:\\Multimedia\\Picture\\2005\\2005.04-02 La Nasa","jpg"))); frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); frame.pack(); frame.show(); } public PicturePanel(Vector files) { super(new GridLayout(1, 0)); table = new JTable(new PictureTableModel(files)); //table.getColumnModel().getColumn(1).setPreferredWidth(1000); //table.setPreferredScrollableViewportSize(new Dimension(500, 70)); //Create the scroll pane and add the table to it. JScrollPane scrollPane = new JScrollPane(table); //Add the scroll pane to this panel. add(scrollPane); } public JTable getTable(){ return table; } private static void createAndShowGUI() { //Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true); //Create and set up the window. JFrame frame = new JFrame("DirsTable"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Display the window. frame.pack(); frame.setVisible(true); } }
1,698
0.704439
0.681075
70
22.457144
21.730614
106
false
false
0
0
0
0
0
0
1.271429
false
false
11
fe9ba74f412d4bb4ea19cbff9837c5fb69eb67a9
2,327,872,317,435
5bfdbbe0cab492284a9afb8c7ce8b67ab726b2cf
/ShaoLearn/tmoonlight-common/src/main/java/com/cyyz/spt/platform/common/exception/ParamError.java
cfd7c91b190f4f499e8fadb0524bfeb668be1503
[]
no_license
tmoonlight/Learning-7DAY
https://github.com/tmoonlight/Learning-7DAY
86042ef2a1879bf6012ad648fd43d694395b8677
5314a2b7333581f2948c855359605c78877818a3
refs/heads/master
2022-12-24T15:34:33.939000
2019-10-16T02:27:28
2019-10-16T02:27:28
150,082,554
0
0
null
false
2022-12-16T10:41:28
2018-09-24T09:50:54
2019-10-16T02:27:31
2022-12-16T10:41:24
9,266
0
0
16
Java
false
false
package com.cyyz.spt.platform.common.exception; /** * Created by hwd on 2017/6/14. */ public class ParamError { private String field; private String msg; public String getField() { return field; } public void setField(String field) { this.field = field; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
UTF-8
Java
427
java
ParamError.java
Java
[ { "context": ".spt.platform.common.exception;\n\n/**\n * Created by hwd on 2017/6/14.\n */\npublic class ParamError {\n p", "end": 70, "score": 0.9994851350784302, "start": 67, "tag": "USERNAME", "value": "hwd" } ]
null
[]
package com.cyyz.spt.platform.common.exception; /** * Created by hwd on 2017/6/14. */ public class ParamError { private String field; private String msg; public String getField() { return field; } public void setField(String field) { this.field = field; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
427
0.590164
0.57377
25
16.08
14.482873
47
false
false
0
0
0
0
0
0
0.28
false
false
11
3bec6cb105397aa6fdc93146ea4910ae3c01c389
11,347,303,650,020
3cba9f1474c67801f1e5673e9e52cbc77ad14adf
/src/view/swing/package-info.java
e9164da8de832a4139da0e1354c8df27ef93c889
[]
no_license
1Israazul/visualgorithm
https://github.com/1Israazul/visualgorithm
993236d0c81b5379048ed12a4b6b7df185fe0a93
9a14ffcfbc28eef6eb22e0b0d566165e1a22af07
refs/heads/master
2021-05-29T23:19:58.882000
2014-03-23T18:22:16
2014-03-23T18:22:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * package-info.java v0.10 27/02/09 * * Visualgorithm * Copyright (C) Hannier, Pironin, Rigoni (visualgo@googlegroups.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /** * This package contains the view of the software. It is composed by different * data structure views that are open in the software. Each of these data * structure views takes part of a tabbed pane. A view must implement the * interface <tt>IView</tt> directly or through a more specific interface. Thus * a new data structure view must take part of the software view at the name of * the data structure and implement <tt>IDataStructureView</tt> or a more * specific interface. * * @author Julien Hannier * @version 0.10 27/02/09 */ package view.swing;
UTF-8
Java
1,421
java
package-info.java
Java
[ { "context": "0.10 27/02/09\n *\n * Visualgorithm\n * Copyright (C) Hannier, Pironin, Rigoni (visualgo@googlegroups.com)\n * \n * This program i", "end": 100, "score": 0.9989791512489319, "start": 76, "tag": "NAME", "value": "Hannier, Pironin, Rigoni" }, { "context": "orithm\n * Copyright (C) Hannier, Pironin, Rigoni (visualgo@googlegroups.com)\n * \n * This program is free software; you can re", "end": 127, "score": 0.9999264478683472, "start": 102, "tag": "EMAIL", "value": "visualgo@googlegroups.com" }, { "context": "t> or a more\n * specific interface.\n * \n * @author Julien Hannier\n * @version 0.10 27/02/09\n */\npackage view.swing;", "end": 1370, "score": 0.9998584985733032, "start": 1356, "tag": "NAME", "value": "Julien Hannier" } ]
null
[]
/* * package-info.java v0.10 27/02/09 * * Visualgorithm * Copyright (C) <NAME> (<EMAIL>) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /** * This package contains the view of the software. It is composed by different * data structure views that are open in the software. Each of these data * structure views takes part of a tabbed pane. A view must implement the * interface <tt>IView</tt> directly or through a more specific interface. Thus * a new data structure view must take part of the software view at the name of * the data structure and implement <tt>IDataStructureView</tt> or a more * specific interface. * * @author <NAME> * @version 0.10 27/02/09 */ package view.swing;
1,377
0.740324
0.717101
34
40.794117
30.243891
79
false
false
0
0
0
0
0
0
0.441176
false
false
11
223ce3beb6ab74de190da36dddf71bfc135613d2
33,947,421,517,498
49c75c07311a7406e99f964738714a13d2337239
/src/main/java/ua/com/as/util/adapters/ResponseTypeAdapter.java
f0c3c5bf5e585e71c4e0b892e2dc54bd4131897b
[]
no_license
deneesr/Practice2REST4_2_0_0
https://github.com/deneesr/Practice2REST4_2_0_0
50991eb6ad7fba98328db67cc7b4cf29c268529c
60ee3d4ea7be80def3c67b3324fc16f08bc10090
refs/heads/master
2021-01-11T14:34:03.906000
2017-01-26T22:19:57
2017-01-26T22:19:57
80,159,551
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ua.com.as.util.adapters; import ua.com.as.util.enums.ResponseType; import ua.com.as.util.exception.ConfigurationException; import javax.xml.bind.annotation.adapters.XmlAdapter; /** * <p>Converter type from <code>String</code> to <code>ResponseType</code>. */ public class ResponseTypeAdapter extends XmlAdapter<String, ResponseType> { /** * Converts a value type to a bound type. * * @param v The value to be converted. Can be null. * @return instance of class. * @throws Exception if there's an error during the conversion. */ @Override public ResponseType unmarshal(String v) throws Exception { switch (v) { case "JSON": return ResponseType.JSON; case "XML": return ResponseType.XML; case "String": return ResponseType.STRING; default: throw new ConfigurationException("Please select response type: JSON or XML or STRING"); } } @Override public String marshal(ResponseType v) throws Exception { return null; } }
UTF-8
Java
1,126
java
ResponseTypeAdapter.java
Java
[]
null
[]
package ua.com.as.util.adapters; import ua.com.as.util.enums.ResponseType; import ua.com.as.util.exception.ConfigurationException; import javax.xml.bind.annotation.adapters.XmlAdapter; /** * <p>Converter type from <code>String</code> to <code>ResponseType</code>. */ public class ResponseTypeAdapter extends XmlAdapter<String, ResponseType> { /** * Converts a value type to a bound type. * * @param v The value to be converted. Can be null. * @return instance of class. * @throws Exception if there's an error during the conversion. */ @Override public ResponseType unmarshal(String v) throws Exception { switch (v) { case "JSON": return ResponseType.JSON; case "XML": return ResponseType.XML; case "String": return ResponseType.STRING; default: throw new ConfigurationException("Please select response type: JSON or XML or STRING"); } } @Override public String marshal(ResponseType v) throws Exception { return null; } }
1,126
0.628774
0.628774
41
26.463415
26.36063
103
false
false
0
0
0
0
0
0
0.243902
false
false
11
fe2df2ee4754abe3afa7a02ab0faa38e28b000f3
36,344,013,259,235
748071b95751fbb8c5dfc03ded4d346d8a5410db
/src/app/home/service/UserService.java
c8795ed269c623852caa3ae44400efc4c5fbeecd
[]
no_license
litete/deepsearch
https://github.com/litete/deepsearch
0f00783c6957ff7a226a74233c8570bbbcbfd0c6
d81958f95eff522f3fe385006641a09365271a7e
refs/heads/master
2020-06-23T10:06:57.215000
2017-01-03T15:49:39
2017-01-03T15:49:39
74,645,004
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package app.home.service; import java.util.List; import app.home.model.Log; import app.home.model.User; public interface UserService { String selectUserHaveVector(int userid); User find(String uid); Integer save(User info); int remove(int uid); //查询有没有看过这篇文章 List ifLoged(int userid,int arctileid); //添加到log中去 int insertLoged(Log log); //插入cookid并返回自增主键 int insertResultId(User user); }
UTF-8
Java
459
java
UserService.java
Java
[]
null
[]
package app.home.service; import java.util.List; import app.home.model.Log; import app.home.model.User; public interface UserService { String selectUserHaveVector(int userid); User find(String uid); Integer save(User info); int remove(int uid); //查询有没有看过这篇文章 List ifLoged(int userid,int arctileid); //添加到log中去 int insertLoged(Log log); //插入cookid并返回自增主键 int insertResultId(User user); }
459
0.745721
0.745721
25
15.36
13.67298
41
false
false
0
0
0
0
0
0
1
false
false
11
d7f4f1624efe07efe8be654533f8b334974f9f54
23,931,557,844,290
351b65aa36a8c0f1d08ce09c35872560a072bb5f
/src/testing/NoSoundTest.java
0e8931a3a148d0d1ebcc282009c8c9c425f1b9c4
[]
no_license
LeeSynkowski/TinySynth
https://github.com/LeeSynkowski/TinySynth
5dc1593c35dccae2e25bcf0249432a9b9dddf883
48437f07c8fe69045f37c09969469008060852b6
refs/heads/master
2020-12-25T04:54:28.170000
2013-01-17T10:06:11
2013-01-17T10:06:11
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package testing; import synth.SimpleTrack; //import synth.SingleInstrumentBox; import synth.SoundSource; import tinyEdge.CloneableSourceFactory; import tinyEdge.SoundSourceFactory; //import synth.StdNote; //import synth.WaveInstrument; public class NoSoundTest { public static void main(String[] args) { //SoundSource s = new SingleInstrumentBox(new WaveInstrument(), new StdNote("a4"), 2); SoundSource s = new SimpleTrack(2); SoundSourceFactory fac = new CloneableSourceFactory(s); s = fac.getSoundSourceInstance(); try { s = fac.getSoundSourceInstance("c4"); } catch (Exception e) { System.out.println("Expected exception caught"); e.printStackTrace(); } System.out.println(s.toString()); } }
UTF-8
Java
725
java
NoSoundTest.java
Java
[]
null
[]
package testing; import synth.SimpleTrack; //import synth.SingleInstrumentBox; import synth.SoundSource; import tinyEdge.CloneableSourceFactory; import tinyEdge.SoundSourceFactory; //import synth.StdNote; //import synth.WaveInstrument; public class NoSoundTest { public static void main(String[] args) { //SoundSource s = new SingleInstrumentBox(new WaveInstrument(), new StdNote("a4"), 2); SoundSource s = new SimpleTrack(2); SoundSourceFactory fac = new CloneableSourceFactory(s); s = fac.getSoundSourceInstance(); try { s = fac.getSoundSourceInstance("c4"); } catch (Exception e) { System.out.println("Expected exception caught"); e.printStackTrace(); } System.out.println(s.toString()); } }
725
0.746207
0.74069
26
26.884615
20.287031
88
false
false
0
0
0
0
0
0
1.730769
false
false
11
ed37c0e00d11c4149f77570e10c9e23556027889
10,411,000,758,192
6948fae88b0b4069c2ae80643b074f4fa59ec86d
/Atcrowdfunding_manager_api/src/main/java/com/atguigu/atcrowdfunding/manager/service/CertTypeService.java
b774c20a622fcde12afc9401a6b0716d0352a32f
[]
no_license
15979638471/acrowdfunding
https://github.com/15979638471/acrowdfunding
c8e4087fb96614f73a34a78640f589d82f9582cf
b85a7af6f8cc685fa267b4761eb247ae60afb731
refs/heads/master
2021-06-26T16:10:14.375000
2019-12-07T05:49:36
2019-12-07T05:49:38
226,449,674
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.atguigu.atcrowdfunding.manager.service; import com.atguigu.atcrowdfunding.bean.AccountTypeCert; import java.util.List; import java.util.Map; public interface CertTypeService { List<Map<String,Object>> queryCertAccttype(); int insertCertAccttype(AccountTypeCert record); int deleteCertAccttype(AccountTypeCert record); }
UTF-8
Java
350
java
CertTypeService.java
Java
[]
null
[]
package com.atguigu.atcrowdfunding.manager.service; import com.atguigu.atcrowdfunding.bean.AccountTypeCert; import java.util.List; import java.util.Map; public interface CertTypeService { List<Map<String,Object>> queryCertAccttype(); int insertCertAccttype(AccountTypeCert record); int deleteCertAccttype(AccountTypeCert record); }
350
0.797143
0.797143
15
22.333334
22.846346
55
false
false
0
0
0
0
0
0
0.533333
false
false
11
de57ccf672e866d2c7b310228131a1e5c3aecd4c
31,078,383,377,054
86e3fbfb36e6dff651316af89b6f273d77035e06
/taktin-server/src/main/java/com/sunny/taktin/controller/ProjectResource.java
a79f1f5804c4a50757390d79b0ff3150600e78dd
[]
no_license
SunnnyChan/taktin
https://github.com/SunnnyChan/taktin
23a3d07faf88ea08ed2284102ef144ec199a6ab4
43788d62fac3f9cb10f53354cfac716f5e533f5b
refs/heads/master
2021-06-28T11:56:08.235000
2020-06-08T07:57:40
2020-06-08T07:57:40
150,532,509
1
0
null
false
2020-10-13T12:13:23
2018-09-27T05:19:48
2020-06-08T07:57:49
2020-10-13T12:13:21
79
0
0
1
Lua
false
false
package com.sunny.taktin.controller; /* * Created by sunnnychan@gmail.com on 2019/3/5. */ public class ProjectResource { }
UTF-8
Java
128
java
ProjectResource.java
Java
[ { "context": "age com.sunny.taktin.controller;\n\n/*\n * Created by sunnnychan@gmail.com on 2019/3/5.\n */\n\npublic class ProjectResource {\n", "end": 75, "score": 0.9999109506607056, "start": 55, "tag": "EMAIL", "value": "sunnnychan@gmail.com" } ]
null
[]
package com.sunny.taktin.controller; /* * Created by <EMAIL> on 2019/3/5. */ public class ProjectResource { }
115
0.71875
0.671875
9
13.222222
17.78125
47
false
false
0
0
0
0
0
0
0.111111
false
false
11
591d38d29de946c6fb0c08da246814547da365d0
12,876,311,983,274
9b6214a6a8edca73946f76b76db5ad890d5cbe83
/daily-db/src/main/java/com/zjrb/daily/db/dao/CityDaoHelper.java
0ae321818e235fb1f30d640ca2f44963126c2e33
[]
no_license
reboat/DbProject
https://github.com/reboat/DbProject
6210088b3517a10eaeeb9ea214ab243077a58d30
ca2a6a19fd90fe9c53ffd61975a2019ad498e449
refs/heads/master
2020-12-13T01:58:14.093000
2019-09-24T07:37:12
2019-09-24T07:37:12
234,282,009
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zjrb.daily.db.dao; import com.zjrb.daily.db.BaseDaoHelper; import com.zjrb.daily.db.DatabaseLoader; import com.zjrb.daily.db.bean.CityBean; /** * CityDaoHelper * * @author a_liYa * @date 2017/8/31 20:27. */ public class CityDaoHelper extends BaseDaoHelper<CityBean, Long> { public CityDaoHelper() { super(DatabaseLoader.getDaoSession().getCityBeanDao()); } }
UTF-8
Java
396
java
CityDaoHelper.java
Java
[ { "context": "bean.CityBean;\n\n/**\n * CityDaoHelper\n *\n * @author a_liYa\n * @date 2017/8/31 20:27.\n */\npublic class CityDa", "end": 195, "score": 0.9995440244674683, "start": 189, "tag": "USERNAME", "value": "a_liYa" } ]
null
[]
package com.zjrb.daily.db.dao; import com.zjrb.daily.db.BaseDaoHelper; import com.zjrb.daily.db.DatabaseLoader; import com.zjrb.daily.db.bean.CityBean; /** * CityDaoHelper * * @author a_liYa * @date 2017/8/31 20:27. */ public class CityDaoHelper extends BaseDaoHelper<CityBean, Long> { public CityDaoHelper() { super(DatabaseLoader.getDaoSession().getCityBeanDao()); } }
396
0.714646
0.686869
19
19.842106
21.011934
66
false
false
0
0
0
0
0
0
0.315789
false
false
11
8d4d4664f9b853a638a3ef980ba415ceabaec779
6,382,321,403,940
0b7bcbe3665ec25e53c6575cc8b9f1c9a4e4cb7c
/aws-sagemaker-imageversion/src/main/java/software/amazon/sagemaker/imageversion/Translator.java
f7fd6dc8aff9f7c3ed82b634f70a6e7445e20f2c
[ "Apache-2.0" ]
permissive
sourabhreddy/aws-cloudformation-resource-providers-sagemaker
https://github.com/sourabhreddy/aws-cloudformation-resource-providers-sagemaker
80905a54d4d59a52bc857b85179d94efbacf5cd4
4b05df45ada7e872525bb485387bbebbd0ce0869
refs/heads/main
2023-03-19T01:03:04.802000
2021-03-12T22:34:50
2021-03-12T22:34:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package software.amazon.sagemaker.imageversion; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; import software.amazon.awssdk.services.sagemaker.model.CreateImageVersionRequest; import software.amazon.awssdk.services.sagemaker.model.DeleteImageVersionRequest; import software.amazon.awssdk.services.sagemaker.model.DescribeImageVersionRequest; import software.amazon.awssdk.services.sagemaker.model.DescribeImageVersionResponse; import software.amazon.awssdk.services.sagemaker.model.ListImageVersionsRequest; import software.amazon.awssdk.services.sagemaker.model.ListImageVersionsResponse; /** * This class is a centralized placeholder for the following. * - api request construction * - object translation to/from aws sdk * - resource model construction for read/list handlers */ public class Translator { /** * Format a request to create an image version resource from the input CFN resource model. * @param model resource model passed into CFN handler * @return createImageVersionRequest the aws service request to create an image version resource */ static CreateImageVersionRequest translateToCreateRequest(final ResourceModel model, final String clientToken) { return CreateImageVersionRequest.builder() .imageName(model.getImageName()) .baseImage(model.getBaseImage()) .clientToken(clientToken) .build(); } /** * Format a request to read an image version resource from the input CFN resource model. * @param model resource model passed into CFN handler * @return describeImageVersionRequest the aws service request to read an image version resource */ static DescribeImageVersionRequest translateToReadRequest(final ResourceModel model) { return DescribeImageVersionRequest.builder() .imageName(getImageNameFromVersionArn(model.getImageVersionArn())) .version(getImageVersionNumberFromVersionArn(model.getImageVersionArn())) .build(); } /** * Format a request to delete an image version resource from the input CFN resource model. * @param model resource model passed into CFN handler * @return deleteImageVersionRequest the aws service request to delete an image version resource */ static DeleteImageVersionRequest translateToDeleteRequest(final ResourceModel model) { return DeleteImageVersionRequest.builder() .imageName(getImageNameFromVersionArn(model.getImageVersionArn())) .version(getImageVersionNumberFromVersionArn(model.getImageVersionArn())) .build(); } /** * Format a request to list all image version resources for an account. * @param model resource model passed into CFN handler * @param nextToken token passed to the aws service list resources request * @return listImageVersionsRequest the aws service request to list image version resources for an account */ static ListImageVersionsRequest translateToListRequest(final ResourceModel model, final String nextToken) { return ListImageVersionsRequest.builder() .imageName(getImageNameFromVersionArn(model.getImageVersionArn())) .nextToken(nextToken) .build(); } /** * Translates a list of ImageVersion resources from a list image version response into a list of CFN resource models. * @param listImageVersionsResponse the response from a list image version request * @return resourceModels list of CloudFormation resource models representing the list of image versions */ static List<ResourceModel> translateFromListResponse(final ListImageVersionsResponse listImageVersionsResponse) { return streamOfOrEmpty(listImageVersionsResponse.imageVersions()) .map(image -> ResourceModel.builder() .imageVersionArn(image.imageVersionArn()) .build()) .collect(Collectors.toList()); } static <T> Stream<T> streamOfOrEmpty(final Collection<T> collection) { return Optional.ofNullable(collection) .map(Collection::stream) .orElseGet(Stream::empty); } /** * Translates image version resource from the service into a CloudFormation resource model. * @param describeImageVersionResponse the response from a an image version read request * @return resourceModel CloudFormation resource model representation of the image version */ static ResourceModel translateFromReadResponse(final DescribeImageVersionResponse describeImageVersionResponse) { return ResourceModel.builder() .imageName(getImageNameFromVersionArn(describeImageVersionResponse.imageVersionArn())) .imageArn(describeImageVersionResponse.imageArn()) .imageVersionArn(describeImageVersionResponse.imageVersionArn()) .version(describeImageVersionResponse.version()) .baseImage(describeImageVersionResponse.baseImage()) .containerImage(describeImageVersionResponse.containerImage()) .build(); } private static String getImageNameFromVersionArn(final String imageVersionArn) { final String[] arnParts = StringUtils.split(imageVersionArn, '/'); return arnParts[arnParts.length - 2]; } private static Integer getImageVersionNumberFromVersionArn(final String imageVersionArn) { final String[] arnParts = StringUtils.split(imageVersionArn, '/'); return Integer.parseInt(arnParts[arnParts.length - 1]); } }
UTF-8
Java
5,724
java
Translator.java
Java
[]
null
[]
package software.amazon.sagemaker.imageversion; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang3.StringUtils; import software.amazon.awssdk.services.sagemaker.model.CreateImageVersionRequest; import software.amazon.awssdk.services.sagemaker.model.DeleteImageVersionRequest; import software.amazon.awssdk.services.sagemaker.model.DescribeImageVersionRequest; import software.amazon.awssdk.services.sagemaker.model.DescribeImageVersionResponse; import software.amazon.awssdk.services.sagemaker.model.ListImageVersionsRequest; import software.amazon.awssdk.services.sagemaker.model.ListImageVersionsResponse; /** * This class is a centralized placeholder for the following. * - api request construction * - object translation to/from aws sdk * - resource model construction for read/list handlers */ public class Translator { /** * Format a request to create an image version resource from the input CFN resource model. * @param model resource model passed into CFN handler * @return createImageVersionRequest the aws service request to create an image version resource */ static CreateImageVersionRequest translateToCreateRequest(final ResourceModel model, final String clientToken) { return CreateImageVersionRequest.builder() .imageName(model.getImageName()) .baseImage(model.getBaseImage()) .clientToken(clientToken) .build(); } /** * Format a request to read an image version resource from the input CFN resource model. * @param model resource model passed into CFN handler * @return describeImageVersionRequest the aws service request to read an image version resource */ static DescribeImageVersionRequest translateToReadRequest(final ResourceModel model) { return DescribeImageVersionRequest.builder() .imageName(getImageNameFromVersionArn(model.getImageVersionArn())) .version(getImageVersionNumberFromVersionArn(model.getImageVersionArn())) .build(); } /** * Format a request to delete an image version resource from the input CFN resource model. * @param model resource model passed into CFN handler * @return deleteImageVersionRequest the aws service request to delete an image version resource */ static DeleteImageVersionRequest translateToDeleteRequest(final ResourceModel model) { return DeleteImageVersionRequest.builder() .imageName(getImageNameFromVersionArn(model.getImageVersionArn())) .version(getImageVersionNumberFromVersionArn(model.getImageVersionArn())) .build(); } /** * Format a request to list all image version resources for an account. * @param model resource model passed into CFN handler * @param nextToken token passed to the aws service list resources request * @return listImageVersionsRequest the aws service request to list image version resources for an account */ static ListImageVersionsRequest translateToListRequest(final ResourceModel model, final String nextToken) { return ListImageVersionsRequest.builder() .imageName(getImageNameFromVersionArn(model.getImageVersionArn())) .nextToken(nextToken) .build(); } /** * Translates a list of ImageVersion resources from a list image version response into a list of CFN resource models. * @param listImageVersionsResponse the response from a list image version request * @return resourceModels list of CloudFormation resource models representing the list of image versions */ static List<ResourceModel> translateFromListResponse(final ListImageVersionsResponse listImageVersionsResponse) { return streamOfOrEmpty(listImageVersionsResponse.imageVersions()) .map(image -> ResourceModel.builder() .imageVersionArn(image.imageVersionArn()) .build()) .collect(Collectors.toList()); } static <T> Stream<T> streamOfOrEmpty(final Collection<T> collection) { return Optional.ofNullable(collection) .map(Collection::stream) .orElseGet(Stream::empty); } /** * Translates image version resource from the service into a CloudFormation resource model. * @param describeImageVersionResponse the response from a an image version read request * @return resourceModel CloudFormation resource model representation of the image version */ static ResourceModel translateFromReadResponse(final DescribeImageVersionResponse describeImageVersionResponse) { return ResourceModel.builder() .imageName(getImageNameFromVersionArn(describeImageVersionResponse.imageVersionArn())) .imageArn(describeImageVersionResponse.imageArn()) .imageVersionArn(describeImageVersionResponse.imageVersionArn()) .version(describeImageVersionResponse.version()) .baseImage(describeImageVersionResponse.baseImage()) .containerImage(describeImageVersionResponse.containerImage()) .build(); } private static String getImageNameFromVersionArn(final String imageVersionArn) { final String[] arnParts = StringUtils.split(imageVersionArn, '/'); return arnParts[arnParts.length - 2]; } private static Integer getImageVersionNumberFromVersionArn(final String imageVersionArn) { final String[] arnParts = StringUtils.split(imageVersionArn, '/'); return Integer.parseInt(arnParts[arnParts.length - 1]); } }
5,724
0.734801
0.734277
119
47.100842
36.703075
121
false
false
0
0
0
0
0
0
0.235294
false
false
11
be2a850dc654293e6081c43c0c5313cbf0a35265
22,969,485,152,476
07f038f2456cd985555f4a486004f3e434ad73e2
/src/main/java/com/sinobridge/eoss/business/projectmanage/controller/BasePartnerInfoController.java
6dc447c499a18fa18b6b232e5261f4a606552505
[]
no_license
JishengYuan/sino-bridge-bussiness
https://github.com/JishengYuan/sino-bridge-bussiness
6979c6163b8f7b76fac0fd7648d7a9ea8f373655
058b757a0ea832b1613b052fc7b34e9cffc36755
refs/heads/master
2020-12-11T09:03:00.967000
2016-06-01T02:02:56
2016-06-01T02:02:56
58,023,686
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * FileName: BasePartnerInfoController.java * 北京神州新桥科技有限公司 * Copyright 2013-2014 (C) Sino-Bridge Software CO., LTD. All Rights Reserved. */ package com.sinobridge.eoss.business.projectmanage.controller; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.sinobridge.base.core.controller.DefaultBaseController; import com.sinobridge.base.core.utils.PaginationSupport; import com.sinobridge.eoss.business.projectmanage.dto.PartnerinfoTree; import com.sinobridge.eoss.business.projectmanage.model.BasePartnerInfo; import com.sinobridge.eoss.business.projectmanage.model.BasePartnerProduct; import com.sinobridge.eoss.business.projectmanage.model.BaseProductType; import com.sinobridge.eoss.business.projectmanage.service.BasePartnerInfoService; import com.sinobridge.eoss.business.projectmanage.service.BasePartnerProductService; import com.sinobridge.eoss.business.projectmanage.service.BaseProductTypeService; import com.sinobridge.eoss.business.projectmanage.utils.PartnerUtils; import com.sinobridge.systemmanage.controller.bean.RoleForm; import com.sinobridge.systemmanage.model.SysDomainValue; import com.sinobridge.systemmanage.model.SysPowerAction; import com.sinobridge.systemmanage.util.Global; import com.sinobridge.systemmanage.util.StringUtil; import com.sinobridge.systemmanage.util.UUIDUtil; import com.sinobridge.systemmanage.vo.SystemUser; /** * <code>BasePartnerInfoController</code> * * @version 1.0 * @author guokemenng * @since 1.0 2013-11-26 */ @Controller @RequestMapping(value = "/business/projectm/partnerInfo") public class BasePartnerInfoController extends DefaultBaseController<BasePartnerInfo, BasePartnerInfoService> { @Autowired private BaseProductTypeService productTypeService; @Autowired protected BasePartnerProductService partnerProductService; /** * <code>partnerManager</code> * 主页面 * @param request * @param response * @return * @since 2013-11-13 guokemenng */ @RequestMapping(value = "/partnerInfo_main") public ModelAndView getPartnerInfo(HttpServletRequest request, HttpServletResponse response) { ModelAndView mav = new ModelAndView("business/projectm/partnerInfo_main"); SystemUser systemUser = (SystemUser) request.getSession().getAttribute(Global.LOGIN_USER); List<SysPowerAction> actions = systemUser.getSysPowerActions(); StringBuffer buffers = new StringBuffer(); for (SysPowerAction sysPowerAction : actions) { buffers.append(sysPowerAction.getPowCode()); buffers.append(","); } mav.addObject("powerActions", buffers.toString()); return mav; } /** * <code>getList</code> * 获取列表 * @return * @since 2013-11-13 guokemenng */ @ResponseBody @RequestMapping(value = "/getList") public Map<String, Object> getList(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> map = new HashMap<String, Object>(); String page = request.getParameter("page"); String rows = request.getParameter("rows"); if (page != null) { this.pageNo = Integer.parseInt(page); } if (rows != null) { this.pageSize = Integer.parseInt(rows); } DetachedCriteria detachedCriteria = DetachedCriteria.forClass(this.model.getClass()); buildSearch(request, detachedCriteria); PaginationSupport paginationSupport = getService().findPageByCriteria(detachedCriteria, this.pageNo, this.pageSize); map.put("total", paginationSupport.getTotalCount()); map.put("rows", paginationSupport.getItems()); return map; } /** * <code>getList</code> * 得到所有厂商格式{["id":XX,"name":XX]} * @return * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException * @since 2013-11-13 guokemenng */ @ResponseBody @RequestMapping(value = "/getAll") public Map<String, List<PartnerinfoTree>> getAll(HttpServletRequest request, HttpServletResponse response, @RequestParam("productTypeId") String productTypeId) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { DetachedCriteria detachedCriteria = DetachedCriteria.forClass(this.model.getClass()); Short s = 1; detachedCriteria.add(Restrictions.eq(BasePartnerInfo.DELETEFLAG, s)); List<PartnerinfoTree> partnerMap = getService().findPartnerByMap(detachedCriteria, productTypeId); Map<String, List<PartnerinfoTree>> data = new HashMap<String, List<PartnerinfoTree>>(); data.put("source", partnerMap); return data; } @ResponseBody @RequestMapping(value = "/getAllProperty") public List<Map<String, String>> getAllProperty(HttpServletRequest request, HttpServletResponse response, @RequestParam("partnerType") String partnerType) { partnerType = "2000"; List<Map<String, String>> rs = getService().findPartnerByProperty(partnerType); return rs; } /** * <code>partnerSearch</code> * * @param request * @param response * @return * @since 2013-11-13 guokemenng */ @RequestMapping(value = "/partnerInfo_Search") public ModelAndView partnerSearch(HttpServletRequest request, HttpServletResponse response) { ModelAndView mav = new ModelAndView("business/projectm/partnerInfo_search"); //厂商设备类型 List<SysDomainValue> typeList = getService().getConfPartnerType(); mav.addObject("typeList", typeList); //厂商服务供应商类型 List<SysDomainValue> serviceList = getService().getPartnerServiceType(); mav.addObject("serviceList", serviceList); return mav; } /** * <code>add</code> * 返回到增加页面 * @param request * @param response * @return * @since 2013-11-18 guokemenng */ @RequestMapping(value = "/add") public ModelAndView add(HttpServletRequest request, HttpServletResponse response) { ModelAndView mav = new ModelAndView("business/projectm/partnerInfo_saveOrUpdate"); //厂商设备类型 List<SysDomainValue> typeList = getService().getConfPartnerType(); mav.addObject("typeList", typeList); //厂商服务供应商类型 List<SysDomainValue> serviceList = getService().getPartnerServiceType(); mav.addObject("serviceList", serviceList); return mav; } @SuppressWarnings("unchecked") @ResponseBody @RequestMapping(value = "/saveOrUpdate") public String saveOrUpdate(HttpServletRequest request, HttpServletResponse response) { try { Map<String, String[]> parameterMap = request.getParameterMap(); String id = parameterMap.get("id")[0]; if (id == null || id.equals("")) { this.model.setId(new Date().getTime() + ""); } this.model.setPartnerCode(parameterMap.get("partnerCode")[0]); this.model.setPartnerFullName(parameterMap.get("partnerFullName")[0]); // this.model.setPartnerEnCode(parameterMap.get("partnerEnCode")[0]); // this.model.setPartnerLogo(parameterMap.get("partnerLogo")[0]); // this.model.setRegisterAddress(parameterMap.get("registerAddress")[0]); this.model.setAddress(parameterMap.get("address")[0]); this.model.setHotLine(parameterMap.get("hotLine")[0]); // this.model.setPartnerOid(parameterMap.get("partnerOid")[0]); // this.model.setPartnerEmail(parameterMap.get("partnerEmail")[0]); // this.model.setWebUrl(parameterMap.get("webUrl")[0]); String[] partnerTypes = parameterMap.get("partnerType"); // if (partnerType != null && partnerType != "") { // this.model.setPartnerType(Short.parseShort(partnerType)); // } String partnerType = ""; boolean b = false; if (partnerTypes != null) { for (String type : partnerTypes) { if (type.equals("3000")) { b = true; } partnerType += type + ","; } } this.model.setPartnerType(partnerType); String productType = parameterMap.get("productType")[0]; if (b) { String servicePartnerType = parameterMap.get("servicePartnerType")[0]; if (servicePartnerType != null && servicePartnerType != "") { this.model.setServicePartnerType(Short.parseShort(servicePartnerType)); } } else { this.model.setServicePartnerType(null); } this.model.setCurrency(parameterMap.get("currency")[0]); getService().saveOrUpdate(this.model); if (StringUtil.isEmpty(id)) { if (!StringUtil.isEmpty(productType)) { String[] productTypeIds = productType.split(","); for (String typeId : productTypeIds) { //厂商产品类别 BasePartnerProduct partnerProduct = new BasePartnerProduct(); partnerProduct.setId(UUIDUtil.random()); partnerProduct.setProductTypeId(typeId); partnerProduct.setBasePartnerInfo(this.model); this.partnerProductService.create(partnerProduct); } } } else { if (!StringUtil.isEmpty(productType)) { String[] productTypeIds = productType.split(","); partnerProductService.delete(id); //先删除所有厂商对应类型 for (String typeId : productTypeIds) { //依次添加厂商对应的产品类别 BasePartnerProduct partnerProduct = new BasePartnerProduct(); partnerProduct.setId(UUIDUtil.random()); partnerProduct.setProductTypeId(typeId); partnerProduct.setBasePartnerInfo(this.model); this.partnerProductService.create(partnerProduct); } } } return this.model.getId(); } catch (Exception e) { e.printStackTrace(); return FAIL; } } /** * <code>detail</code> * * @param request * @param response * @return * @since 2014-12-9 wangya */ @RequestMapping(value = "/detail") public ModelAndView detail(HttpServletRequest request, HttpServletResponse response) { ModelAndView mav = new ModelAndView("business/projectm/partnerInfo_detail"); String id = request.getParameter("id"); BasePartnerInfo model = getService().get(id); //厂商类型 Set<BasePartnerProduct> productTypeSet = model.getBasePartnerProducts(); StringBuffer sb = new StringBuffer(); StringBuffer sbNames = new StringBuffer(); StringBuffer sbs = new StringBuffer(); StringBuffer sbIds = new StringBuffer(); if (productTypeSet.size() > 0) { Iterator<BasePartnerProduct> it = productTypeSet.iterator(); while (it.hasNext()) { BasePartnerProduct product = it.next(); BaseProductType type = this.productTypeService.get(product.getProductTypeId()); if (type != null) { sb.append(type.getTypeName() + ","); sbs.append(product.getProductTypeId() + ","); } } String[] typeNames = sb.toString().split(","); for (int i = 0; i < typeNames.length; i++) { if (i == typeNames.length - 1) { sbNames.append(typeNames[i]); } else { sbNames.append(typeNames[i] + ","); } } String[] typeIds = sbs.toString().split(","); for (int i = 0; i < typeIds.length; i++) { if (i == typeIds.length - 1) { sbIds.append(typeIds[i]); } else { sbIds.append(typeIds[i] + ","); } } } mav.addObject("typeNames", sbNames.toString()); mav.addObject("model", model); //厂商设备类型 List<SysDomainValue> typeList = getService().getConfPartnerType(); mav.addObject("typeList", typeList); return mav; } @RequestMapping(value = "/edit") public ModelAndView edit(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") String id) { ModelAndView mav = new ModelAndView("business/projectm/partnerInfo_saveOrUpdate"); this.model = getService().get(id); //厂商设备类型 List<SysDomainValue> typeList = getService().getConfPartnerType(); mav.addObject("typeList", typeList); //厂商服务供应商类型 List<SysDomainValue> serviceList = getService().getPartnerServiceType(); mav.addObject("serviceList", serviceList); mav.addObject("model", this.model); //厂商类型 Set<BasePartnerProduct> productTypeSet = this.model.getBasePartnerProducts(); StringBuffer sb = new StringBuffer(); StringBuffer sbNames = new StringBuffer(); StringBuffer sbs = new StringBuffer(); StringBuffer sbIds = new StringBuffer(); if (productTypeSet.size() > 0) { Iterator<BasePartnerProduct> it = productTypeSet.iterator(); while (it.hasNext()) { BasePartnerProduct product = it.next(); if (!StringUtil.isEmpty(product.getProductTypeId())) { BaseProductType type = this.productTypeService.get(product.getProductTypeId()); if (type != null) { sb.append(type.getTypeName() + ","); } sbs.append(product.getProductTypeId() + ","); } } String[] typeNames = sb.toString().split(","); for (int i = 0; i < typeNames.length; i++) { if (i == typeNames.length - 1) { sbNames.append(typeNames[i]); } else { sbNames.append(typeNames[i] + ","); } } String[] typeIds = sbs.toString().split(","); for (int i = 0; i < typeIds.length; i++) { if (i == typeIds.length - 1) { sbIds.append(typeIds[i]); } else { sbIds.append(typeIds[i] + ","); } } } mav.addObject("typeIds", sbIds.toString()); mav.addObject("typeNames", sbNames.toString()); return mav; } /** * <code>buildSearch</code> * 创建查询条件 * @param detachedCriteria * @since 2013-11-13 guokemenng */ public void buildSearch(HttpServletRequest request, DetachedCriteria detachedCriteria) { //没删除 Short s = 1; detachedCriteria.add(Restrictions.eq(BasePartnerInfo.DELETEFLAG, s)); //厂商类型 String partnerType = request.getParameter("partnerType"); //服务供应商类型 String servicePartnerType = request.getParameter("servicePartnerType"); String partnerName = request.getParameter("partnerName"); if (partnerType != null) { detachedCriteria.add(Restrictions.like(BasePartnerInfo.PARTNERTYPE, partnerType)); } if (partnerName != null) { detachedCriteria.add(Restrictions.like(BasePartnerInfo.PARTNERFULLNAME, partnerName)); } if (servicePartnerType != null) { detachedCriteria.add(Restrictions.eq(BasePartnerInfo.SERVICEPARTNERTYPE, Short.parseShort(servicePartnerType))); } } @RequestMapping(value = "/getAlltype") @ResponseBody public List<RoleForm> getAlltype() { List<RoleForm> rs = new ArrayList<RoleForm>(); List<BaseProductType> types = productTypeService.find(); for (BaseProductType baseProductType : types) { RoleForm rf = new RoleForm(); rf.setId(baseProductType.getId()); rf.setName(baseProductType.getTypeName()); rf.setPiny(baseProductType.getTypeCode()); rs.add(rf); } return rs; } @RequestMapping(value = "/getPartnertype") @ResponseBody public List<RoleForm> getPartnertype(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") String id) { List<RoleForm> rs = new ArrayList<RoleForm>(); List<BaseProductType> types = productTypeService.getListByPartner(id); for (BaseProductType baseProductType : types) { RoleForm rf = new RoleForm(); rf.setId(baseProductType.getId()); rf.setName(baseProductType.getTypeName()); rf.setPiny(baseProductType.getTypeCode()); rs.add(rf); } return rs; } /** * <code>addPartnerProduct</code> * 添加设备类型 * @param request * @param response * @param permissions * @return * @since 2013-11-19 guokemenng */ @ResponseBody @RequestMapping(value = "/addPartnerProduct", method = RequestMethod.POST) public String addPartnerProduct(HttpServletRequest request, HttpServletResponse response, @RequestParam("permissions") String permissions) { try { if (permissions != null) { getService().addPartnerProduct(permissions); } return SUCCESS; } catch (Exception e) { e.printStackTrace(); return FAIL; } } /** * <code>remove</code> * 删除信息 * @param request * @param response * @param id * @return * @since 2013-11-20 guokemenng */ @ResponseBody @RequestMapping(value = "/remove") public String remove(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") String id) { try { getService().delete(id); return SUCCESS; } catch (Exception e) { e.printStackTrace(); return FAIL; } } /** * <code>getProductByPartner</code> * 得到厂商所支持的类型 * 格式{["id":XX,"name":XX]} * @param partnerId * @return * @since 2013-11-20 guokemenng */ @ResponseBody @RequestMapping(value = "/getProductByPartner") public List<Map<String, String>> getProductByPartner(@RequestParam("partnerId") String partnerId) { this.model = getService().get(partnerId); Set<BasePartnerProduct> productSet = new HashSet<BasePartnerProduct>(0); if (this.model != null) { productSet = this.model.getBasePartnerProducts(); } List<Map<String, String>> mapList = new ArrayList<Map<String, String>>(); if (productSet.size() > 0) { Iterator<BasePartnerProduct> it = productSet.iterator(); while (it.hasNext()) { BasePartnerProduct product = it.next(); Map<String, String> map = new HashMap<String, String>(); map.put("id", product.getId()); map.put("name", this.productTypeService.get(product.getProductTypeId()).getTypeName()); mapList.add(map); } } return mapList; } /** * <code>searchStaff</code> * 厂商插件,搜索厂商 * @param request * @param response * @return * @since 2014年8月19日 guokemenng */ @ResponseBody @RequestMapping(value = "/searchPartnerInfo") public Map<String, Object> searchPartnerInfo(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> map = new HashMap<String, Object>(); String pageNo = request.getParameter("pageNo"); String pageSize = request.getParameter("pageSize"); String name = request.getParameter("text"); String code = request.getParameter("code"); if (StringUtil.isEmpty(code)) { return map; } else if (code.equals("root")) { if (pageNo != null) { this.pageNo = Integer.parseInt(pageNo) - 1; } if (pageSize != null) { this.pageSize = Integer.parseInt(pageSize); } DetachedCriteria detachedCriteria = DetachedCriteria.forClass(getModel().getClass()); if (!StringUtil.isEmpty(name)) { detachedCriteria.add(Restrictions.or(Restrictions.like(BasePartnerInfo.PARTNERFULLNAME, name + "%"), Restrictions.like(BasePartnerInfo.PARTNERCODE, name + "%"))); } PaginationSupport paginationSupport = getService().findPageByCriteria(detachedCriteria, this.pageNo * this.pageSize, this.pageSize); @SuppressWarnings("unchecked") List<BasePartnerInfo> modelList = (List<BasePartnerInfo>) paginationSupport.getItems(); List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>(); for (BasePartnerInfo info : modelList) { mapList.add(PartnerUtils.transferPartner(info.getId(), info.getPartnerFullName())); } map.put("rows", mapList); map.put("total", paginationSupport.getTotalCount()); map.put("page", pageNo); return map; } else { if (pageNo != null) { this.pageNo = Integer.parseInt(pageNo) - 1; } if (pageSize != null) { this.pageSize = Integer.parseInt(pageSize); } Object[] params = new Object[3]; params[0] = code; params[1] = name + "%"; params[2] = name + "%"; List<BasePartnerInfo> modelList = getService().getPartnerInfoByProductTypeId(this.pageNo, this.pageSize, params); List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>(); for (BasePartnerInfo info : modelList) { mapList.add(PartnerUtils.transferPartner(info.getId(), info.getPartnerFullName())); } map.put("rows", mapList); map.put("total", getService().getTotalCount(params)); map.put("page", pageNo); return map; } } /** * <code>getPartnerCtyByType</code> * 厂商插件,厂商根据字母分类列表 * @return * @since 2014年8月19日 guokemenng */ @ResponseBody @RequestMapping(value = "/getPartnerCtyByType") public List<Map<String, Object>> getPartnerCtyByType(HttpServletRequest request, HttpServletResponse response) { String code = request.getParameter("code"); String id = request.getParameter("id"); if (StringUtil.isEmpty(id)) { return PartnerUtils.getInitializePartnerCty(); } else { List<BasePartnerInfo> modelList = null; //所有的厂商 if (StringUtil.isEmpty(code)) { modelList = new ArrayList<BasePartnerInfo>(); //显示为空 } else if (code.equals("root")) { modelList = getService().find(); } else { Object[] params = new Object[1]; params[0] = code; String sql = "select * from business_partnerinfo p,business_partnerproduct t where p.id = t.partnerId and t.productTypeId = ?"; // modelList = getService().getPartnerInfoByType(code); modelList = getService().getPartnerInfoByProductTypeId(sql, params); } return PartnerUtils.transferPartner(id, modelList); } } @ResponseBody @RequestMapping(value = "/getParentsByPartner") public List<Map<String, Object>> getParentsByPartner(HttpServletRequest request, HttpServletResponse response) { List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>(); String selectId = request.getParameter("selectId"); BasePartnerInfo model = getService().get(selectId); String id = PartnerUtils.getTypeByPartner(model); Map<String, Object> map = new HashMap<String, Object>(); map.put("id", id); mapList.add(map); return mapList; } public static void main(String[] args) { System.out.println(11); /* try { InetAddress a = InetAddress.getLocalHost(); System.out.println(a); } catch (Exception e) { }*/ } }
UTF-8
Java
25,957
java
BasePartnerInfoController.java
Java
[ { "context": "Controller</code>\n * \n * @version 1.0\n * @author guokemenng\n * @since 1.0 2013-11-26\n */\n@Controller\n@Reques", "end": 2262, "score": 0.9991087913513184, "start": 2252, "tag": "USERNAME", "value": "guokemenng" }, { "context": "ponse\n * @return\n * @since 2013-11-13 guokemenng\n */\n @RequestMapping(value = \"/partnerInfo", "end": 2780, "score": 0.9020041227340698, "start": 2770, "tag": "USERNAME", "value": "guokemenng" }, { "context": " 获取列表\n * @return\n * @since 2013-11-13 guokemenng\n */\n @ResponseBody\n @RequestMapping(val", "end": 3588, "score": 0.7730404138565063, "start": 3578, "tag": "USERNAME", "value": "guokemenng" }, { "context": "egalAccessException \n * @since 2013-11-13 guokemenng\n */\n @ResponseBody\n @RequestMapping(val", "end": 4759, "score": 0.9988425374031067, "start": 4749, "tag": "USERNAME", "value": "guokemenng" }, { "context": "ponse\n * @return\n * @since 2013-11-13 guokemenng\n */\n @RequestMapping(value = \"/partnerInfo", "end": 6054, "score": 0.9937837719917297, "start": 6044, "tag": "USERNAME", "value": "guokemenng" }, { "context": "ponse\n * @return\n * @since 2013-11-18 guokemenng\n */\n @RequestMapping(value = \"/add\")\n p", "end": 6763, "score": 0.9949288368225098, "start": 6753, "tag": "USERNAME", "value": "guokemenng" }, { "context": "ram detachedCriteria\n * @since 2013-11-13 guokemenng\n */\n public void buildSearch(HttpServletRe", "end": 15883, "score": 0.9969037771224976, "start": 15873, "tag": "USERNAME", "value": "guokemenng" }, { "context": "sions\n * @return\n * @since 2013-11-19 guokemenng\n */\n @ResponseBody\n @RequestMapping(val", "end": 18188, "score": 0.9776657819747925, "start": 18178, "tag": "USERNAME", "value": "guokemenng" }, { "context": "am id\n * @return\n * @since 2013-11-20 guokemenng\n */\n @ResponseBody\n @RequestMapping(val", "end": 18866, "score": 0.9665492177009583, "start": 18856, "tag": "USERNAME", "value": "guokemenng" }, { "context": "nerId\n * @return\n * @since 2013-11-20 guokemenng\n */\n @ResponseBody\n @RequestMapping(val", "end": 19410, "score": 0.9940260648727417, "start": 19400, "tag": "USERNAME", "value": "guokemenng" }, { "context": "ponse\n * @return\n * @since 2014年8月19日 guokemenng\n */\n @ResponseBody\n @RequestMapping(val", "end": 20580, "score": 0.9957807660102844, "start": 20570, "tag": "USERNAME", "value": "guokemenng" }, { "context": "母分类列表\n * @return\n * @since 2014年8月19日 guokemenng\n */\n @ResponseBody\n @RequestMapping(val", "end": 23486, "score": 0.9961802363395691, "start": 23476, "tag": "USERNAME", "value": "guokemenng" } ]
null
[]
/* * FileName: BasePartnerInfoController.java * 北京神州新桥科技有限公司 * Copyright 2013-2014 (C) Sino-Bridge Software CO., LTD. All Rights Reserved. */ package com.sinobridge.eoss.business.projectmanage.controller; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.sinobridge.base.core.controller.DefaultBaseController; import com.sinobridge.base.core.utils.PaginationSupport; import com.sinobridge.eoss.business.projectmanage.dto.PartnerinfoTree; import com.sinobridge.eoss.business.projectmanage.model.BasePartnerInfo; import com.sinobridge.eoss.business.projectmanage.model.BasePartnerProduct; import com.sinobridge.eoss.business.projectmanage.model.BaseProductType; import com.sinobridge.eoss.business.projectmanage.service.BasePartnerInfoService; import com.sinobridge.eoss.business.projectmanage.service.BasePartnerProductService; import com.sinobridge.eoss.business.projectmanage.service.BaseProductTypeService; import com.sinobridge.eoss.business.projectmanage.utils.PartnerUtils; import com.sinobridge.systemmanage.controller.bean.RoleForm; import com.sinobridge.systemmanage.model.SysDomainValue; import com.sinobridge.systemmanage.model.SysPowerAction; import com.sinobridge.systemmanage.util.Global; import com.sinobridge.systemmanage.util.StringUtil; import com.sinobridge.systemmanage.util.UUIDUtil; import com.sinobridge.systemmanage.vo.SystemUser; /** * <code>BasePartnerInfoController</code> * * @version 1.0 * @author guokemenng * @since 1.0 2013-11-26 */ @Controller @RequestMapping(value = "/business/projectm/partnerInfo") public class BasePartnerInfoController extends DefaultBaseController<BasePartnerInfo, BasePartnerInfoService> { @Autowired private BaseProductTypeService productTypeService; @Autowired protected BasePartnerProductService partnerProductService; /** * <code>partnerManager</code> * 主页面 * @param request * @param response * @return * @since 2013-11-13 guokemenng */ @RequestMapping(value = "/partnerInfo_main") public ModelAndView getPartnerInfo(HttpServletRequest request, HttpServletResponse response) { ModelAndView mav = new ModelAndView("business/projectm/partnerInfo_main"); SystemUser systemUser = (SystemUser) request.getSession().getAttribute(Global.LOGIN_USER); List<SysPowerAction> actions = systemUser.getSysPowerActions(); StringBuffer buffers = new StringBuffer(); for (SysPowerAction sysPowerAction : actions) { buffers.append(sysPowerAction.getPowCode()); buffers.append(","); } mav.addObject("powerActions", buffers.toString()); return mav; } /** * <code>getList</code> * 获取列表 * @return * @since 2013-11-13 guokemenng */ @ResponseBody @RequestMapping(value = "/getList") public Map<String, Object> getList(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> map = new HashMap<String, Object>(); String page = request.getParameter("page"); String rows = request.getParameter("rows"); if (page != null) { this.pageNo = Integer.parseInt(page); } if (rows != null) { this.pageSize = Integer.parseInt(rows); } DetachedCriteria detachedCriteria = DetachedCriteria.forClass(this.model.getClass()); buildSearch(request, detachedCriteria); PaginationSupport paginationSupport = getService().findPageByCriteria(detachedCriteria, this.pageNo, this.pageSize); map.put("total", paginationSupport.getTotalCount()); map.put("rows", paginationSupport.getItems()); return map; } /** * <code>getList</code> * 得到所有厂商格式{["id":XX,"name":XX]} * @return * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException * @since 2013-11-13 guokemenng */ @ResponseBody @RequestMapping(value = "/getAll") public Map<String, List<PartnerinfoTree>> getAll(HttpServletRequest request, HttpServletResponse response, @RequestParam("productTypeId") String productTypeId) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { DetachedCriteria detachedCriteria = DetachedCriteria.forClass(this.model.getClass()); Short s = 1; detachedCriteria.add(Restrictions.eq(BasePartnerInfo.DELETEFLAG, s)); List<PartnerinfoTree> partnerMap = getService().findPartnerByMap(detachedCriteria, productTypeId); Map<String, List<PartnerinfoTree>> data = new HashMap<String, List<PartnerinfoTree>>(); data.put("source", partnerMap); return data; } @ResponseBody @RequestMapping(value = "/getAllProperty") public List<Map<String, String>> getAllProperty(HttpServletRequest request, HttpServletResponse response, @RequestParam("partnerType") String partnerType) { partnerType = "2000"; List<Map<String, String>> rs = getService().findPartnerByProperty(partnerType); return rs; } /** * <code>partnerSearch</code> * * @param request * @param response * @return * @since 2013-11-13 guokemenng */ @RequestMapping(value = "/partnerInfo_Search") public ModelAndView partnerSearch(HttpServletRequest request, HttpServletResponse response) { ModelAndView mav = new ModelAndView("business/projectm/partnerInfo_search"); //厂商设备类型 List<SysDomainValue> typeList = getService().getConfPartnerType(); mav.addObject("typeList", typeList); //厂商服务供应商类型 List<SysDomainValue> serviceList = getService().getPartnerServiceType(); mav.addObject("serviceList", serviceList); return mav; } /** * <code>add</code> * 返回到增加页面 * @param request * @param response * @return * @since 2013-11-18 guokemenng */ @RequestMapping(value = "/add") public ModelAndView add(HttpServletRequest request, HttpServletResponse response) { ModelAndView mav = new ModelAndView("business/projectm/partnerInfo_saveOrUpdate"); //厂商设备类型 List<SysDomainValue> typeList = getService().getConfPartnerType(); mav.addObject("typeList", typeList); //厂商服务供应商类型 List<SysDomainValue> serviceList = getService().getPartnerServiceType(); mav.addObject("serviceList", serviceList); return mav; } @SuppressWarnings("unchecked") @ResponseBody @RequestMapping(value = "/saveOrUpdate") public String saveOrUpdate(HttpServletRequest request, HttpServletResponse response) { try { Map<String, String[]> parameterMap = request.getParameterMap(); String id = parameterMap.get("id")[0]; if (id == null || id.equals("")) { this.model.setId(new Date().getTime() + ""); } this.model.setPartnerCode(parameterMap.get("partnerCode")[0]); this.model.setPartnerFullName(parameterMap.get("partnerFullName")[0]); // this.model.setPartnerEnCode(parameterMap.get("partnerEnCode")[0]); // this.model.setPartnerLogo(parameterMap.get("partnerLogo")[0]); // this.model.setRegisterAddress(parameterMap.get("registerAddress")[0]); this.model.setAddress(parameterMap.get("address")[0]); this.model.setHotLine(parameterMap.get("hotLine")[0]); // this.model.setPartnerOid(parameterMap.get("partnerOid")[0]); // this.model.setPartnerEmail(parameterMap.get("partnerEmail")[0]); // this.model.setWebUrl(parameterMap.get("webUrl")[0]); String[] partnerTypes = parameterMap.get("partnerType"); // if (partnerType != null && partnerType != "") { // this.model.setPartnerType(Short.parseShort(partnerType)); // } String partnerType = ""; boolean b = false; if (partnerTypes != null) { for (String type : partnerTypes) { if (type.equals("3000")) { b = true; } partnerType += type + ","; } } this.model.setPartnerType(partnerType); String productType = parameterMap.get("productType")[0]; if (b) { String servicePartnerType = parameterMap.get("servicePartnerType")[0]; if (servicePartnerType != null && servicePartnerType != "") { this.model.setServicePartnerType(Short.parseShort(servicePartnerType)); } } else { this.model.setServicePartnerType(null); } this.model.setCurrency(parameterMap.get("currency")[0]); getService().saveOrUpdate(this.model); if (StringUtil.isEmpty(id)) { if (!StringUtil.isEmpty(productType)) { String[] productTypeIds = productType.split(","); for (String typeId : productTypeIds) { //厂商产品类别 BasePartnerProduct partnerProduct = new BasePartnerProduct(); partnerProduct.setId(UUIDUtil.random()); partnerProduct.setProductTypeId(typeId); partnerProduct.setBasePartnerInfo(this.model); this.partnerProductService.create(partnerProduct); } } } else { if (!StringUtil.isEmpty(productType)) { String[] productTypeIds = productType.split(","); partnerProductService.delete(id); //先删除所有厂商对应类型 for (String typeId : productTypeIds) { //依次添加厂商对应的产品类别 BasePartnerProduct partnerProduct = new BasePartnerProduct(); partnerProduct.setId(UUIDUtil.random()); partnerProduct.setProductTypeId(typeId); partnerProduct.setBasePartnerInfo(this.model); this.partnerProductService.create(partnerProduct); } } } return this.model.getId(); } catch (Exception e) { e.printStackTrace(); return FAIL; } } /** * <code>detail</code> * * @param request * @param response * @return * @since 2014-12-9 wangya */ @RequestMapping(value = "/detail") public ModelAndView detail(HttpServletRequest request, HttpServletResponse response) { ModelAndView mav = new ModelAndView("business/projectm/partnerInfo_detail"); String id = request.getParameter("id"); BasePartnerInfo model = getService().get(id); //厂商类型 Set<BasePartnerProduct> productTypeSet = model.getBasePartnerProducts(); StringBuffer sb = new StringBuffer(); StringBuffer sbNames = new StringBuffer(); StringBuffer sbs = new StringBuffer(); StringBuffer sbIds = new StringBuffer(); if (productTypeSet.size() > 0) { Iterator<BasePartnerProduct> it = productTypeSet.iterator(); while (it.hasNext()) { BasePartnerProduct product = it.next(); BaseProductType type = this.productTypeService.get(product.getProductTypeId()); if (type != null) { sb.append(type.getTypeName() + ","); sbs.append(product.getProductTypeId() + ","); } } String[] typeNames = sb.toString().split(","); for (int i = 0; i < typeNames.length; i++) { if (i == typeNames.length - 1) { sbNames.append(typeNames[i]); } else { sbNames.append(typeNames[i] + ","); } } String[] typeIds = sbs.toString().split(","); for (int i = 0; i < typeIds.length; i++) { if (i == typeIds.length - 1) { sbIds.append(typeIds[i]); } else { sbIds.append(typeIds[i] + ","); } } } mav.addObject("typeNames", sbNames.toString()); mav.addObject("model", model); //厂商设备类型 List<SysDomainValue> typeList = getService().getConfPartnerType(); mav.addObject("typeList", typeList); return mav; } @RequestMapping(value = "/edit") public ModelAndView edit(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") String id) { ModelAndView mav = new ModelAndView("business/projectm/partnerInfo_saveOrUpdate"); this.model = getService().get(id); //厂商设备类型 List<SysDomainValue> typeList = getService().getConfPartnerType(); mav.addObject("typeList", typeList); //厂商服务供应商类型 List<SysDomainValue> serviceList = getService().getPartnerServiceType(); mav.addObject("serviceList", serviceList); mav.addObject("model", this.model); //厂商类型 Set<BasePartnerProduct> productTypeSet = this.model.getBasePartnerProducts(); StringBuffer sb = new StringBuffer(); StringBuffer sbNames = new StringBuffer(); StringBuffer sbs = new StringBuffer(); StringBuffer sbIds = new StringBuffer(); if (productTypeSet.size() > 0) { Iterator<BasePartnerProduct> it = productTypeSet.iterator(); while (it.hasNext()) { BasePartnerProduct product = it.next(); if (!StringUtil.isEmpty(product.getProductTypeId())) { BaseProductType type = this.productTypeService.get(product.getProductTypeId()); if (type != null) { sb.append(type.getTypeName() + ","); } sbs.append(product.getProductTypeId() + ","); } } String[] typeNames = sb.toString().split(","); for (int i = 0; i < typeNames.length; i++) { if (i == typeNames.length - 1) { sbNames.append(typeNames[i]); } else { sbNames.append(typeNames[i] + ","); } } String[] typeIds = sbs.toString().split(","); for (int i = 0; i < typeIds.length; i++) { if (i == typeIds.length - 1) { sbIds.append(typeIds[i]); } else { sbIds.append(typeIds[i] + ","); } } } mav.addObject("typeIds", sbIds.toString()); mav.addObject("typeNames", sbNames.toString()); return mav; } /** * <code>buildSearch</code> * 创建查询条件 * @param detachedCriteria * @since 2013-11-13 guokemenng */ public void buildSearch(HttpServletRequest request, DetachedCriteria detachedCriteria) { //没删除 Short s = 1; detachedCriteria.add(Restrictions.eq(BasePartnerInfo.DELETEFLAG, s)); //厂商类型 String partnerType = request.getParameter("partnerType"); //服务供应商类型 String servicePartnerType = request.getParameter("servicePartnerType"); String partnerName = request.getParameter("partnerName"); if (partnerType != null) { detachedCriteria.add(Restrictions.like(BasePartnerInfo.PARTNERTYPE, partnerType)); } if (partnerName != null) { detachedCriteria.add(Restrictions.like(BasePartnerInfo.PARTNERFULLNAME, partnerName)); } if (servicePartnerType != null) { detachedCriteria.add(Restrictions.eq(BasePartnerInfo.SERVICEPARTNERTYPE, Short.parseShort(servicePartnerType))); } } @RequestMapping(value = "/getAlltype") @ResponseBody public List<RoleForm> getAlltype() { List<RoleForm> rs = new ArrayList<RoleForm>(); List<BaseProductType> types = productTypeService.find(); for (BaseProductType baseProductType : types) { RoleForm rf = new RoleForm(); rf.setId(baseProductType.getId()); rf.setName(baseProductType.getTypeName()); rf.setPiny(baseProductType.getTypeCode()); rs.add(rf); } return rs; } @RequestMapping(value = "/getPartnertype") @ResponseBody public List<RoleForm> getPartnertype(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") String id) { List<RoleForm> rs = new ArrayList<RoleForm>(); List<BaseProductType> types = productTypeService.getListByPartner(id); for (BaseProductType baseProductType : types) { RoleForm rf = new RoleForm(); rf.setId(baseProductType.getId()); rf.setName(baseProductType.getTypeName()); rf.setPiny(baseProductType.getTypeCode()); rs.add(rf); } return rs; } /** * <code>addPartnerProduct</code> * 添加设备类型 * @param request * @param response * @param permissions * @return * @since 2013-11-19 guokemenng */ @ResponseBody @RequestMapping(value = "/addPartnerProduct", method = RequestMethod.POST) public String addPartnerProduct(HttpServletRequest request, HttpServletResponse response, @RequestParam("permissions") String permissions) { try { if (permissions != null) { getService().addPartnerProduct(permissions); } return SUCCESS; } catch (Exception e) { e.printStackTrace(); return FAIL; } } /** * <code>remove</code> * 删除信息 * @param request * @param response * @param id * @return * @since 2013-11-20 guokemenng */ @ResponseBody @RequestMapping(value = "/remove") public String remove(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") String id) { try { getService().delete(id); return SUCCESS; } catch (Exception e) { e.printStackTrace(); return FAIL; } } /** * <code>getProductByPartner</code> * 得到厂商所支持的类型 * 格式{["id":XX,"name":XX]} * @param partnerId * @return * @since 2013-11-20 guokemenng */ @ResponseBody @RequestMapping(value = "/getProductByPartner") public List<Map<String, String>> getProductByPartner(@RequestParam("partnerId") String partnerId) { this.model = getService().get(partnerId); Set<BasePartnerProduct> productSet = new HashSet<BasePartnerProduct>(0); if (this.model != null) { productSet = this.model.getBasePartnerProducts(); } List<Map<String, String>> mapList = new ArrayList<Map<String, String>>(); if (productSet.size() > 0) { Iterator<BasePartnerProduct> it = productSet.iterator(); while (it.hasNext()) { BasePartnerProduct product = it.next(); Map<String, String> map = new HashMap<String, String>(); map.put("id", product.getId()); map.put("name", this.productTypeService.get(product.getProductTypeId()).getTypeName()); mapList.add(map); } } return mapList; } /** * <code>searchStaff</code> * 厂商插件,搜索厂商 * @param request * @param response * @return * @since 2014年8月19日 guokemenng */ @ResponseBody @RequestMapping(value = "/searchPartnerInfo") public Map<String, Object> searchPartnerInfo(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> map = new HashMap<String, Object>(); String pageNo = request.getParameter("pageNo"); String pageSize = request.getParameter("pageSize"); String name = request.getParameter("text"); String code = request.getParameter("code"); if (StringUtil.isEmpty(code)) { return map; } else if (code.equals("root")) { if (pageNo != null) { this.pageNo = Integer.parseInt(pageNo) - 1; } if (pageSize != null) { this.pageSize = Integer.parseInt(pageSize); } DetachedCriteria detachedCriteria = DetachedCriteria.forClass(getModel().getClass()); if (!StringUtil.isEmpty(name)) { detachedCriteria.add(Restrictions.or(Restrictions.like(BasePartnerInfo.PARTNERFULLNAME, name + "%"), Restrictions.like(BasePartnerInfo.PARTNERCODE, name + "%"))); } PaginationSupport paginationSupport = getService().findPageByCriteria(detachedCriteria, this.pageNo * this.pageSize, this.pageSize); @SuppressWarnings("unchecked") List<BasePartnerInfo> modelList = (List<BasePartnerInfo>) paginationSupport.getItems(); List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>(); for (BasePartnerInfo info : modelList) { mapList.add(PartnerUtils.transferPartner(info.getId(), info.getPartnerFullName())); } map.put("rows", mapList); map.put("total", paginationSupport.getTotalCount()); map.put("page", pageNo); return map; } else { if (pageNo != null) { this.pageNo = Integer.parseInt(pageNo) - 1; } if (pageSize != null) { this.pageSize = Integer.parseInt(pageSize); } Object[] params = new Object[3]; params[0] = code; params[1] = name + "%"; params[2] = name + "%"; List<BasePartnerInfo> modelList = getService().getPartnerInfoByProductTypeId(this.pageNo, this.pageSize, params); List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>(); for (BasePartnerInfo info : modelList) { mapList.add(PartnerUtils.transferPartner(info.getId(), info.getPartnerFullName())); } map.put("rows", mapList); map.put("total", getService().getTotalCount(params)); map.put("page", pageNo); return map; } } /** * <code>getPartnerCtyByType</code> * 厂商插件,厂商根据字母分类列表 * @return * @since 2014年8月19日 guokemenng */ @ResponseBody @RequestMapping(value = "/getPartnerCtyByType") public List<Map<String, Object>> getPartnerCtyByType(HttpServletRequest request, HttpServletResponse response) { String code = request.getParameter("code"); String id = request.getParameter("id"); if (StringUtil.isEmpty(id)) { return PartnerUtils.getInitializePartnerCty(); } else { List<BasePartnerInfo> modelList = null; //所有的厂商 if (StringUtil.isEmpty(code)) { modelList = new ArrayList<BasePartnerInfo>(); //显示为空 } else if (code.equals("root")) { modelList = getService().find(); } else { Object[] params = new Object[1]; params[0] = code; String sql = "select * from business_partnerinfo p,business_partnerproduct t where p.id = t.partnerId and t.productTypeId = ?"; // modelList = getService().getPartnerInfoByType(code); modelList = getService().getPartnerInfoByProductTypeId(sql, params); } return PartnerUtils.transferPartner(id, modelList); } } @ResponseBody @RequestMapping(value = "/getParentsByPartner") public List<Map<String, Object>> getParentsByPartner(HttpServletRequest request, HttpServletResponse response) { List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>(); String selectId = request.getParameter("selectId"); BasePartnerInfo model = getService().get(selectId); String id = PartnerUtils.getTypeByPartner(model); Map<String, Object> map = new HashMap<String, Object>(); map.put("id", id); mapList.add(map); return mapList; } public static void main(String[] args) { System.out.println(11); /* try { InetAddress a = InetAddress.getLocalHost(); System.out.println(a); } catch (Exception e) { }*/ } }
25,957
0.606834
0.600611
648
38.427467
31.144938
245
false
false
0
0
0
0
0
0
0.614198
false
false
11
166e2812c93b2c7b4ab5c9765b705c888cf55350
781,684,067,232
aad3bf65ba6fe04b20898d09704870fa7d7b81ba
/MainLib/src/main/java/com/mjn/libs/api/interceptor/BaoSaveCookiesInterceptor.java
a981638cd8c871e20cb578aa5169721aa16c093e
[]
no_license
lanboys/Life-tools-app
https://github.com/lanboys/Life-tools-app
db53f7e21d2d8aa8590ff4ef5d468d3db1b5a601
7471d35fef0dd509bebbcb205b1fec650a491791
refs/heads/master
2020-03-22T11:26:02.072000
2018-03-29T09:19:25
2018-03-29T09:52:48
139,970,544
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mjn.libs.api.interceptor; import android.content.Context; import android.text.TextUtils; import com.bing.lan.comm.api.interceptor.CookiesInterceptor; import com.mjn.libs.utils.AppSpDataUtil; import java.io.IOException; import java.util.List; import okhttp3.Request; import okhttp3.Response; /** * 从 Response 中获取 set-cookie 字段的值,并保存在本地 */ public class BaoSaveCookiesInterceptor extends CookiesInterceptor { public BaoSaveCookiesInterceptor(Context context) { super(context); } @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response response = chain.proceed(request); if (!response.headers("set-cookie").isEmpty()) { List<String> cookies = response.headers("set-cookie"); for (String cookie : cookies) { if (cookie.contains("token")) { saveBaoToken(cookie); } } } else { log.i("没有Cookie,不做保存操作 "); } return response; } private void saveBaoToken(String cookie) { if (!TextUtils.isEmpty(cookie) && !AppSpDataUtil.getInstance().getCookies().contains(cookie)) { String temp = AppSpDataUtil.getInstance().getCookies(); log.i("saveBaoToken()前: " + temp); temp += cookie + ";"; log.i("saveBaoToken()前: " + temp); AppSpDataUtil.getInstance().setCookies(temp); } } }
UTF-8
Java
1,565
java
BaoSaveCookiesInterceptor.java
Java
[]
null
[]
package com.mjn.libs.api.interceptor; import android.content.Context; import android.text.TextUtils; import com.bing.lan.comm.api.interceptor.CookiesInterceptor; import com.mjn.libs.utils.AppSpDataUtil; import java.io.IOException; import java.util.List; import okhttp3.Request; import okhttp3.Response; /** * 从 Response 中获取 set-cookie 字段的值,并保存在本地 */ public class BaoSaveCookiesInterceptor extends CookiesInterceptor { public BaoSaveCookiesInterceptor(Context context) { super(context); } @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response response = chain.proceed(request); if (!response.headers("set-cookie").isEmpty()) { List<String> cookies = response.headers("set-cookie"); for (String cookie : cookies) { if (cookie.contains("token")) { saveBaoToken(cookie); } } } else { log.i("没有Cookie,不做保存操作 "); } return response; } private void saveBaoToken(String cookie) { if (!TextUtils.isEmpty(cookie) && !AppSpDataUtil.getInstance().getCookies().contains(cookie)) { String temp = AppSpDataUtil.getInstance().getCookies(); log.i("saveBaoToken()前: " + temp); temp += cookie + ";"; log.i("saveBaoToken()前: " + temp); AppSpDataUtil.getInstance().setCookies(temp); } } }
1,565
0.615182
0.613861
53
27.584906
22.904589
80
false
false
0
0
0
0
0
0
0.433962
false
false
11
f2a287433ee04b0334b1c5ad24473af8861342ad
20,366,734,964,395
7c23099374591bc68283712ad4e95f977f8dd0d2
/com/parallel6/ui/adapters/pager/CategoriesPageAdapter.java
3fc1f35928d140c0fbc9a231e30ed8e1939d81ef
[]
no_license
eFOIA-12/eFOIA
https://github.com/eFOIA-12/eFOIA
736af184a67de80c209c2719c8119fc260e9fe3e
e9add4119191d68f826981a42fcacdb44982ac89
refs/heads/master
2021-01-21T23:33:36.280000
2015-07-14T17:47:01
2015-07-14T17:47:01
38,971,834
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.parallel6.ui.adapters.pager; import android.app.Activity; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.GridView; import com.parallel6.captivereachconnectsdk.CaptiveReachConnect; import com.parallel6.captivereachconnectsdk.R; import com.parallel6.captivereachconnectsdk.models.MobileMenu; import com.parallel6.ui.actions.CRActionFactory; import com.parallel6.ui.adapters.CategoriesGridAdapter; import com.parallel6.ui.enums.Action; import com.parallel6.ui.interfaces.ControllerState; import java.util.ArrayList; import java.util.List; public class CategoriesPageAdapter extends PagerAdapter { private static final String TAG = CategoriesPageAdapter.class.getSimpleName(); protected CRActionFactory actionFactory; protected Activity activity; private int bgCategoriesGridBottom = -1; private int bgCategoriesGridTop = -1; protected ControllerState categoriesController; private CategoriesGridAdapter.OnCategorySelectedListener categoriesListener = new CategoriesGridAdapter.OnCategorySelectedListener() { public void onCategorySelected(MobileMenu var1) { CaptiveReachConnect.getInstance().trackInsightV2(CategoriesPageAdapter.this.context, "mobile_menus", "open", String.valueOf(var1.getId()), var1.getTitle()); CategoriesPageAdapter.this.actionFactory.executeAction(Action.valueOf(var1.getAction().toUpperCase()), var1, CategoriesPageAdapter.this.categoriesController); } }; private final int categoriesPerPage = 6; private List categoryList; protected Context context; private boolean isShowTitle = true; private boolean matchSize; protected OnClickListener onActionClickListener; public CategoriesPageAdapter(Context var1, List var2, int var3, int var4, ControllerState var5, CRActionFactory var6) { this.context = var1; this.categoryList = var2; this.categoriesController = var5; this.bgCategoriesGridTop = var3; this.bgCategoriesGridBottom = var4; this.actionFactory = var6; } public CategoriesPageAdapter(Context var1, List var2, int var3, int var4, ControllerState var5, boolean var6, CRActionFactory var7) { this.context = var1; this.categoryList = var2; this.categoriesController = var5; this.bgCategoriesGridTop = var3; this.bgCategoriesGridBottom = var4; this.matchSize = var6; this.actionFactory = var7; } public void destroyItem(ViewGroup var1, int var2, Object var3) { var1.removeView((View)var3); } protected CategoriesGridAdapter getCategoriesGridAdapter(Context var1, List var2, int var3, int var4, int var5, CategoriesGridAdapter.OnCategorySelectedListener var6, boolean var7) { return new CategoriesGridAdapter(var1, var2, var3, var4, var5, var6, var7); } protected CategoriesGridAdapter.OnCategorySelectedListener getCategoriesGridListener() { return this.categoriesListener; } protected int getCategoryPageLayoutResource() { return R.layout.page_category; } public int getCount() { return (int)Math.ceil((double)this.categoryList.size() / 6.0D); } public boolean getIsShowTitle() { return this.isShowTitle; } public Object instantiateItem(ViewGroup var1, int var2) { Log.d(TAG, "Inflating page: " + var2); View var5 = LayoutInflater.from(this.context).inflate(this.getCategoryPageLayoutResource(), var1, false); GridView var6 = (GridView)var5.findViewById(R.id.categories_gridview); var2 *= 6; int var4 = var2 + 6; Log.d(TAG, "Showing categories: [" + var2 + ", " + var4 + "]"); ArrayList var7 = new ArrayList(); while(true) { int var3; if(var4 < this.categoryList.size()) { var3 = var4; } else { var3 = this.categoryList.size(); } if(var2 >= var3) { CategoriesGridAdapter var8 = this.getCategoriesGridAdapter(this.context, var7, 6, this.bgCategoriesGridTop, this.bgCategoriesGridBottom, this.getCategoriesGridListener(), this.matchSize); var8.isShowTitle(this.getIsShowTitle()); var6.setAdapter(var8); var1.addView(var5); return var5; } var7.add(this.categoryList.get(var2)); ++var2; } } public boolean isViewFromObject(View var1, Object var2) { return var1.equals(var2); } public void setIsShowTitle(boolean var1) { this.isShowTitle = var1; } }
UTF-8
Java
4,804
java
CategoriesPageAdapter.java
Java
[]
null
[]
package com.parallel6.ui.adapters.pager; import android.app.Activity; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.GridView; import com.parallel6.captivereachconnectsdk.CaptiveReachConnect; import com.parallel6.captivereachconnectsdk.R; import com.parallel6.captivereachconnectsdk.models.MobileMenu; import com.parallel6.ui.actions.CRActionFactory; import com.parallel6.ui.adapters.CategoriesGridAdapter; import com.parallel6.ui.enums.Action; import com.parallel6.ui.interfaces.ControllerState; import java.util.ArrayList; import java.util.List; public class CategoriesPageAdapter extends PagerAdapter { private static final String TAG = CategoriesPageAdapter.class.getSimpleName(); protected CRActionFactory actionFactory; protected Activity activity; private int bgCategoriesGridBottom = -1; private int bgCategoriesGridTop = -1; protected ControllerState categoriesController; private CategoriesGridAdapter.OnCategorySelectedListener categoriesListener = new CategoriesGridAdapter.OnCategorySelectedListener() { public void onCategorySelected(MobileMenu var1) { CaptiveReachConnect.getInstance().trackInsightV2(CategoriesPageAdapter.this.context, "mobile_menus", "open", String.valueOf(var1.getId()), var1.getTitle()); CategoriesPageAdapter.this.actionFactory.executeAction(Action.valueOf(var1.getAction().toUpperCase()), var1, CategoriesPageAdapter.this.categoriesController); } }; private final int categoriesPerPage = 6; private List categoryList; protected Context context; private boolean isShowTitle = true; private boolean matchSize; protected OnClickListener onActionClickListener; public CategoriesPageAdapter(Context var1, List var2, int var3, int var4, ControllerState var5, CRActionFactory var6) { this.context = var1; this.categoryList = var2; this.categoriesController = var5; this.bgCategoriesGridTop = var3; this.bgCategoriesGridBottom = var4; this.actionFactory = var6; } public CategoriesPageAdapter(Context var1, List var2, int var3, int var4, ControllerState var5, boolean var6, CRActionFactory var7) { this.context = var1; this.categoryList = var2; this.categoriesController = var5; this.bgCategoriesGridTop = var3; this.bgCategoriesGridBottom = var4; this.matchSize = var6; this.actionFactory = var7; } public void destroyItem(ViewGroup var1, int var2, Object var3) { var1.removeView((View)var3); } protected CategoriesGridAdapter getCategoriesGridAdapter(Context var1, List var2, int var3, int var4, int var5, CategoriesGridAdapter.OnCategorySelectedListener var6, boolean var7) { return new CategoriesGridAdapter(var1, var2, var3, var4, var5, var6, var7); } protected CategoriesGridAdapter.OnCategorySelectedListener getCategoriesGridListener() { return this.categoriesListener; } protected int getCategoryPageLayoutResource() { return R.layout.page_category; } public int getCount() { return (int)Math.ceil((double)this.categoryList.size() / 6.0D); } public boolean getIsShowTitle() { return this.isShowTitle; } public Object instantiateItem(ViewGroup var1, int var2) { Log.d(TAG, "Inflating page: " + var2); View var5 = LayoutInflater.from(this.context).inflate(this.getCategoryPageLayoutResource(), var1, false); GridView var6 = (GridView)var5.findViewById(R.id.categories_gridview); var2 *= 6; int var4 = var2 + 6; Log.d(TAG, "Showing categories: [" + var2 + ", " + var4 + "]"); ArrayList var7 = new ArrayList(); while(true) { int var3; if(var4 < this.categoryList.size()) { var3 = var4; } else { var3 = this.categoryList.size(); } if(var2 >= var3) { CategoriesGridAdapter var8 = this.getCategoriesGridAdapter(this.context, var7, 6, this.bgCategoriesGridTop, this.bgCategoriesGridBottom, this.getCategoriesGridListener(), this.matchSize); var8.isShowTitle(this.getIsShowTitle()); var6.setAdapter(var8); var1.addView(var5); return var5; } var7.add(this.categoryList.get(var2)); ++var2; } } public boolean isViewFromObject(View var1, Object var2) { return var1.equals(var2); } public void setIsShowTitle(boolean var1) { this.isShowTitle = var1; } }
4,804
0.703997
0.68214
122
37.377048
37.785706
199
false
false
0
0
0
0
0
0
0.95082
false
false
11
21518eba14e0ac0ed88e72e190d03dec5ba08a99
2,164,663,578,924
a073f65363ac9ef129df1d4777fb3f32cf928811
/src/main/java/com/express/controller/NoticeController.java
9d615025f588a7cb85a3ab30811a2dcfce30f475
[]
no_license
KishorDavara/Spring-Security
https://github.com/KishorDavara/Spring-Security
9626a4a8c28a3cf09bfaeabe6353e7f7353fbf6e
46184efa8823bbb1316420dca6e528090b74c3b9
refs/heads/main
2023-05-11T08:36:11.752000
2023-05-01T06:21:20
2023-05-01T06:21:20
630,334,239
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.express.controller; import com.express.model.Notice; import com.express.repository.NoticeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.CacheControl; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.concurrent.TimeUnit; @RestController public class NoticeController { @Autowired private NoticeRepository noticeRepository; @GetMapping("/notices") public ResponseEntity<List<Notice>> getNoticeDetails() { List<Notice> notices = noticeRepository.findAllActiveNotices(); if(!notices.isEmpty()) { return ResponseEntity.ok() .cacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS)) .body(notices); } return null; } }
UTF-8
Java
953
java
NoticeController.java
Java
[]
null
[]
package com.express.controller; import com.express.model.Notice; import com.express.repository.NoticeRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.CacheControl; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.concurrent.TimeUnit; @RestController public class NoticeController { @Autowired private NoticeRepository noticeRepository; @GetMapping("/notices") public ResponseEntity<List<Notice>> getNoticeDetails() { List<Notice> notices = noticeRepository.findAllActiveNotices(); if(!notices.isEmpty()) { return ResponseEntity.ok() .cacheControl(CacheControl.maxAge(60, TimeUnit.SECONDS)) .body(notices); } return null; } }
953
0.734523
0.732424
30
30.766666
22.934229
76
false
false
0
0
0
0
0
0
0.5
false
false
11
ce5cd173b05037b4f73374dbe72a39b09444961b
23,141,283,846,923
5f7141adfd93217181cba67fabc661f74d0a2a3b
/ocp/src/main/java/ocp/design/TestProxy.java
69a956974d9b9d190227dcfbbbc79dd315177dba
[]
no_license
dineshbias/coreJava
https://github.com/dineshbias/coreJava
640ef8f1cc24420262a03289ffda374b268d76ba
122fef9c646533fabab713bc3b788a685ff553d6
refs/heads/master
2020-03-10T17:10:56.691000
2019-02-26T13:53:48
2019-02-26T13:53:48
129,493,611
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package ocp.design; import java.lang.reflect.Proxy; import ocp.design.proxy.OwnerInvocationHandler; import ocp.design.proxy.PersonBean; import ocp.design.proxy.PersonBeanImpl; /** * @author dinesh.joshi * */ public class TestProxy { public static void main(String... args) { TestProxy test = new TestProxy(); test.testDrive(); } public void testDrive() { PersonBean joe = new PersonBeanImpl("joe", "Male", "Dating", 1); PersonBean ownerProxy = getOwnerProxyBean(joe); System.out.println("Name is : " + ownerProxy.getName()); ownerProxy.setInterests("bowling"); System.out.println("Interest set for owner proxy : " + ownerProxy.getName()); System.out.println("Rating " + ownerProxy.getHotOrNotRating()); try { ownerProxy.setHotOrNotRating(45); } catch (Exception e) { e.printStackTrace(); } System.out.println("Rating " + ownerProxy.getHotOrNotRating()); } public static PersonBean getOwnerProxyBean(PersonBean personBean) { return (PersonBean) Proxy.newProxyInstance(personBean.getClass().getClassLoader(), personBean.getClass().getInterfaces(), new OwnerInvocationHandler(personBean)); } }
UTF-8
Java
1,206
java
TestProxy.java
Java
[ { "context": "cp.design.proxy.PersonBeanImpl;\r\n\r\n/**\r\n * @author dinesh.joshi\r\n *\r\n */\r\npublic class TestProxy {\r\n\r\n\tpublic sta", "end": 230, "score": 0.8701667785644531, "start": 218, "tag": "NAME", "value": "dinesh.joshi" }, { "context": "Drive() {\r\n\t\tPersonBean joe = new PersonBeanImpl(\"joe\", \"Male\", \"Dating\", 1);\r\n\r\n\t\tPersonBean ownerProx", "end": 449, "score": 0.9805697798728943, "start": 446, "tag": "NAME", "value": "joe" }, { "context": "rsonBean joe = new PersonBeanImpl(\"joe\", \"Male\", \"Dating\", 1);\r\n\r\n\t\tPersonBean ownerProxy = getOwnerProxyB", "end": 467, "score": 0.888862133026123, "start": 461, "tag": "NAME", "value": "Dating" } ]
null
[]
/** * */ package ocp.design; import java.lang.reflect.Proxy; import ocp.design.proxy.OwnerInvocationHandler; import ocp.design.proxy.PersonBean; import ocp.design.proxy.PersonBeanImpl; /** * @author dinesh.joshi * */ public class TestProxy { public static void main(String... args) { TestProxy test = new TestProxy(); test.testDrive(); } public void testDrive() { PersonBean joe = new PersonBeanImpl("joe", "Male", "Dating", 1); PersonBean ownerProxy = getOwnerProxyBean(joe); System.out.println("Name is : " + ownerProxy.getName()); ownerProxy.setInterests("bowling"); System.out.println("Interest set for owner proxy : " + ownerProxy.getName()); System.out.println("Rating " + ownerProxy.getHotOrNotRating()); try { ownerProxy.setHotOrNotRating(45); } catch (Exception e) { e.printStackTrace(); } System.out.println("Rating " + ownerProxy.getHotOrNotRating()); } public static PersonBean getOwnerProxyBean(PersonBean personBean) { return (PersonBean) Proxy.newProxyInstance(personBean.getClass().getClassLoader(), personBean.getClass().getInterfaces(), new OwnerInvocationHandler(personBean)); } }
1,206
0.693201
0.690713
47
23.659575
26.263214
84
false
false
0
0
0
0
0
0
1.361702
false
false
11
5cc27ea146e3da94f12b95a8b4417b62d51c80ae
23,141,283,844,804
fe486edfc70088dba4d821f828f528733cc1d1d9
/Abstract Factory/src/Lotion.java
9f6a541d860c27869e43262529de8854d854d2c4
[]
no_license
gopinadh66/Abstract-Factory-
https://github.com/gopinadh66/Abstract-Factory-
643348d031845ed4deb4a8b41ad3568a12b28e48
3e3a009aac7bca9a4c5e001756d051438172037c
refs/heads/main
2023-08-11T13:52:38.999000
2021-09-10T14:20:21
2021-09-10T14:20:21
405,105,891
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public interface Lotion { public void getLotion(); }
UTF-8
Java
64
java
Lotion.java
Java
[]
null
[]
public interface Lotion { public void getLotion(); }
64
0.625
0.625
5
10.4
11.926441
25
false
false
0
0
0
0
0
0
0.6
false
false
11
3a949bfd32ceef004868f8bd92375243ef1be4d1
8,615,704,458,305
67cef68337acf9ebac1ef356181c6223a9f5a811
/src/main/java/com/tools/ztest/test/Outer.java
92613aed9791a4ed6aab0622963d245b69efe753
[]
no_license
YingjieW/tools
https://github.com/YingjieW/tools
730a94ed231d621fc460e2905870e6a911210f0d
4048b03dd036674dd74381d6a062cc9aeb0725b8
refs/heads/master
2022-12-24T22:33:40.611000
2019-05-27T06:33:34
2019-05-27T06:33:34
61,645,070
0
0
null
false
2022-12-16T02:43:36
2016-06-21T15:25:03
2019-05-27T06:33:53
2022-12-16T02:43:31
76,826
0
0
18
Java
false
false
package com.tools.ztest.test; /** * Descripe: * * @author yingjie.wang * @since 17/2/27 下午5:21 */ public class Outer { class Inner { private int a = 10; } private Inner inner = new Inner(); private int b = inner.a; private void print() { System.out.println("b: " + b); } public static void main(String[] args) { Outer outer = new Outer(); outer.print(); } }
UTF-8
Java
432
java
Outer.java
Java
[ { "context": ".tools.ztest.test;\n\n/**\n * Descripe:\n *\n * @author yingjie.wang\n * @since 17/2/27 下午5:21\n */\npublic class Outer {", "end": 74, "score": 0.9962289333343506, "start": 62, "tag": "NAME", "value": "yingjie.wang" } ]
null
[]
package com.tools.ztest.test; /** * Descripe: * * @author yingjie.wang * @since 17/2/27 下午5:21 */ public class Outer { class Inner { private int a = 10; } private Inner inner = new Inner(); private int b = inner.a; private void print() { System.out.println("b: " + b); } public static void main(String[] args) { Outer outer = new Outer(); outer.print(); } }
432
0.553738
0.530374
22
18.454546
13.54698
44
false
false
0
0
0
0
0
0
0.318182
false
false
11
48061507afc18e684032f1ffcc5e6407a4a2cbdc
4,509,715,723,524
f13357a637f3bcbcc244ed9ba194a50dda25065e
/src/tasks1/series/Main40a.java
61b38e8b97bbc0b9e81c6d0df423468cd176e246
[]
no_license
ShkurinaMaria/my-first-tasks
https://github.com/ShkurinaMaria/my-first-tasks
ff8d73ab63b981dd9201f904cd589ef481cf9564
d68bb6f0bfdd62e48099778cebf1a2cb9176dcae
refs/heads/master
2023-02-27T20:51:51.004000
2021-02-10T17:17:26
2021-02-10T17:17:26
308,081,797
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tasks1.series; import java.util.SortedMap; public class Main40a { public static void main(String[] args) { int[] arr1 = {3, 6, 1, 7, 9}; int[] arr2 = {6, 6, 1, 7, 3,7,8}; int[] arr3 = {3, 1, 4, 2, 3}; int[] arr4 = {34, 66, 2, 56, 8, 2}; System.out.println(sequence(arr1)); System.out.println(sequence(arr2)); System.out.println(sequence(arr3)); System.out.println(sequence(arr4)); } static int sequence(int[] arr) { int k = 0; for (int i = 1; i < arr.length - 1; i++) { boolean firstCondition = arr[i - 1] > arr[i] && arr[i] < arr[i + 1]; boolean secondCondition = arr[i - 1] < arr[i] && arr[i] > arr[i + 1]; if (firstCondition || secondCondition) { k = arr.length; } else { System.out.print("Номер первого элемента, который не является зубчиком = "); return i; } } System.out.print("Количество элементов в пилообразной последовательности = "); return k; } }
UTF-8
Java
1,195
java
Main40a.java
Java
[]
null
[]
package tasks1.series; import java.util.SortedMap; public class Main40a { public static void main(String[] args) { int[] arr1 = {3, 6, 1, 7, 9}; int[] arr2 = {6, 6, 1, 7, 3,7,8}; int[] arr3 = {3, 1, 4, 2, 3}; int[] arr4 = {34, 66, 2, 56, 8, 2}; System.out.println(sequence(arr1)); System.out.println(sequence(arr2)); System.out.println(sequence(arr3)); System.out.println(sequence(arr4)); } static int sequence(int[] arr) { int k = 0; for (int i = 1; i < arr.length - 1; i++) { boolean firstCondition = arr[i - 1] > arr[i] && arr[i] < arr[i + 1]; boolean secondCondition = arr[i - 1] < arr[i] && arr[i] > arr[i + 1]; if (firstCondition || secondCondition) { k = arr.length; } else { System.out.print("Номер первого элемента, который не является зубчиком = "); return i; } } System.out.print("Количество элементов в пилообразной последовательности = "); return k; } }
1,195
0.513636
0.473636
34
31.352942
25.492655
92
false
false
0
0
0
0
0
0
1.235294
false
false
11
e1b3749ea7b4004d7c87e05e28e2f6e9ab3a6bad
33,870,112,155,561
0d3728d898d6c184cee057d1302f5d7913cae26c
/api/src/main/java/org/openmrs/module/appointments/validator/impl/DefaultAppointmentValidator.java
ee7b3b92fe56aadf2d2d991f750b45c7cabf3ef2
[]
no_license
eRegister/openmrs-module-appointments
https://github.com/eRegister/openmrs-module-appointments
d4e97c0e33d443510aaaea341e155029c0712939
527018ea636966ac691b95f3ab7e85599cac4a1d
refs/heads/master
2021-12-05T04:26:45.889000
2021-07-07T11:21:28
2021-07-07T11:21:28
149,622,153
0
0
null
true
2018-09-20T14:27:37
2018-09-20T14:27:37
2018-09-20T06:49:36
2018-09-20T06:49:34
441
0
0
0
null
false
null
package org.openmrs.module.appointments.validator.impl; import org.openmrs.api.context.Context; import org.openmrs.module.appointments.model.Appointment; import org.openmrs.module.appointments.validator.AppointmentValidator; import org.springframework.stereotype.Component; import java.util.List; @Component public class DefaultAppointmentValidator implements AppointmentValidator { @Override public void validate(Appointment appointment, List<String> errors) { if (appointment.getPatient() == null) errors.add("Appointment cannot be created without Patient"); if (appointment.getService() == null) errors.add("Appointment cannot be created without Service"); } }
UTF-8
Java
701
java
DefaultAppointmentValidator.java
Java
[]
null
[]
package org.openmrs.module.appointments.validator.impl; import org.openmrs.api.context.Context; import org.openmrs.module.appointments.model.Appointment; import org.openmrs.module.appointments.validator.AppointmentValidator; import org.springframework.stereotype.Component; import java.util.List; @Component public class DefaultAppointmentValidator implements AppointmentValidator { @Override public void validate(Appointment appointment, List<String> errors) { if (appointment.getPatient() == null) errors.add("Appointment cannot be created without Patient"); if (appointment.getService() == null) errors.add("Appointment cannot be created without Service"); } }
701
0.78174
0.78174
20
33.049999
27.439888
74
false
false
0
0
0
0
0
0
1.1
false
false
11
78c430924481c11acf943558bb5d39e8583de015
38,019,050,528,024
c5e51cb9b1b1e8d749629bad7b1f77f10a632f1a
/app/src/main/java/video/zkk/com/huyavideo/fragment/home/ErciyuanFragment.java
a8f9d852da2c87e4800e3bee37155db8fb3b3add
[]
no_license
panacena/huyavideo
https://github.com/panacena/huyavideo
bf96c46c257522fea4d8078ca415539b94803597
3895eb630980545408603c29380a60a0fa90b708
refs/heads/master
2021-01-23T14:05:48.585000
2017-06-23T10:03:43
2017-06-23T10:03:43
93,240,991
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package video.zkk.com.huyavideo.fragment.home; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.alibaba.fastjson.JSON; import com.aspsine.swipetoloadlayout.OnLoadMoreListener; import com.aspsine.swipetoloadlayout.OnRefreshListener; import com.aspsine.swipetoloadlayout.SwipeToLoadLayout; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.StringCallback; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import okhttp3.Call; import video.zkk.com.huyavideo.R; import video.zkk.com.huyavideo.activity.home.VideoActivity; import video.zkk.com.huyavideo.adapter.home.FuliAdapter; import video.zkk.com.huyavideo.api.Api; import video.zkk.com.huyavideo.bean.home.FuliBean; /** * Created by Administrator on 2016/9/13 0013. */ public class ErciyuanFragment extends Fragment implements OnRefreshListener,OnLoadMoreListener{ @BindView(R.id.swipeToLoadLayout) SwipeToLoadLayout swipeToLoadLayout; @BindView(R.id.swipe_target) RecyclerView swipe_target; FuliAdapter mFuliAdapter; int start = 0; //当前是第几页 private List<FuliBean.UserBean> mFuliBean=new ArrayList<FuliBean.UserBean>(); @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view=inflater.inflate(R.layout.frament_fuli, container,false); ButterKnife.bind(this,view) ; swipeToLoadLayout.setOnLoadMoreListener(this); swipeToLoadLayout.setOnRefreshListener(this); mFuliAdapter=new FuliAdapter(getActivity()); swipe_target.setLayoutManager(new LinearLayoutManager(getActivity())); swipe_target.setAdapter(mFuliAdapter); mFuliAdapter.setOnItemClickListener(new FuliAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Intent intent=new Intent(getActivity(), VideoActivity.class); intent.putExtra("videoId",mFuliBean.get(position).getVideo_id()); intent.putExtra("videoName",mFuliBean.get(position).getTitle()); startActivity(intent); } }); get_fulisForTest(); return view; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Override public void onRefresh() { get_fulis(); } @Override public void onLoadMore() { start=start+40; get_Morefulis(start); } private void get_fulisForTest(){ swipeToLoadLayout.postDelayed(new Runnable() { @Override public void run() { swipeToLoadLayout.setRefreshing(true); } }, 10); } private void get_fulis(){ OkHttpUtils .get() .url(Api.Erciyuan_URL) .addParams("start", "0") .addParams("pageNum", "40") .build() .execute(new StringCallback() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(String response, int id) { mFuliBean.clear(); FuliBean fuliBean= JSON.parseObject(response,FuliBean.class); mFuliBean.addAll(fuliBean.getUser()); Log.i("zkk--"," " + response); swipeToLoadLayout.postDelayed(new Runnable() { @Override public void run() { swipeToLoadLayout.setRefreshing(false); mFuliAdapter.setList(mFuliBean); } }, 10); } }); } /** * 下拉获取更多 */ private void get_Morefulis(Integer nowstart){ Log.i("zkk---",nowstart +""); OkHttpUtils .get() .url(Api.FULI_URL) .addParams("start", nowstart+"") .addParams("pageNum", "20") .build() .execute(new StringCallback() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(String response, int id) { FuliBean fuliBean= JSON.parseObject(response,FuliBean.class); mFuliBean.addAll(fuliBean.getUser()); Log.i("zkk--"," " + response); swipeToLoadLayout.postDelayed(new Runnable() { @Override public void run() { swipeToLoadLayout.setLoadingMore(false); mFuliAdapter.setList(mFuliBean); } }, 10); } }); } }
UTF-8
Java
5,742
java
ErciyuanFragment.java
Java
[]
null
[]
package video.zkk.com.huyavideo.fragment.home; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.alibaba.fastjson.JSON; import com.aspsine.swipetoloadlayout.OnLoadMoreListener; import com.aspsine.swipetoloadlayout.OnRefreshListener; import com.aspsine.swipetoloadlayout.SwipeToLoadLayout; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.StringCallback; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import okhttp3.Call; import video.zkk.com.huyavideo.R; import video.zkk.com.huyavideo.activity.home.VideoActivity; import video.zkk.com.huyavideo.adapter.home.FuliAdapter; import video.zkk.com.huyavideo.api.Api; import video.zkk.com.huyavideo.bean.home.FuliBean; /** * Created by Administrator on 2016/9/13 0013. */ public class ErciyuanFragment extends Fragment implements OnRefreshListener,OnLoadMoreListener{ @BindView(R.id.swipeToLoadLayout) SwipeToLoadLayout swipeToLoadLayout; @BindView(R.id.swipe_target) RecyclerView swipe_target; FuliAdapter mFuliAdapter; int start = 0; //当前是第几页 private List<FuliBean.UserBean> mFuliBean=new ArrayList<FuliBean.UserBean>(); @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view=inflater.inflate(R.layout.frament_fuli, container,false); ButterKnife.bind(this,view) ; swipeToLoadLayout.setOnLoadMoreListener(this); swipeToLoadLayout.setOnRefreshListener(this); mFuliAdapter=new FuliAdapter(getActivity()); swipe_target.setLayoutManager(new LinearLayoutManager(getActivity())); swipe_target.setAdapter(mFuliAdapter); mFuliAdapter.setOnItemClickListener(new FuliAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Intent intent=new Intent(getActivity(), VideoActivity.class); intent.putExtra("videoId",mFuliBean.get(position).getVideo_id()); intent.putExtra("videoName",mFuliBean.get(position).getTitle()); startActivity(intent); } }); get_fulisForTest(); return view; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } @Override public void onRefresh() { get_fulis(); } @Override public void onLoadMore() { start=start+40; get_Morefulis(start); } private void get_fulisForTest(){ swipeToLoadLayout.postDelayed(new Runnable() { @Override public void run() { swipeToLoadLayout.setRefreshing(true); } }, 10); } private void get_fulis(){ OkHttpUtils .get() .url(Api.Erciyuan_URL) .addParams("start", "0") .addParams("pageNum", "40") .build() .execute(new StringCallback() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(String response, int id) { mFuliBean.clear(); FuliBean fuliBean= JSON.parseObject(response,FuliBean.class); mFuliBean.addAll(fuliBean.getUser()); Log.i("zkk--"," " + response); swipeToLoadLayout.postDelayed(new Runnable() { @Override public void run() { swipeToLoadLayout.setRefreshing(false); mFuliAdapter.setList(mFuliBean); } }, 10); } }); } /** * 下拉获取更多 */ private void get_Morefulis(Integer nowstart){ Log.i("zkk---",nowstart +""); OkHttpUtils .get() .url(Api.FULI_URL) .addParams("start", nowstart+"") .addParams("pageNum", "20") .build() .execute(new StringCallback() { @Override public void onError(Call call, Exception e, int id) { } @Override public void onResponse(String response, int id) { FuliBean fuliBean= JSON.parseObject(response,FuliBean.class); mFuliBean.addAll(fuliBean.getUser()); Log.i("zkk--"," " + response); swipeToLoadLayout.postDelayed(new Runnable() { @Override public void run() { swipeToLoadLayout.setLoadingMore(false); mFuliAdapter.setList(mFuliBean); } }, 10); } }); } }
5,742
0.57625
0.571179
183
30.245901
25.717033
129
false
false
0
0
0
0
0
0
0.540984
false
false
11
3f18b6516e2b8ff18c0daf89aa8bb347b72e7b01
33,895,881,946,957
94e4357c6a0de2bcefd391b676b65b136cb3e835
/Comanda/src/LogicaDelAutomata/PedidoEntregado.java
b239153819ec5625df15de5bdae6ac8b12590934
[]
no_license
r-news/patternsAndSOLID
https://github.com/r-news/patternsAndSOLID
bbbe3778f1b007681376dd38e855449a9a725532
7ecc241cc2024529f0ec6a1958c9c4d4b945decd
refs/heads/master
2020-05-30T14:44:22.307000
2019-06-13T16:37:49
2019-06-13T16:37:49
189,798,483
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package LogicaDelAutomata; import Acciones.*; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author rodrigo */ public class PedidoEntregado extends EstadoPedido { public PedidoEntregado() { this.nombre = "Pedido Entregado"; } @Override public EstadoPedido ejecutarAccion(Accion accion) { EstadoPedido siguienteEstado; if (accion instanceof Ordenar) { siguienteEstado = new PedidoTomado(); } else if (accion instanceof PedirCuenta) { siguienteEstado = new EsperandoCuenta(); } else { siguienteEstado = this; } return siguienteEstado; } @Override public boolean equals(Object objeto) { boolean esIgual = true; if (objeto == null || objeto.getClass() != this.getClass()) { esIgual = false; } if (objeto instanceof PedidoEntregado) { PedidoEntregado otra = (PedidoEntregado) objeto; esIgual = this.nombre.equals(otra.getNombre()); } return esIgual; } }
UTF-8
Java
1,212
java
PedidoEntregado.java
Java
[ { "context": " the template in the editor.\n */\n/**\n *\n * @author rodrigo\n */\npublic class PedidoEntregado extends EstadoPe", "end": 258, "score": 0.9977484941482544, "start": 251, "tag": "USERNAME", "value": "rodrigo" } ]
null
[]
package LogicaDelAutomata; import Acciones.*; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author rodrigo */ public class PedidoEntregado extends EstadoPedido { public PedidoEntregado() { this.nombre = "Pedido Entregado"; } @Override public EstadoPedido ejecutarAccion(Accion accion) { EstadoPedido siguienteEstado; if (accion instanceof Ordenar) { siguienteEstado = new PedidoTomado(); } else if (accion instanceof PedirCuenta) { siguienteEstado = new EsperandoCuenta(); } else { siguienteEstado = this; } return siguienteEstado; } @Override public boolean equals(Object objeto) { boolean esIgual = true; if (objeto == null || objeto.getClass() != this.getClass()) { esIgual = false; } if (objeto instanceof PedidoEntregado) { PedidoEntregado otra = (PedidoEntregado) objeto; esIgual = this.nombre.equals(otra.getNombre()); } return esIgual; } }
1,212
0.620462
0.620462
45
25.933332
22.246498
79
false
false
0
0
0
0
0
0
0.4
false
false
11
7534e7fd235bf32fe60a73564fd7ff1d37ec41a2
35,433,480,237,141
efbbf58845ef9fddce58095a579621c39d0475b4
/src/main/java/com/stock/mvc/controllers/EmployeurController.java
e78a17e0465628f449e39576dc9d6e69a389eebb
[]
no_license
webens/gestion_de_stock
https://github.com/webens/gestion_de_stock
8dff410eb177037b548495813cfd990f1c50560e
3d6bc21dd377b64f92ece38f2e9d053c387e7ec9
refs/heads/master
2020-06-25T20:16:54.058000
2019-07-29T08:48:03
2019-07-29T08:48:03
199,412,470
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.stock.mvc.controllers; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.stock.mvc.entity.Employeur; import com.stock.mvc.services.IEmployeurService; @Controller @RequestMapping(value = "/employeur", method = RequestMethod.GET) public class EmployeurController { @Autowired public IEmployeurService employeurservice; @RequestMapping(value = "") public String employeur(Model model) { List<Employeur> employeurs=employeurservice.selectAll(); //on decide de recuperer la "selection de tout" de employeurservice ds une liste if(employeurs==null) { //on decide de dire que si la liste est vide, dinstancier des employeurs ds cette liste employeurs=new ArrayList<Employeur>(); } model.addAttribute("employeurs",employeurs); return "employeur/employeur"; } }
UTF-8
Java
1,078
java
EmployeurController.java
Java
[]
null
[]
package com.stock.mvc.controllers; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.stock.mvc.entity.Employeur; import com.stock.mvc.services.IEmployeurService; @Controller @RequestMapping(value = "/employeur", method = RequestMethod.GET) public class EmployeurController { @Autowired public IEmployeurService employeurservice; @RequestMapping(value = "") public String employeur(Model model) { List<Employeur> employeurs=employeurservice.selectAll(); //on decide de recuperer la "selection de tout" de employeurservice ds une liste if(employeurs==null) { //on decide de dire que si la liste est vide, dinstancier des employeurs ds cette liste employeurs=new ArrayList<Employeur>(); } model.addAttribute("employeurs",employeurs); return "employeur/employeur"; } }
1,078
0.797774
0.797774
30
34.933334
32.42009
140
false
false
0
0
0
0
0
0
1.233333
false
false
11
ec829f6bfba6feccea2b763258673463455c579c
39,307,540,718,452
1322898eeeec0dea191396f46e9204c57740891a
/src/main/java/ru/uds/musicproject/model/TrackObject.java
619e699e810e09d2b101b66b065cd53d20a64e4a
[]
no_license
Dimut2805/DownloaderMusic
https://github.com/Dimut2805/DownloaderMusic
f62c68154f6d601f65fc4fcb6c52515ac49de5ff
7bbb4aecd22d018b8ec944918396407ff9366693
refs/heads/master
2022-04-10T16:05:24.119000
2020-02-14T11:51:34
2020-02-14T11:51:34
238,422,709
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ru.uds.musicproject.model; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import java.io.File; import java.net.MalformedURLException; public class TrackObject { private File music; private ImageView icon; private File iconFile; public TrackObject(File icon, File music) { try { this.icon = new ImageView(new Image(icon.toURI().toURL().toString())); } catch (MalformedURLException e) { e.printStackTrace(); } iconFile = icon; this.music = music; } public File getIconFile() { return iconFile; } public ImageView getIcon() { return icon; } public File getMusic() { return music; } }
UTF-8
Java
750
java
TrackObject.java
Java
[]
null
[]
package ru.uds.musicproject.model; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import java.io.File; import java.net.MalformedURLException; public class TrackObject { private File music; private ImageView icon; private File iconFile; public TrackObject(File icon, File music) { try { this.icon = new ImageView(new Image(icon.toURI().toURL().toString())); } catch (MalformedURLException e) { e.printStackTrace(); } iconFile = icon; this.music = music; } public File getIconFile() { return iconFile; } public ImageView getIcon() { return icon; } public File getMusic() { return music; } }
750
0.621333
0.621333
35
20.457144
17.672161
82
false
false
0
0
0
0
0
0
0.457143
false
false
11
817de082047dac6aacf29419690970d39866da0b
34,720,515,677,598
91c9549eda789c55777d3d77247a528a723172b4
/files/OtsuThreshold.java
03b85c8b101a29be6f7ab63d84ce75165e2e54b5
[]
no_license
rarmand/projects_java
https://github.com/rarmand/projects_java
4321d83c3a744f3954cc552d58846849196c0ad6
c3b4871484ed1f8402ebb65b630baea2d28b0ab3
refs/heads/master
2020-01-15T14:36:58.106000
2017-03-21T19:52:47
2017-03-21T19:52:47
85,745,558
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sample.sprawko; import kimage.image.Image; import kimage.plugin.Plugin; import kimage.utils.gui.ImageFrame; import kimage.utils.histogram.Histogram; import sample.sprawko.GreyScale; /** * * @author Aleksandra Holik * progrowanie metodą Otsu */ public class OtsuThreshold extends Threshold{ @Override public int getThreshold(Image imgIn) { Histogram imgInHistogram = new Histogram(imgIn, true); int[] imgInGreyHistogram = imgInHistogram.getRedHistogram(); Integer totalPixels = imgIn.getWidth()*imgIn.getHeight(); double distributionSum = 0.0; for(int i = 0; i < 256; i++) distributionSum += (double) imgInGreyHistogram[i] * i; double distributionBackgroundSum = 0; int whiteBackground = 0; int whiteForeground = 0; double varienceMaximum = 0; int threshold = 0; for(int t = 0; t < 256; t++) { whiteBackground += imgInGreyHistogram[t]; if (whiteBackground == 0) continue; whiteForeground = totalPixels - whiteBackground; if (whiteForeground == 0) break; distributionBackgroundSum += (double) (t * imgInGreyHistogram[t]); double meanBackground; double meanForeground; meanBackground = distributionBackgroundSum / whiteBackground; meanForeground = (distributionSum - distributionBackgroundSum) / whiteForeground; double varienceBetweenClasses = (double) whiteBackground * whiteForeground * (meanBackground - meanForeground) * (meanBackground - meanForeground); if(varienceBetweenClasses > varienceMaximum) { varienceMaximum = varienceBetweenClasses; threshold = t; } } return threshold; } @Override public void process(Image imgIn, Image imgOut) { super.imgIn = imgIn; super.imgOut = imgOut; threshold = getThreshold(imgIn); makeBinary(); } public static void main(String[] argc) { Image img; img = new Image("./res/lena.png"); System.out.println("successfully loaded image"); ImageFrame originalPictureFrame = new ImageFrame(img); originalPictureFrame.display(); Plugin makeGrey = new GreyScale(); makeGrey.process(img, img); System.out.println("successfully made image to greyscale"); Plugin otsu = new OtsuThreshold(); otsu.process(img, img); System.out.println("successfully calculated otsus threshold"); ImageFrame thresholdPictureFrame = new ImageFrame(img); thresholdPictureFrame.display(); } }
UTF-8
Java
2,852
java
OtsuThreshold.java
Java
[ { "context": "mport sample.sprawko.GreyScale;\n\n/**\n *\n * @author Aleksandra Holik\n * progrowanie metodą Otsu\n */\npublic class OtsuT", "end": 227, "score": 0.9998785853385925, "start": 211, "tag": "NAME", "value": "Aleksandra Holik" } ]
null
[]
package sample.sprawko; import kimage.image.Image; import kimage.plugin.Plugin; import kimage.utils.gui.ImageFrame; import kimage.utils.histogram.Histogram; import sample.sprawko.GreyScale; /** * * @author <NAME> * progrowanie metodą Otsu */ public class OtsuThreshold extends Threshold{ @Override public int getThreshold(Image imgIn) { Histogram imgInHistogram = new Histogram(imgIn, true); int[] imgInGreyHistogram = imgInHistogram.getRedHistogram(); Integer totalPixels = imgIn.getWidth()*imgIn.getHeight(); double distributionSum = 0.0; for(int i = 0; i < 256; i++) distributionSum += (double) imgInGreyHistogram[i] * i; double distributionBackgroundSum = 0; int whiteBackground = 0; int whiteForeground = 0; double varienceMaximum = 0; int threshold = 0; for(int t = 0; t < 256; t++) { whiteBackground += imgInGreyHistogram[t]; if (whiteBackground == 0) continue; whiteForeground = totalPixels - whiteBackground; if (whiteForeground == 0) break; distributionBackgroundSum += (double) (t * imgInGreyHistogram[t]); double meanBackground; double meanForeground; meanBackground = distributionBackgroundSum / whiteBackground; meanForeground = (distributionSum - distributionBackgroundSum) / whiteForeground; double varienceBetweenClasses = (double) whiteBackground * whiteForeground * (meanBackground - meanForeground) * (meanBackground - meanForeground); if(varienceBetweenClasses > varienceMaximum) { varienceMaximum = varienceBetweenClasses; threshold = t; } } return threshold; } @Override public void process(Image imgIn, Image imgOut) { super.imgIn = imgIn; super.imgOut = imgOut; threshold = getThreshold(imgIn); makeBinary(); } public static void main(String[] argc) { Image img; img = new Image("./res/lena.png"); System.out.println("successfully loaded image"); ImageFrame originalPictureFrame = new ImageFrame(img); originalPictureFrame.display(); Plugin makeGrey = new GreyScale(); makeGrey.process(img, img); System.out.println("successfully made image to greyscale"); Plugin otsu = new OtsuThreshold(); otsu.process(img, img); System.out.println("successfully calculated otsus threshold"); ImageFrame thresholdPictureFrame = new ImageFrame(img); thresholdPictureFrame.display(); } }
2,842
0.604349
0.598387
89
31.044945
22.583136
93
false
false
0
0
0
0
0
0
0.606742
false
false
11
53c934957aa709c95189ca448f6971c7e4a73ab7
18,133,351,980,686
0680359d200c51a9a12b4367988c8864791761a2
/ViraTravelAgency/src/main/java/ir/vira/travelagency/configuration/AppSecurity.java
9e9be683a1feccc19e8ea9e1b43981e934c8768d
[]
no_license
Eagle-Eyes/VTA
https://github.com/Eagle-Eyes/VTA
95fe89231a33c99f68fa1a6a9d712854b132354c
2fc2e48b04fa2db53147c1f080b04078f79bd605
refs/heads/master
2020-04-26T23:31:39.941000
2019-03-25T04:14:16
2019-03-25T04:14:16
173,904,996
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ir.vira.travelagency.configuration; import ir.vira.travelagency.model.service.AccountService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration public class AppSecurity extends WebSecurityConfigurerAdapter { private static final Logger logger = LoggerFactory.getLogger(AppSecurity.class); private AccountService accountService; private BCryptPasswordEncoder bCryptPasswordEncoder; // private AuthenticationHandler authenticationHandler; // // public AppSecurity(AccountService accountService, BCryptPasswordEncoder bCryptPasswordEncoder, AuthenticationHandler authenticationHandler) { // this.accountService = accountService; // this.bCryptPasswordEncoder = bCryptPasswordEncoder; // this.authenticationHandler = authenticationHandler; // } public AppSecurity(AccountService accountService, BCryptPasswordEncoder bCryptPasswordEncoder) { this.accountService = accountService; this.bCryptPasswordEncoder = bCryptPasswordEncoder; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(accountService).passwordEncoder(bCryptPasswordEncoder); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/javax.faces.resource/**", "/", "/index", "/login", "/jsf/login.xhtml", "/logout", "/error", "/resetPassword/*").permitAll() // .anyRequest().authenticated() // .antMatchers("**/*.xhtml").denyAll() //, "/jsf/login.xhtml" .and() .formLogin() .loginPage("/login") // .loginProcessingUrl("/loginAction") // .successHandler(authenticationHandler) // .failureHandler(authenticationHandler) // .defaultSuccessUrl("/home") .permitAll() .and() // .exceptionHandling() // .accessDeniedPage("/403") // .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/") .permitAll() .and() .csrf().disable(); // http.authorizeRequests().antMatchers("/home/**/*").hasRole("USER"); // http.authorizeRequests().antMatchers("/admin/**/*").hasRole("ADMINISTRATOR"); } }
UTF-8
Java
3,012
java
AppSecurity.java
Java
[]
null
[]
package ir.vira.travelagency.configuration; import ir.vira.travelagency.model.service.AccountService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration public class AppSecurity extends WebSecurityConfigurerAdapter { private static final Logger logger = LoggerFactory.getLogger(AppSecurity.class); private AccountService accountService; private BCryptPasswordEncoder bCryptPasswordEncoder; // private AuthenticationHandler authenticationHandler; // // public AppSecurity(AccountService accountService, BCryptPasswordEncoder bCryptPasswordEncoder, AuthenticationHandler authenticationHandler) { // this.accountService = accountService; // this.bCryptPasswordEncoder = bCryptPasswordEncoder; // this.authenticationHandler = authenticationHandler; // } public AppSecurity(AccountService accountService, BCryptPasswordEncoder bCryptPasswordEncoder) { this.accountService = accountService; this.bCryptPasswordEncoder = bCryptPasswordEncoder; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(accountService).passwordEncoder(bCryptPasswordEncoder); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/javax.faces.resource/**", "/", "/index", "/login", "/jsf/login.xhtml", "/logout", "/error", "/resetPassword/*").permitAll() // .anyRequest().authenticated() // .antMatchers("**/*.xhtml").denyAll() //, "/jsf/login.xhtml" .and() .formLogin() .loginPage("/login") // .loginProcessingUrl("/loginAction") // .successHandler(authenticationHandler) // .failureHandler(authenticationHandler) // .defaultSuccessUrl("/home") .permitAll() .and() // .exceptionHandling() // .accessDeniedPage("/403") // .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/") .permitAll() .and() .csrf().disable(); // http.authorizeRequests().antMatchers("/home/**/*").hasRole("USER"); // http.authorizeRequests().antMatchers("/admin/**/*").hasRole("ADMINISTRATOR"); } }
3,012
0.64409
0.64243
78
37.615383
33.743462
154
false
false
0
0
0
0
0
0
0.423077
false
false
11
8746699de725b7ea52c0358446f703868b9afb1c
10,402,410,827,675
cc85674113be7c80fc75a8089a85fed24c6a6b1d
/src/Video.java
1ff554bb998be9b5f2619507855b0f1b259e1ea5
[]
no_license
pete8550/TestEksamen
https://github.com/pete8550/TestEksamen
ff8a8a1f6abe42cdec573810aaa7a4e5da266a8e
172dc2838b1adfca0a5e0a1e831f2c4b0e326eec
refs/heads/master
2020-04-12T02:36:19.721000
2018-12-18T12:38:48
2018-12-18T12:38:48
162,247,721
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.sql.Time; public class Video extends Media { private String videoType; private Time videoLenght; private String videoSolution; private String videoAuthor; @Override public void logToConsole(){ System.out.println(this.videoAuthor + this.videoType); } }
UTF-8
Java
303
java
Video.java
Java
[]
null
[]
import java.sql.Time; public class Video extends Media { private String videoType; private Time videoLenght; private String videoSolution; private String videoAuthor; @Override public void logToConsole(){ System.out.println(this.videoAuthor + this.videoType); } }
303
0.70297
0.70297
14
20.642857
17.653843
62
false
false
0
0
0
0
0
0
0.428571
false
false
11
2726fca3fc1aa326f4f743a9f8f25adb7103aa98
33,621,004,006,875
045699573f75c253513115887e04f29f1e23e432
/src/main/java/com/geetion/puputuan/service/BarService.java
ce6123e237c3ef20c15d28c5938ca73e67393bc9
[]
no_license
zhuobinchan/popoteam_server_v1.0
https://github.com/zhuobinchan/popoteam_server_v1.0
61b46d716d3257f3110ab79ec7da04c7c6d4d8e3
f4dd97f76e8d5192a54a3eafc06cd79c280155a9
refs/heads/master
2021-01-21T23:04:51.632000
2017-06-23T05:48:15
2017-06-23T05:48:15
95,187,326
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.geetion.puputuan.service; import com.geetion.puputuan.common.mybatis.PageEntity; import com.geetion.puputuan.common.mybatis.PagingResult; import com.geetion.puputuan.model.Bar; import java.util.List; import java.util.Map; public interface BarService { Bar getBarById(Long id); Bar getBar(Map param); List<Bar> getBarList(Map param); PagingResult<Bar> getBarPage(PageEntity pageEntity); boolean addBar(Bar object); boolean updateBar(Bar object); boolean removeBar(Long id); List<Bar> getOtherBars(Map param); }
UTF-8
Java
565
java
BarService.java
Java
[]
null
[]
package com.geetion.puputuan.service; import com.geetion.puputuan.common.mybatis.PageEntity; import com.geetion.puputuan.common.mybatis.PagingResult; import com.geetion.puputuan.model.Bar; import java.util.List; import java.util.Map; public interface BarService { Bar getBarById(Long id); Bar getBar(Map param); List<Bar> getBarList(Map param); PagingResult<Bar> getBarPage(PageEntity pageEntity); boolean addBar(Bar object); boolean updateBar(Bar object); boolean removeBar(Long id); List<Bar> getOtherBars(Map param); }
565
0.746903
0.746903
27
19.925926
19.556047
56
false
false
0
0
0
0
0
0
0.518519
false
false
11
64c946e7121bc93192968cbd40299237bfd860a1
12,996,571,065,008
4738d4fd8869eca8bb0cee171f33b0af6efc6e65
/iot-think/.svn/pristine/6e/6ef6c1a33709535feb908feb26322f87488bf49f.svn-base
5f2d922191764c7e27b06fe8943939a6670f9b88
[]
no_license
wwkkww1983/jidi_test_01
https://github.com/wwkkww1983/jidi_test_01
813125cf82cd0a0bb560160c3816c9b463895464
69916bb56ce67031257e88dd85a9a77d82469954
refs/heads/master
2022-03-04T21:18:39.097000
2019-07-18T14:33:31
2019-07-18T14:33:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rz.iot.think.mqtt.util; import com.rz.iot.think.mqtt.model.ConcentratorMessageBase; import com.rz.iot.think.mqtt.model.report.ConcentratorAppointParamReport; import com.rz.iot.utils.RzIotDatetime; import com.rz.iot.utils.RzIotDigit; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * @Author:jidi * @Date:2019/04/17 15:01 * @Description: **/ public class MqttDateTimeUtils { public static Map<String, Integer> DateToEach(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); Map<String, Integer> values = new HashMap(); values.put("year", calendar.get(1) - 2000); values.put("month", calendar.get(2) + 1); values.put("day", calendar.get(5)); values.put("week", calendar.get(7) - 1); values.put("hour", calendar.get(11)); values.put("minute", calendar.get(12)); values.put("second", calendar.get(13)); return values; } }
UTF-8
Java
1,049
6ef6c1a33709535feb908feb26322f87488bf49f.svn-base
Java
[ { "context": "il.HashMap;\nimport java.util.Map;\n\n/**\n * @Author:jidi\n * @Date:2019/04/17 15:01\n * @Description:\n **/\np", "end": 398, "score": 0.9995999932289124, "start": 394, "tag": "USERNAME", "value": "jidi" } ]
null
[]
package com.rz.iot.think.mqtt.util; import com.rz.iot.think.mqtt.model.ConcentratorMessageBase; import com.rz.iot.think.mqtt.model.report.ConcentratorAppointParamReport; import com.rz.iot.utils.RzIotDatetime; import com.rz.iot.utils.RzIotDigit; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * @Author:jidi * @Date:2019/04/17 15:01 * @Description: **/ public class MqttDateTimeUtils { public static Map<String, Integer> DateToEach(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); Map<String, Integer> values = new HashMap(); values.put("year", calendar.get(1) - 2000); values.put("month", calendar.get(2) + 1); values.put("day", calendar.get(5)); values.put("week", calendar.get(7) - 1); values.put("hour", calendar.get(11)); values.put("minute", calendar.get(12)); values.put("second", calendar.get(13)); return values; } }
1,049
0.673975
0.647283
34
29.852942
20.311012
73
false
false
0
0
0
0
0
0
0.882353
false
false
11
a6cad2d5fba1ef0b188d9227a163419e1adea60b
32,710,470,983,020
86858caed98add37cc44012634cfb212dbb00884
/OOPTest/src/com/doug/hamburger.java
661c47ccd3dbb4ecb9a7ae426b59a8cb11883edc
[]
no_license
allogene/JavaPractice
https://github.com/allogene/JavaPractice
a17386363a91c0f58ce71582237cb4014ef9c139
7d753ad243007c017835ceaa9d034c03036e1194
refs/heads/master
2020-12-02T18:04:10.757000
2017-07-06T20:44:00
2017-07-06T20:44:00
96,462,837
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.doug; /** * Created by Acer on 5/30/2017. */ public class hamburger { private String meat, rollType; private double BurgerPrice, additionsSubTotal; private int numCondiments = 4, maxCondiments = 4; private AdditionList additionItem = new AdditionList(); private AdditionList[] additonNamesPrice = new AdditionList[6]; public hamburger(String meat, String rollType, double price, int numCondiments, int maxCondiments) { this.meat = meat; this.rollType = rollType; this.BurgerPrice = price; this.numCondiments = numCondiments; this.maxCondiments = maxCondiments; } public void addCondiment(condiment Condiment) { addCondiment(Condiment, this.maxCondiments); } public void removeCondiment(condiment Condiment) { removeCondiment(Condiment, this.numCondiments); } public void addCondiment(condiment Condiment, int numCondiments) { if (this.numCondiments > 0) { System.out.println("Adding " + Condiment.getName() + " to burger @ a cost of $" + Condiment.getPrice()); this.additionsSubTotal += Condiment.getPrice(); // System.out.println("numCondiments value: " + numCondiments); // System.out.println("this.numCondiments value: " + this.numCondiments); int i = (numCondiments - this.numCondiments); // System.out.println("index value: " + i); this.additionItem.setName(Condiment.getName()); this.additionItem.setPrice(Condiment.getPrice()); addAdditonNamesPrice(this.additionItem,i); this.numCondiments--; } else { System.out.println("Already added maximum number of condiments allowed."); } } public void removeCondiment(condiment Condiment, int numCondiments) { if (this.numCondiments < 5) { System.out.println("Removing " + Condiment.getName() + " to burger @ a cost of $" + Condiment.getPrice()); this.additionsSubTotal -= Condiment.getPrice(); this.numCondiments++; //TO DO: Remove from additionNamesPrice array } else { System.out.println("No condiments have been added."); } } public String getMeat() { return meat; } public String getRollType() { return rollType; } public double getBurgerPrice() { return BurgerPrice; } public int getNumCondiments() { return numCondiments; } public void addAdditionsSubTotal(double price) { this.additionsSubTotal += price; } public void removeAdditionsSubTotal(double price) { this.additionsSubTotal -= price; } public double getTotalPrice() { return additionsSubTotal + BurgerPrice; } public double getAdditionsSubTotal() { return additionsSubTotal; } public String printAdditonNamesPrice() { for (int x = 0; x < this.maxCondiments; x++){ AdditionList tempItem; // System.out.println("x: " + x); tempItem = this.additonNamesPrice[x]; System.out.println("Addition " + tempItem.getName() + " Price = $" + tempItem.getPrice()); } return ""; } public void addAdditonNamesPrice(AdditionList additionItem, int index) { for(int x = 0; x <= index; x++){ AdditionList temp = this.additonNamesPrice[x]; } System.out.println("item name: "+ additionItem.getName() + " price: " + additionItem.getPrice()); this.additonNamesPrice[index] = additionItem; } }
UTF-8
Java
3,639
java
hamburger.java
Java
[ { "context": "package com.doug;\n\n/**\n * Created by Acer on 5/30/2017.\n */\npublic class hamburger {\n pr", "end": 41, "score": 0.9786747694015503, "start": 37, "tag": "NAME", "value": "Acer" } ]
null
[]
package com.doug; /** * Created by Acer on 5/30/2017. */ public class hamburger { private String meat, rollType; private double BurgerPrice, additionsSubTotal; private int numCondiments = 4, maxCondiments = 4; private AdditionList additionItem = new AdditionList(); private AdditionList[] additonNamesPrice = new AdditionList[6]; public hamburger(String meat, String rollType, double price, int numCondiments, int maxCondiments) { this.meat = meat; this.rollType = rollType; this.BurgerPrice = price; this.numCondiments = numCondiments; this.maxCondiments = maxCondiments; } public void addCondiment(condiment Condiment) { addCondiment(Condiment, this.maxCondiments); } public void removeCondiment(condiment Condiment) { removeCondiment(Condiment, this.numCondiments); } public void addCondiment(condiment Condiment, int numCondiments) { if (this.numCondiments > 0) { System.out.println("Adding " + Condiment.getName() + " to burger @ a cost of $" + Condiment.getPrice()); this.additionsSubTotal += Condiment.getPrice(); // System.out.println("numCondiments value: " + numCondiments); // System.out.println("this.numCondiments value: " + this.numCondiments); int i = (numCondiments - this.numCondiments); // System.out.println("index value: " + i); this.additionItem.setName(Condiment.getName()); this.additionItem.setPrice(Condiment.getPrice()); addAdditonNamesPrice(this.additionItem,i); this.numCondiments--; } else { System.out.println("Already added maximum number of condiments allowed."); } } public void removeCondiment(condiment Condiment, int numCondiments) { if (this.numCondiments < 5) { System.out.println("Removing " + Condiment.getName() + " to burger @ a cost of $" + Condiment.getPrice()); this.additionsSubTotal -= Condiment.getPrice(); this.numCondiments++; //TO DO: Remove from additionNamesPrice array } else { System.out.println("No condiments have been added."); } } public String getMeat() { return meat; } public String getRollType() { return rollType; } public double getBurgerPrice() { return BurgerPrice; } public int getNumCondiments() { return numCondiments; } public void addAdditionsSubTotal(double price) { this.additionsSubTotal += price; } public void removeAdditionsSubTotal(double price) { this.additionsSubTotal -= price; } public double getTotalPrice() { return additionsSubTotal + BurgerPrice; } public double getAdditionsSubTotal() { return additionsSubTotal; } public String printAdditonNamesPrice() { for (int x = 0; x < this.maxCondiments; x++){ AdditionList tempItem; // System.out.println("x: " + x); tempItem = this.additonNamesPrice[x]; System.out.println("Addition " + tempItem.getName() + " Price = $" + tempItem.getPrice()); } return ""; } public void addAdditonNamesPrice(AdditionList additionItem, int index) { for(int x = 0; x <= index; x++){ AdditionList temp = this.additonNamesPrice[x]; } System.out.println("item name: "+ additionItem.getName() + " price: " + additionItem.getPrice()); this.additonNamesPrice[index] = additionItem; } }
3,639
0.622973
0.619126
109
32.376148
29.230118
118
false
false
0
0
0
0
0
0
0.559633
false
false
11
ee02fe23acb52691215a5903f5b56019b147ac47
901,943,176,094
6172d3ea09e1b0ad4232d6906658191330f973f5
/Lab6_TSURKAN_V_Google/src/test/java/pages/frameworks/GoogleEngine.java
4ae1312928ececa5754f9a307c663a155bd435f4
[]
no_license
KPI-Testing/Testing2017-18
https://github.com/KPI-Testing/Testing2017-18
3fb57448a5dcd547472bf06f86713be4ea0b7727
6217396e72997a8a8a06a3224ad5bf2ae3444524
refs/heads/master
2022-12-28T15:44:24.296000
2018-05-03T07:53:14
2018-05-03T07:53:14
106,281,083
0
9
null
false
2020-10-13T00:00:36
2017-10-09T12:31:34
2018-05-03T07:56:36
2020-10-13T00:00:35
240,363
0
21
27
Java
false
false
package pages.frameworks; import org.apache.commons.io.FileUtils; import org.openqa.selenium.*; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.FindBys; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.FluentWait; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; import java.util.NoSuchElementException; import java.util.concurrent.TimeUnit; import static junit.framework.TestCase.assertTrue; public class GoogleEngine { private ChromeDriverEx driver; public GoogleEngine(ChromeDriverEx driver){ this.driver = driver; PageFactory.initElements(driver, this); } @FindBy(name = "btnK") private WebElement SubmitSearch; @FindBy(id = "lst-ib") private WebElement TextLine; @FindBy(id = "pnnext") private WebElement NextPage; @FindBy(id = "pnprev") private WebElement PreviousPage; public GoogleEngine Search(String request) { System.out.println("Search for \"" + request + "\""); SetSearch(request).SearchButtonPress(); return this; } public GoogleEngine SetSearch(String request) { if (request == null) return this; TextLine.sendKeys(request); return this; } public GoogleEngine SearchButtonPress() { SubmitSearch.sendKeys(Keys.ENTER); return this; } public GoogleEngine GoToNext() { NextPage.sendKeys(Keys.ENTER); return this; } public GoogleEngine GoToPrevious() { PreviousPage.sendKeys(Keys.ENTER); return this; } public GoogleEngine PageLinkSearch(String link) throws Exception { int pageNumber = 1; if (!driver.findElement(By.id("pnnext")).getText().contains("Следующая")) { System.out.println("No pages or captcha"); assert (false); } boolean notFinded = true; do { for (int f = 0; f < driver.findElements(By.className("_Rm")).size(); f++) { if (notFinded && driver.findElements(By.className("_Rm")).get(f).getText().contains(link)) { System.out.println("Your link \"" + link + "\" on page: " + pageNumber); System.out.println("On first page: " + ((pageNumber == 1) ? "True" : "False")); notFinded = false; Calendar calendar = new GregorianCalendar(); String s = new SimpleDateFormat("dd_MM_yyyy_HH_mm_SS").format(calendar.getTime()); System.out.println("page_number is " + pageNumber); File file = driver.getFullScreenshotAs(OutputType.FILE); GoogleEngine.get_screenshot( "YES"+link+s + ".",file); } } if (driver.findElements(By.className("navend")).get(1).getText().contains("Следующая")) { GoToNext(); pageNumber++; } } while (notFinded && driver.findElements(By.className("navend")).get(1).getText().contains("Следующая")); if (notFinded) { System.out.println("\""+link + "\" was not found"); for (int i = pageNumber; i>0;i--) { Calendar calendar = new GregorianCalendar(); String s = new SimpleDateFormat("dd_MM_yyyy_HH_mm_SS").format(calendar.getTime()); File file = driver.getFullScreenshotAs(OutputType.FILE); GoogleEngine.get_screenshot("NO" + i + link + s + ".", file); if (i!=1) { GoToPrevious(); } } } return this; } public static void get_screenshot(String name, File scrFile)throws Exception{ try { FileUtils.copyFile(scrFile, new File(name + "png")); } catch (IOException e) { System.out.println(e.getMessage()); } } }
UTF-8
Java
4,221
java
GoogleEngine.java
Java
[]
null
[]
package pages.frameworks; import org.apache.commons.io.FileUtils; import org.openqa.selenium.*; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.FindBys; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.FluentWait; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; import java.util.NoSuchElementException; import java.util.concurrent.TimeUnit; import static junit.framework.TestCase.assertTrue; public class GoogleEngine { private ChromeDriverEx driver; public GoogleEngine(ChromeDriverEx driver){ this.driver = driver; PageFactory.initElements(driver, this); } @FindBy(name = "btnK") private WebElement SubmitSearch; @FindBy(id = "lst-ib") private WebElement TextLine; @FindBy(id = "pnnext") private WebElement NextPage; @FindBy(id = "pnprev") private WebElement PreviousPage; public GoogleEngine Search(String request) { System.out.println("Search for \"" + request + "\""); SetSearch(request).SearchButtonPress(); return this; } public GoogleEngine SetSearch(String request) { if (request == null) return this; TextLine.sendKeys(request); return this; } public GoogleEngine SearchButtonPress() { SubmitSearch.sendKeys(Keys.ENTER); return this; } public GoogleEngine GoToNext() { NextPage.sendKeys(Keys.ENTER); return this; } public GoogleEngine GoToPrevious() { PreviousPage.sendKeys(Keys.ENTER); return this; } public GoogleEngine PageLinkSearch(String link) throws Exception { int pageNumber = 1; if (!driver.findElement(By.id("pnnext")).getText().contains("Следующая")) { System.out.println("No pages or captcha"); assert (false); } boolean notFinded = true; do { for (int f = 0; f < driver.findElements(By.className("_Rm")).size(); f++) { if (notFinded && driver.findElements(By.className("_Rm")).get(f).getText().contains(link)) { System.out.println("Your link \"" + link + "\" on page: " + pageNumber); System.out.println("On first page: " + ((pageNumber == 1) ? "True" : "False")); notFinded = false; Calendar calendar = new GregorianCalendar(); String s = new SimpleDateFormat("dd_MM_yyyy_HH_mm_SS").format(calendar.getTime()); System.out.println("page_number is " + pageNumber); File file = driver.getFullScreenshotAs(OutputType.FILE); GoogleEngine.get_screenshot( "YES"+link+s + ".",file); } } if (driver.findElements(By.className("navend")).get(1).getText().contains("Следующая")) { GoToNext(); pageNumber++; } } while (notFinded && driver.findElements(By.className("navend")).get(1).getText().contains("Следующая")); if (notFinded) { System.out.println("\""+link + "\" was not found"); for (int i = pageNumber; i>0;i--) { Calendar calendar = new GregorianCalendar(); String s = new SimpleDateFormat("dd_MM_yyyy_HH_mm_SS").format(calendar.getTime()); File file = driver.getFullScreenshotAs(OutputType.FILE); GoogleEngine.get_screenshot("NO" + i + link + s + ".", file); if (i!=1) { GoToPrevious(); } } } return this; } public static void get_screenshot(String name, File scrFile)throws Exception{ try { FileUtils.copyFile(scrFile, new File(name + "png")); } catch (IOException e) { System.out.println(e.getMessage()); } } }
4,221
0.570577
0.568908
141
27.74468
28.564821
114
false
false
0
0
0
0
0
0
0.475177
false
false
11
6294ae25f5480e5be34905ce27471718988795e5
27,994,596,846,974
e41f4928bfa090cda719d18bc097c4b7f443d7d0
/app/src/main/java/com/hdu/newe/here/page/base/BasePresenter.java
339f54488d0081c1bdd17c8a26529fbec4038c3b
[ "Apache-2.0" ]
permissive
JaylenHsieh/Here
https://github.com/JaylenHsieh/Here
bd9f0b956dbb9a47fd1029a8839809fd52755e3b
d0759420365ab396c75008a67924cd940e9f52ce
refs/heads/master
2018-11-02T21:44:53.990000
2018-10-18T07:16:23
2018-10-18T07:16:23
111,284,989
4
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.hdu.newe.here.page.base; /** * * @author Jaylen Hsieh * @date 2017/11/19 */ public interface BasePresenter { void onCreate(); void onStart(); void onResume(); void onPause(); void onStop(); void onDestroy(); }
UTF-8
Java
259
java
BasePresenter.java
Java
[ { "context": "ge com.hdu.newe.here.page.base;\n\n/**\n *\n * @author Jaylen Hsieh\n * @date 2017/11/19\n */\n\npublic interface BasePre", "end": 68, "score": 0.9998636841773987, "start": 56, "tag": "NAME", "value": "Jaylen Hsieh" } ]
null
[]
package com.hdu.newe.here.page.base; /** * * @author <NAME> * @date 2017/11/19 */ public interface BasePresenter { void onCreate(); void onStart(); void onResume(); void onPause(); void onStop(); void onDestroy(); }
253
0.598456
0.567568
23
10.26087
11.60666
36
false
false
0
0
0
0
0
0
0.304348
false
false
11
0eafe8228963289b798f047df707e722b60ccc18
1,752,346,699,109
c3bbd7f87705306b6148e001cd2917db1e91364c
/dawn-web-manager/src/main/java/com/dawn/service/SysRolePermissionService.java
b307e1ddd1775917157dcc7957c115d8011c906c
[]
no_license
wuenbaiyila/dawn
https://github.com/wuenbaiyila/dawn
90c3af2dd0351c6bfc34a8f1423513e6781e9be5
cf04f55a6f7d02e6c421e8eedd6ca66f8dcdf7d5
refs/heads/master
2021-05-05T00:58:16.604000
2018-03-12T15:16:46
2018-03-12T15:16:46
119,526,146
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dawn.service; import java.util.List; import com.dawn.pojo.SysRolePermission; public interface SysRolePermissionService { public int addSysRolePermissionService(SysRolePermission sysRolePermission); // 根据角色id查询权限菜单 public List<SysRolePermission> queryByRoleId(String roleId); }
UTF-8
Java
318
java
SysRolePermissionService.java
Java
[]
null
[]
package com.dawn.service; import java.util.List; import com.dawn.pojo.SysRolePermission; public interface SysRolePermissionService { public int addSysRolePermissionService(SysRolePermission sysRolePermission); // 根据角色id查询权限菜单 public List<SysRolePermission> queryByRoleId(String roleId); }
318
0.825503
0.825503
14
20.285715
24.820581
77
false
false
0
0
0
0
0
0
0.571429
false
false
11
f8fcb3cab028c5a94cddbd2f5cba7b6639ca2b50
27,728,308,882,530
08037bd6af23e0adf00971169cb108082d6d2b3e
/src/org/tcl/game/gui/load/DataLoad.java
5b32ac06b4a70aab3bd597b8debd07c0ce0b66cd
[]
no_license
tanghao0123/MagicBoardGame
https://github.com/tanghao0123/MagicBoardGame
943b0d83b9a1e059c163a49832858b556753ea03
736a48c17cf951267bdceab9b2d2af61b1fd2c3a
refs/heads/master
2022-11-22T00:02:08.982000
2020-07-02T10:58:01
2020-07-02T10:58:01
276,611,189
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.tcl.game.gui.load; /** * 数据加载 * @author 李婷妍 */ public class DataLoad { public DataLoad(String path){ } }
UTF-8
Java
144
java
DataLoad.java
Java
[ { "context": "ge org.tcl.game.gui.load;\n\n/**\n * 数据加载\n * @author 李婷妍\n */\npublic class DataLoad {\n public DataLoad(S", "end": 58, "score": 0.9997002482414246, "start": 55, "tag": "NAME", "value": "李婷妍" } ]
null
[]
package org.tcl.game.gui.load; /** * 数据加载 * @author 李婷妍 */ public class DataLoad { public DataLoad(String path){ } }
144
0.615385
0.615385
11
10.818182
11.75367
33
false
false
0
0
0
0
0
0
0.090909
false
false
11
7a4b4d58f60de7630dceda7bd1be05babf9b4980
9,869,834,859,975
5d0dad9f86fa4442c26f383992337837390f4172
/app/src/main/java/com/example/rishabh/UploadAdapter.java
475631562582a4579d6d3d74aa1561e6c5ed8d8d
[]
no_license
lokiore/VConnect
https://github.com/lokiore/VConnect
8e21ca4b95452dac4d9734852a8830de05f5b12c
e87f412ed151df0c3a5307825d947653321fd1a2
refs/heads/master
2020-03-10T01:06:05.552000
2018-04-12T20:46:15
2018-04-12T20:46:15
129,100,442
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.rishabh; import android.app.Activity; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.ArrayList; /** * Created by lokiore on 11/4/18. */ public class UploadAdapter extends ArrayAdapter<Upload> { public UploadAdapter(Activity context, ArrayList<Upload> uploads) { super(context, 0, uploads); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View listViewItem = convertView; if (listViewItem == null) { listViewItem = LayoutInflater.from(getContext()).inflate(R.layout.user_item, parent, false); } //Timeline timeline = getItem(position); Upload upload = getItem(position); ImageView timelineProfilePhoto = listViewItem.findViewById(R.id.upload_profile_photo); //timelineProfilePhoto.setImageResource(timeline.getProfilePic()); Uri profUri = Uri.parse(upload.getImageUrl()); Picasso.get().load(profUri).into(timelineProfilePhoto); TextView timelineUsername = listViewItem.findViewById(R.id.upload_username); timelineUsername.setText(upload.getName()); return listViewItem; } }
UTF-8
Java
1,550
java
UploadAdapter.java
Java
[ { "context": "o;\n\nimport java.util.ArrayList;\n\n/**\n * Created by lokiore on 11/4/18.\n */\n\npublic class UploadAdapter exten", "end": 482, "score": 0.9996424317359924, "start": 475, "tag": "USERNAME", "value": "lokiore" } ]
null
[]
package com.example.rishabh; import android.app.Activity; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.ArrayList; /** * Created by lokiore on 11/4/18. */ public class UploadAdapter extends ArrayAdapter<Upload> { public UploadAdapter(Activity context, ArrayList<Upload> uploads) { super(context, 0, uploads); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View listViewItem = convertView; if (listViewItem == null) { listViewItem = LayoutInflater.from(getContext()).inflate(R.layout.user_item, parent, false); } //Timeline timeline = getItem(position); Upload upload = getItem(position); ImageView timelineProfilePhoto = listViewItem.findViewById(R.id.upload_profile_photo); //timelineProfilePhoto.setImageResource(timeline.getProfilePic()); Uri profUri = Uri.parse(upload.getImageUrl()); Picasso.get().load(profUri).into(timelineProfilePhoto); TextView timelineUsername = listViewItem.findViewById(R.id.upload_username); timelineUsername.setText(upload.getName()); return listViewItem; } }
1,550
0.723871
0.72
53
28.245283
27.89394
104
false
false
0
0
0
0
0
0
0.622642
false
false
11
a9daff37da780cbc2b26e64e9b8e8c2e4967b925
14,482,629,735,010
b610d289434a9567693df38eb514c493667fd096
/app/src/main/java/com/courseproject/fragments/EducationCardFragment.java
d51a89b53391c5ded9f1e64e9a407e28878f57cc
[]
no_license
AndrewBlinets/CourseWork-1
https://github.com/AndrewBlinets/CourseWork-1
2bdb7157109674b1aef16a9bca02c9a515595c85
f723b83ab3b85888a6845add65c9e9e17f62752a
refs/heads/master
2021-08-27T19:55:44.254000
2017-11-28T06:13:26
2017-11-28T06:13:26
111,071,729
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.courseproject.fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.courseproject.R; import com.courseproject.constants.ConstantsForIntent; import com.courseproject.dao.StudentDataBaseHadler; import com.courseproject.model.student.Student; //фрагмент для вывода основной информации о студента public class EducationCardFragment extends Fragment { private static final int LAYOUT = R.layout.fragment_education_card; private View view; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(LAYOUT,container,false); Bundle bundle = this.getArguments(); Student student = new StudentDataBaseHadler(getContext()).getById(bundle.getLong(ConstantsForIntent.idStudent));// получения инфы из БД ((TextView)view.findViewById(R.id.firstName)).setText(student.getName()); ((TextView)view.findViewById(R.id.secondName)).setText(student.getSecondName()); ((TextView)view.findViewById(R.id.surName)).setText(student.getSurName()); ((TextView)view.findViewById(R.id.groupNumber)).setText(student.getGroup().getName()); return view; } }
UTF-8
Java
1,477
java
EducationCardFragment.java
Java
[]
null
[]
package com.courseproject.fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.courseproject.R; import com.courseproject.constants.ConstantsForIntent; import com.courseproject.dao.StudentDataBaseHadler; import com.courseproject.model.student.Student; //фрагмент для вывода основной информации о студента public class EducationCardFragment extends Fragment { private static final int LAYOUT = R.layout.fragment_education_card; private View view; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(LAYOUT,container,false); Bundle bundle = this.getArguments(); Student student = new StudentDataBaseHadler(getContext()).getById(bundle.getLong(ConstantsForIntent.idStudent));// получения инфы из БД ((TextView)view.findViewById(R.id.firstName)).setText(student.getName()); ((TextView)view.findViewById(R.id.secondName)).setText(student.getSecondName()); ((TextView)view.findViewById(R.id.surName)).setText(student.getSurName()); ((TextView)view.findViewById(R.id.groupNumber)).setText(student.getGroup().getName()); return view; } }
1,477
0.766949
0.766243
32
43.25
33.258457
143
false
false
0
0
0
0
0
0
0.8125
false
false
11
a9f29bd8daaf27b5047b142ec185bed5a6fe555a
5,712,306,506,771
52a5cc4cfe81abd1165e3e5ff25a2f4893f175eb
/SciCumulusCore/src/main/java/chiron/cloud/CloudUtils.java
cfc298759991f1fe7fddf99414a96f0573e6073f
[]
no_license
curiousTauseef/SciCumulus
https://github.com/curiousTauseef/SciCumulus
45542f66d7ba6ed0f6c0ff61290a9839af604fba
f5072506ae2d3426c029a91caa275a3ac6649b11
refs/heads/master
2022-09-20T12:58:51.553000
2020-04-14T20:00:42
2020-04-14T20:00:42
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package chiron.cloud; import chiron.EMachine; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.DescribeInstancesResult; import com.amazonaws.services.ec2.model.Filter; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.Reservation; import chiron.XMLReader; import com.amazonaws.services.ec2.model.Tag; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * * @author vitor */ public class CloudUtils { public static final String JDBC_DRIVER = "org.postgresql.Driver"; public static final String clusterLabelName = "Name"; public static final String clusterNodeType = "NodeType"; public static final String clusterHeaderName = "SC-"; public static final String keyHeaderName = clusterHeaderName + "Key-"; public static final String securityGroupHeaderName = clusterHeaderName + "SG-"; public static final String instanceStateNameLabel = "instance-state-name"; public static final List<String> runningInstanceStates = new ArrayList<String>(Arrays.asList("running","pending","shutting-down","stopping")); public static final String instanceTypeNameLabel = "instance-type"; public static final String securityGroupNameLabel = "group-name"; public static final String keyNameLabel = "key-name"; public static final String instanceNameLabel = "tag-value"; public static final String networkInterfaceAttachmentStatus = "network-interface.attachment.status"; public static final String networkInterfaceStatus = "network-interface.status"; private static final String identation = " "; public static void printInitialMessage(){ System.out.println("####################################################"); System.out.println("################ SciCumulus Starter ################"); System.out.println("####################################################"); } public static void printOperation(String text) { System.out.println("------------------ " + text + " ------------------"); } public static void printFirstLevel(String text){ System.out.println(text); } public static void printSecondLevel(String text){ System.out.println(identation + text); } public static List<Filter> createFilter(List<Filter> filters, String key, List<String> values){ Filter newFilter = new Filter(key); newFilter.setValues(values); filters.add(newFilter); return filters; } // public static boolean hasAliveInstanceFromCluster(AmazonEC2Client amazonClient, String clusterName) { // DescribeInstancesResult result = getAliveInstancesFromCluster(amazonClient, clusterName); // // for (Reservation reservation : result.getReservations()) { // int instances = reservation.getInstances().size(); // if(instances > 0){ // return true; // } // } // // return false; // } // // public static DescribeSecurityGroupsResult getAliveSecurityGroupFromACluster(AmazonEC2Client amazonClient, XMLReader configurationFile){ // DescribeSecurityGroupsRequest iRequest = new DescribeSecurityGroupsRequest(); // List<Filter> filter = new ArrayList<Filter>(); // // List<String> values = new ArrayList<String>(); // values.add(getSecurityGroupName(configurationFile.clusterName)); // createFilter(filter, securityGroupNameLabel, values); // iRequest.setFilters(filter); // // return amazonClient.describeSecurityGroups(iRequest); // } // // public static boolean hasAliveSecurityGroupFromCluster(AmazonEC2Client amazonClient, XMLReader configurationFile) { // DescribeSecurityGroupsResult result = getAliveSecurityGroupFromACluster(amazonClient, configurationFile); // return (result.getSecurityGroups().size()>0); // } // // public static DescribeKeyPairsResult getAliveKeyPairFromACluster(AmazonEC2Client amazonClient, XMLReader configurationFile){ // DescribeKeyPairsRequest iRequest = new DescribeKeyPairsRequest(); // List<Filter> filter = new ArrayList<Filter>(); // // List<String> values = new ArrayList<String>(); // values.add(getKeyPairName(configurationFile.clusterName)); // createFilter(filter, keyNameLabel, values); // iRequest.setFilters(filter); // // return amazonClient.describeKeyPairs(iRequest); // } // // public static boolean hasAliveKeyPairFromCluster(AmazonEC2Client amazonClient, XMLReader configurationFile) { // DescribeKeyPairsResult result = getAliveKeyPairFromACluster(amazonClient, configurationFile); // return (result.getKeyPairs().size()>0); // } // // public static DescribeInstancesResult getAliveInstancesFromCluster(AmazonEC2Client amazonClient, String clusterName){ // List<Filter> filters = new ArrayList<Filter>(); // createFilter(filters, instanceStateNameLabel, runningInstanceStates); // // ArrayList<Tag> tags = new ArrayList<Tag>(); // tags.add(new Tag(clusterLabelName, getVirtualMachinesName(clusterName))); // // DescribeInstancesRequest iRequest = getDescribeInstancesRequest(tags, filters); // // return amazonClient.describeInstances(iRequest); // } // // public static DescribeInstancesResult getAliveInstancesFromClusterByType(AmazonEC2Client amazonClient, String clusterName, VirtualMachineType vmType){ // List<Filter> filters = new ArrayList<Filter>(); // createFilter(filters, instanceStateNameLabel, runningInstanceStates); // // List<String> values = new ArrayList<String>(); // values.add(vmType.getType()); // createFilter(filters, instanceTypeNameLabel, values); // // ArrayList<Tag> tags = new ArrayList<Tag>(); // tags.add(new Tag(clusterLabelName, getVirtualMachinesName(clusterName))); // // DescribeInstancesRequest iRequest = getDescribeInstancesRequest(tags, filters); // // return amazonClient.describeInstances(iRequest); // } // // public static DescribeInstancesResult getDescribeMachinesFromCluster(AmazonEC2Client amazonClient, String clusterName){ // ArrayList<Tag> tags = new ArrayList<Tag>(); // // List<Filter> filters = new ArrayList<Filter>(); // createFilter(filters, instanceStateNameLabel, runningInstanceStates); // // tags.add(new Tag(clusterLabelName, getVirtualMachinesName(clusterName))); // // DescribeInstancesRequest iRequest = getDescribeInstancesRequest(tags, filters); // // return amazonClient.describeInstances(iRequest); // } private static VirtualMachineType getVmType(XMLReader configurationFile, String instanceType) { for(VirtualMachineType type : configurationFile.vmTypes){ if(type.getType().equals(instanceType)){ VirtualMachineType retrievedType = new VirtualMachineType(type.getFinancialCost(), type.getDiskSpace(), type.getRam(), type.getGflops(), type.getPlatform(), type.getNumberOfCores()); retrievedType.setType(instanceType); return retrievedType; } } return null; } public static DescribeInstancesResult getNodesFromCluster(AmazonEC2Client amazonClient, String clusterName){ List<Filter> filters = new ArrayList<Filter>(); createFilter(filters, instanceStateNameLabel, runningInstanceStates); ArrayList<Tag> tags = new ArrayList<Tag>(); tags.add(new Tag(clusterLabelName, getVirtualMachinesName(clusterName))); tags.add(new Tag(clusterNodeType, "NODE")); DescribeInstancesRequest iRequest = getDescribeInstancesRequest(tags, filters); return amazonClient.describeInstances(iRequest); } public static ArrayList<EMachine> getMachinesFromCluster(AmazonEC2Client amazonClient, XMLReader configurationFile) { int rank = 0; ArrayList<EMachine> machines = new ArrayList<EMachine>(); DescribeInstancesResult superNode = getDescribeSuperNodeFromCluster(amazonClient, configurationFile.clusterName); for(Reservation reservation : superNode.getReservations()){ for(Instance instance : reservation.getInstances()){ VirtualMachineType vmType = CloudUtils.getVmType(configurationFile, instance.getInstanceType()); EMachine mac = new EMachine(rank, instance.getPublicDnsName(), instance.getPublicIpAddress(), instance.getPrivateIpAddress(), vmType.getType(), vmType.getNumberOfCores()); machines.add(mac); rank++; } } DescribeInstancesResult nodes = getNodesFromCluster(amazonClient, configurationFile.clusterName); for(Reservation reservation : nodes.getReservations()){ for(Instance instance : reservation.getInstances()){ VirtualMachineType vmType = CloudUtils.getVmType(configurationFile, instance.getInstanceType()); EMachine mac = new EMachine(rank, instance.getPublicDnsName(), instance.getPublicIpAddress(), instance.getPrivateIpAddress(), vmType.getType(), vmType.getNumberOfCores()); machines.add(mac); rank++; } } return machines; } // public static boolean hasVMType(ArrayList<VirtualMachineType> vmTypes, VirtualMachineType vmType) { // for(VirtualMachineType machine : vmTypes){ // if(machine.getType().equals(vmType.getType())){ // return true; // } // } // // return false; // } // // public static VirtualMachineType getVmType(ArrayList<VirtualMachineType> vmTypes, VirtualMachineType vmType) { // for(VirtualMachineType machine : vmTypes){ // if(machine.getType().equals(vmType.getType())){ // return machine; // } // } // // return null; // } // // public static VirtualMachineType getVmType(List<VirtualMachineType> vmTypes, String instanceType) { // for(VirtualMachineType type : vmTypes){ // if(type.getType().equals(instanceType)){ // VirtualMachineType retrievedType = new VirtualMachineType(type.getFinancialCost(), // type.getDiskSpace(), type.getRam(), type.getGflops(), type.getPlatform(), type.getNumberOfCores()); // retrievedType.setType(instanceType); // return retrievedType; // } // } // // return null; // } // // public static String[] splitAndDiscard(String s, String regex){ // String[] ret = s.split(regex); // String aux = new String(""); // for(int i = 0; i< ret.length; i++){ // if(!(ret[i].matches(""))){ // aux+=ret[i]+regex; // } // } // ret = aux.split(regex); // return ret; // } // // public static String[] splitAndDiscard(String s, String regex1, String regex2){ // String[] ret = s.split(regex1); // String aux = new String(""); // for(int i = 0; i< ret.length; i++){ // if(!(ret[i].matches(""))){ // if(!(ret[i].matches(regex2))){ // aux+=ret[i]+regex1; // } // } // } // ret = aux.split(regex1); // return ret; // } // // public static boolean MachineListContains(String name, ArrayList<EMachine> machines){ // for(int i=0; i<machines.size(); i++){ // if(machines.get(i).name.matches(name)) return true; // } // return false; // } // // public static boolean machineListIsAllReady(ArrayList<EMachine> machines){ // for(int i=0; i<machines.size(); i++){ // EMachine mac = machines.get(i); // if(mac.publicDNS.matches("pending")) return false; // if(mac.publicDNS == null) return false; // if(mac.publicDNS.matches("")) return false; // } // return true; // } // // public static EMachine getMachineByName(ArrayList<EMachine> machines, String name){ // EMachine mach=null; // for(int i=0; i<machines.size(); i++){ // if(!(machines.get(i).name.matches(name)))mach = machines.get(i); // } // return mach; // } // // public static ArrayList<VirtualMachineType> getVirtualMachineTypesFromCluster(EnvironmentConfiguration environment) { // DescribeInstancesResult result = getAliveInstancesFromCluster(environment.amazonClient, environment.getClusterName()); // ArrayList<VirtualMachineType> vmTypes = new ArrayList<VirtualMachineType>(); // // for(Reservation reservation : result.getReservations()){ // for(Instance instance : reservation.getInstances()){ // VirtualMachineType vmType = CloudUtils.getVmType(environment.getVMTypes(), instance.getInstanceType()); // if(!hasVMType(vmTypes, vmType)){ // vmType.setAmountInstantiatedVM(1); // vmTypes.add(vmType); // }else{ // VirtualMachineType virtualMachine = getVmType(vmTypes, vmType); // virtualMachine.addAmountInstantiatedVM(); // } // } // } // // return vmTypes; // } // // public static MachineComparison compareInstanciatedMachines(ArrayList<VirtualMachineType> instanciatedMachines, List<VirtualMachineType> newConfMachines) { // MachineComparison comparison = new MachineComparison(); // comparison.setEqualToInstanciatedMachines(true); // // for(VirtualMachineType newVMType : newConfMachines){ // VirtualMachineType instVMType = getMachineType(instanciatedMachines, newVMType); // // if(instVMType==null && newVMType.getAmountInstantiatedVM()!=0){ // comparison.setEqualToInstanciatedMachines(false); // // VirtualMachineType vmType = new VirtualMachineType(newVMType.getFinancialCost(), // newVMType.getDiskSpace(), newVMType.getRam(), newVMType.getGflops(), // newVMType.getPlatform(), newVMType.getNumberOfCores()); // vmType.setType(newVMType.getType()); // vmType.setAmountInstantiatedVM(newVMType.getAmountInstantiatedVM()); // comparison.addMachinesToAllocate(newVMType); // }else if(instVMType!=null){ // int diffMachines = newVMType.getAmountInstantiatedVM() - instVMType.getAmountInstantiatedVM(); // if(diffMachines > 0){ // comparison.setEqualToInstanciatedMachines(false); // // VirtualMachineType vmType = new VirtualMachineType(newVMType.getFinancialCost(), // newVMType.getDiskSpace(), newVMType.getRam(), newVMType.getGflops(), // newVMType.getPlatform(), newVMType.getNumberOfCores()); // vmType.setType(newVMType.getType()); // vmType.setAmountInstantiatedVM(diffMachines); // comparison.addMachinesToAllocate(vmType); // }else if(diffMachines < 0){ // comparison.setEqualToInstanciatedMachines(false); // VirtualMachineType vmType = new VirtualMachineType(newVMType.getFinancialCost(), // newVMType.getDiskSpace(), newVMType.getRam(), newVMType.getGflops(), // newVMType.getPlatform(), newVMType.getNumberOfCores()); // vmType.setType(newVMType.getType()); // vmType.setAmountInstantiatedVM(Math.abs(diffMachines)); // comparison.addMachinesToDeallocate(vmType); // } // } // } // // for(VirtualMachineType instVMType : instanciatedMachines){ // VirtualMachineType newVMType = getMachineType(newConfMachines, instVMType); // if(newVMType == null){ // comparison.setEqualToInstanciatedMachines(false); // // VirtualMachineType vmType = new VirtualMachineType(instVMType.getFinancialCost(), // instVMType.getDiskSpace(), instVMType.getRam(), instVMType.getGflops(), // instVMType.getPlatform(), instVMType.getNumberOfCores()); // vmType.setType(instVMType.getType()); // vmType.setAmountInstantiatedVM(instVMType.getAmountInstantiatedVM()); // comparison.addMachinesToDeallocate(instVMType); // } // } // // return comparison; // } // // private static VirtualMachineType getMachineType(List<VirtualMachineType> machinesType, VirtualMachineType vmType){ // for(VirtualMachineType iVMType : machinesType){ // if(iVMType.getType().equals(vmType.getType())){ // return iVMType; // } // } // // return null; // } public static String getVirtualMachinesName(String clusterName){ return CloudUtils.clusterHeaderName + clusterName; } // public static String getKeyPairName(String clusterName){ // return CloudUtils.keyHeaderName + clusterName; // } // // public static String getSecurityGroupName(String clusterName){ // return CloudUtils.securityGroupHeaderName + clusterName; // } // // public static List<String> getSecurityGroupList(String clusterName) { // List<String> securityGroups = new ArrayList<String>(); // securityGroups.add(CloudUtils.securityGroupHeaderName + clusterName); // return securityGroups; // } public static DescribeInstancesResult getDescribeSuperNodeFromCluster(AmazonEC2Client amazonClient, String clusterName){ ArrayList<Tag> tags = new ArrayList<Tag>(); List<Filter> filters = new ArrayList<Filter>(); createFilter(filters, instanceStateNameLabel, runningInstanceStates); tags.add(new Tag(clusterLabelName, getVirtualMachinesName(clusterName))); tags.add(new Tag(clusterNodeType, "SUPERNODE")); DescribeInstancesRequest iRequest = getDescribeInstancesRequest(tags, filters); return amazonClient.describeInstances(iRequest); } protected static DescribeInstancesRequest getDescribeInstancesRequest(ArrayList<Tag> tags, List<Filter> filters) { DescribeInstancesRequest request = new DescribeInstancesRequest(); for(Tag tag : tags){ Filter filter = getFilterFromTag(tag.getKey(), tag.getValue()); filters.add(filter); } request.setFilters(filters); return request; } protected static Filter getFilterFromTag(String tag, String value) { Filter filter = new Filter(); filter.setName("tag:" + tag); filter.setValues(Collections.singletonList(value)); return filter; } }
UTF-8
Java
19,868
java
CloudUtils.java
Java
[ { "context": "ections;\nimport java.util.List;\n\n/**\n *\n * @author vitor\n */\npublic class CloudUtils {\n \n public sta", "end": 580, "score": 0.9944955110549927, "start": 575, "tag": "USERNAME", "value": "vitor" } ]
null
[]
package chiron.cloud; import chiron.EMachine; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.DescribeInstancesResult; import com.amazonaws.services.ec2.model.Filter; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.Reservation; import chiron.XMLReader; import com.amazonaws.services.ec2.model.Tag; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * * @author vitor */ public class CloudUtils { public static final String JDBC_DRIVER = "org.postgresql.Driver"; public static final String clusterLabelName = "Name"; public static final String clusterNodeType = "NodeType"; public static final String clusterHeaderName = "SC-"; public static final String keyHeaderName = clusterHeaderName + "Key-"; public static final String securityGroupHeaderName = clusterHeaderName + "SG-"; public static final String instanceStateNameLabel = "instance-state-name"; public static final List<String> runningInstanceStates = new ArrayList<String>(Arrays.asList("running","pending","shutting-down","stopping")); public static final String instanceTypeNameLabel = "instance-type"; public static final String securityGroupNameLabel = "group-name"; public static final String keyNameLabel = "key-name"; public static final String instanceNameLabel = "tag-value"; public static final String networkInterfaceAttachmentStatus = "network-interface.attachment.status"; public static final String networkInterfaceStatus = "network-interface.status"; private static final String identation = " "; public static void printInitialMessage(){ System.out.println("####################################################"); System.out.println("################ SciCumulus Starter ################"); System.out.println("####################################################"); } public static void printOperation(String text) { System.out.println("------------------ " + text + " ------------------"); } public static void printFirstLevel(String text){ System.out.println(text); } public static void printSecondLevel(String text){ System.out.println(identation + text); } public static List<Filter> createFilter(List<Filter> filters, String key, List<String> values){ Filter newFilter = new Filter(key); newFilter.setValues(values); filters.add(newFilter); return filters; } // public static boolean hasAliveInstanceFromCluster(AmazonEC2Client amazonClient, String clusterName) { // DescribeInstancesResult result = getAliveInstancesFromCluster(amazonClient, clusterName); // // for (Reservation reservation : result.getReservations()) { // int instances = reservation.getInstances().size(); // if(instances > 0){ // return true; // } // } // // return false; // } // // public static DescribeSecurityGroupsResult getAliveSecurityGroupFromACluster(AmazonEC2Client amazonClient, XMLReader configurationFile){ // DescribeSecurityGroupsRequest iRequest = new DescribeSecurityGroupsRequest(); // List<Filter> filter = new ArrayList<Filter>(); // // List<String> values = new ArrayList<String>(); // values.add(getSecurityGroupName(configurationFile.clusterName)); // createFilter(filter, securityGroupNameLabel, values); // iRequest.setFilters(filter); // // return amazonClient.describeSecurityGroups(iRequest); // } // // public static boolean hasAliveSecurityGroupFromCluster(AmazonEC2Client amazonClient, XMLReader configurationFile) { // DescribeSecurityGroupsResult result = getAliveSecurityGroupFromACluster(amazonClient, configurationFile); // return (result.getSecurityGroups().size()>0); // } // // public static DescribeKeyPairsResult getAliveKeyPairFromACluster(AmazonEC2Client amazonClient, XMLReader configurationFile){ // DescribeKeyPairsRequest iRequest = new DescribeKeyPairsRequest(); // List<Filter> filter = new ArrayList<Filter>(); // // List<String> values = new ArrayList<String>(); // values.add(getKeyPairName(configurationFile.clusterName)); // createFilter(filter, keyNameLabel, values); // iRequest.setFilters(filter); // // return amazonClient.describeKeyPairs(iRequest); // } // // public static boolean hasAliveKeyPairFromCluster(AmazonEC2Client amazonClient, XMLReader configurationFile) { // DescribeKeyPairsResult result = getAliveKeyPairFromACluster(amazonClient, configurationFile); // return (result.getKeyPairs().size()>0); // } // // public static DescribeInstancesResult getAliveInstancesFromCluster(AmazonEC2Client amazonClient, String clusterName){ // List<Filter> filters = new ArrayList<Filter>(); // createFilter(filters, instanceStateNameLabel, runningInstanceStates); // // ArrayList<Tag> tags = new ArrayList<Tag>(); // tags.add(new Tag(clusterLabelName, getVirtualMachinesName(clusterName))); // // DescribeInstancesRequest iRequest = getDescribeInstancesRequest(tags, filters); // // return amazonClient.describeInstances(iRequest); // } // // public static DescribeInstancesResult getAliveInstancesFromClusterByType(AmazonEC2Client amazonClient, String clusterName, VirtualMachineType vmType){ // List<Filter> filters = new ArrayList<Filter>(); // createFilter(filters, instanceStateNameLabel, runningInstanceStates); // // List<String> values = new ArrayList<String>(); // values.add(vmType.getType()); // createFilter(filters, instanceTypeNameLabel, values); // // ArrayList<Tag> tags = new ArrayList<Tag>(); // tags.add(new Tag(clusterLabelName, getVirtualMachinesName(clusterName))); // // DescribeInstancesRequest iRequest = getDescribeInstancesRequest(tags, filters); // // return amazonClient.describeInstances(iRequest); // } // // public static DescribeInstancesResult getDescribeMachinesFromCluster(AmazonEC2Client amazonClient, String clusterName){ // ArrayList<Tag> tags = new ArrayList<Tag>(); // // List<Filter> filters = new ArrayList<Filter>(); // createFilter(filters, instanceStateNameLabel, runningInstanceStates); // // tags.add(new Tag(clusterLabelName, getVirtualMachinesName(clusterName))); // // DescribeInstancesRequest iRequest = getDescribeInstancesRequest(tags, filters); // // return amazonClient.describeInstances(iRequest); // } private static VirtualMachineType getVmType(XMLReader configurationFile, String instanceType) { for(VirtualMachineType type : configurationFile.vmTypes){ if(type.getType().equals(instanceType)){ VirtualMachineType retrievedType = new VirtualMachineType(type.getFinancialCost(), type.getDiskSpace(), type.getRam(), type.getGflops(), type.getPlatform(), type.getNumberOfCores()); retrievedType.setType(instanceType); return retrievedType; } } return null; } public static DescribeInstancesResult getNodesFromCluster(AmazonEC2Client amazonClient, String clusterName){ List<Filter> filters = new ArrayList<Filter>(); createFilter(filters, instanceStateNameLabel, runningInstanceStates); ArrayList<Tag> tags = new ArrayList<Tag>(); tags.add(new Tag(clusterLabelName, getVirtualMachinesName(clusterName))); tags.add(new Tag(clusterNodeType, "NODE")); DescribeInstancesRequest iRequest = getDescribeInstancesRequest(tags, filters); return amazonClient.describeInstances(iRequest); } public static ArrayList<EMachine> getMachinesFromCluster(AmazonEC2Client amazonClient, XMLReader configurationFile) { int rank = 0; ArrayList<EMachine> machines = new ArrayList<EMachine>(); DescribeInstancesResult superNode = getDescribeSuperNodeFromCluster(amazonClient, configurationFile.clusterName); for(Reservation reservation : superNode.getReservations()){ for(Instance instance : reservation.getInstances()){ VirtualMachineType vmType = CloudUtils.getVmType(configurationFile, instance.getInstanceType()); EMachine mac = new EMachine(rank, instance.getPublicDnsName(), instance.getPublicIpAddress(), instance.getPrivateIpAddress(), vmType.getType(), vmType.getNumberOfCores()); machines.add(mac); rank++; } } DescribeInstancesResult nodes = getNodesFromCluster(amazonClient, configurationFile.clusterName); for(Reservation reservation : nodes.getReservations()){ for(Instance instance : reservation.getInstances()){ VirtualMachineType vmType = CloudUtils.getVmType(configurationFile, instance.getInstanceType()); EMachine mac = new EMachine(rank, instance.getPublicDnsName(), instance.getPublicIpAddress(), instance.getPrivateIpAddress(), vmType.getType(), vmType.getNumberOfCores()); machines.add(mac); rank++; } } return machines; } // public static boolean hasVMType(ArrayList<VirtualMachineType> vmTypes, VirtualMachineType vmType) { // for(VirtualMachineType machine : vmTypes){ // if(machine.getType().equals(vmType.getType())){ // return true; // } // } // // return false; // } // // public static VirtualMachineType getVmType(ArrayList<VirtualMachineType> vmTypes, VirtualMachineType vmType) { // for(VirtualMachineType machine : vmTypes){ // if(machine.getType().equals(vmType.getType())){ // return machine; // } // } // // return null; // } // // public static VirtualMachineType getVmType(List<VirtualMachineType> vmTypes, String instanceType) { // for(VirtualMachineType type : vmTypes){ // if(type.getType().equals(instanceType)){ // VirtualMachineType retrievedType = new VirtualMachineType(type.getFinancialCost(), // type.getDiskSpace(), type.getRam(), type.getGflops(), type.getPlatform(), type.getNumberOfCores()); // retrievedType.setType(instanceType); // return retrievedType; // } // } // // return null; // } // // public static String[] splitAndDiscard(String s, String regex){ // String[] ret = s.split(regex); // String aux = new String(""); // for(int i = 0; i< ret.length; i++){ // if(!(ret[i].matches(""))){ // aux+=ret[i]+regex; // } // } // ret = aux.split(regex); // return ret; // } // // public static String[] splitAndDiscard(String s, String regex1, String regex2){ // String[] ret = s.split(regex1); // String aux = new String(""); // for(int i = 0; i< ret.length; i++){ // if(!(ret[i].matches(""))){ // if(!(ret[i].matches(regex2))){ // aux+=ret[i]+regex1; // } // } // } // ret = aux.split(regex1); // return ret; // } // // public static boolean MachineListContains(String name, ArrayList<EMachine> machines){ // for(int i=0; i<machines.size(); i++){ // if(machines.get(i).name.matches(name)) return true; // } // return false; // } // // public static boolean machineListIsAllReady(ArrayList<EMachine> machines){ // for(int i=0; i<machines.size(); i++){ // EMachine mac = machines.get(i); // if(mac.publicDNS.matches("pending")) return false; // if(mac.publicDNS == null) return false; // if(mac.publicDNS.matches("")) return false; // } // return true; // } // // public static EMachine getMachineByName(ArrayList<EMachine> machines, String name){ // EMachine mach=null; // for(int i=0; i<machines.size(); i++){ // if(!(machines.get(i).name.matches(name)))mach = machines.get(i); // } // return mach; // } // // public static ArrayList<VirtualMachineType> getVirtualMachineTypesFromCluster(EnvironmentConfiguration environment) { // DescribeInstancesResult result = getAliveInstancesFromCluster(environment.amazonClient, environment.getClusterName()); // ArrayList<VirtualMachineType> vmTypes = new ArrayList<VirtualMachineType>(); // // for(Reservation reservation : result.getReservations()){ // for(Instance instance : reservation.getInstances()){ // VirtualMachineType vmType = CloudUtils.getVmType(environment.getVMTypes(), instance.getInstanceType()); // if(!hasVMType(vmTypes, vmType)){ // vmType.setAmountInstantiatedVM(1); // vmTypes.add(vmType); // }else{ // VirtualMachineType virtualMachine = getVmType(vmTypes, vmType); // virtualMachine.addAmountInstantiatedVM(); // } // } // } // // return vmTypes; // } // // public static MachineComparison compareInstanciatedMachines(ArrayList<VirtualMachineType> instanciatedMachines, List<VirtualMachineType> newConfMachines) { // MachineComparison comparison = new MachineComparison(); // comparison.setEqualToInstanciatedMachines(true); // // for(VirtualMachineType newVMType : newConfMachines){ // VirtualMachineType instVMType = getMachineType(instanciatedMachines, newVMType); // // if(instVMType==null && newVMType.getAmountInstantiatedVM()!=0){ // comparison.setEqualToInstanciatedMachines(false); // // VirtualMachineType vmType = new VirtualMachineType(newVMType.getFinancialCost(), // newVMType.getDiskSpace(), newVMType.getRam(), newVMType.getGflops(), // newVMType.getPlatform(), newVMType.getNumberOfCores()); // vmType.setType(newVMType.getType()); // vmType.setAmountInstantiatedVM(newVMType.getAmountInstantiatedVM()); // comparison.addMachinesToAllocate(newVMType); // }else if(instVMType!=null){ // int diffMachines = newVMType.getAmountInstantiatedVM() - instVMType.getAmountInstantiatedVM(); // if(diffMachines > 0){ // comparison.setEqualToInstanciatedMachines(false); // // VirtualMachineType vmType = new VirtualMachineType(newVMType.getFinancialCost(), // newVMType.getDiskSpace(), newVMType.getRam(), newVMType.getGflops(), // newVMType.getPlatform(), newVMType.getNumberOfCores()); // vmType.setType(newVMType.getType()); // vmType.setAmountInstantiatedVM(diffMachines); // comparison.addMachinesToAllocate(vmType); // }else if(diffMachines < 0){ // comparison.setEqualToInstanciatedMachines(false); // VirtualMachineType vmType = new VirtualMachineType(newVMType.getFinancialCost(), // newVMType.getDiskSpace(), newVMType.getRam(), newVMType.getGflops(), // newVMType.getPlatform(), newVMType.getNumberOfCores()); // vmType.setType(newVMType.getType()); // vmType.setAmountInstantiatedVM(Math.abs(diffMachines)); // comparison.addMachinesToDeallocate(vmType); // } // } // } // // for(VirtualMachineType instVMType : instanciatedMachines){ // VirtualMachineType newVMType = getMachineType(newConfMachines, instVMType); // if(newVMType == null){ // comparison.setEqualToInstanciatedMachines(false); // // VirtualMachineType vmType = new VirtualMachineType(instVMType.getFinancialCost(), // instVMType.getDiskSpace(), instVMType.getRam(), instVMType.getGflops(), // instVMType.getPlatform(), instVMType.getNumberOfCores()); // vmType.setType(instVMType.getType()); // vmType.setAmountInstantiatedVM(instVMType.getAmountInstantiatedVM()); // comparison.addMachinesToDeallocate(instVMType); // } // } // // return comparison; // } // // private static VirtualMachineType getMachineType(List<VirtualMachineType> machinesType, VirtualMachineType vmType){ // for(VirtualMachineType iVMType : machinesType){ // if(iVMType.getType().equals(vmType.getType())){ // return iVMType; // } // } // // return null; // } public static String getVirtualMachinesName(String clusterName){ return CloudUtils.clusterHeaderName + clusterName; } // public static String getKeyPairName(String clusterName){ // return CloudUtils.keyHeaderName + clusterName; // } // // public static String getSecurityGroupName(String clusterName){ // return CloudUtils.securityGroupHeaderName + clusterName; // } // // public static List<String> getSecurityGroupList(String clusterName) { // List<String> securityGroups = new ArrayList<String>(); // securityGroups.add(CloudUtils.securityGroupHeaderName + clusterName); // return securityGroups; // } public static DescribeInstancesResult getDescribeSuperNodeFromCluster(AmazonEC2Client amazonClient, String clusterName){ ArrayList<Tag> tags = new ArrayList<Tag>(); List<Filter> filters = new ArrayList<Filter>(); createFilter(filters, instanceStateNameLabel, runningInstanceStates); tags.add(new Tag(clusterLabelName, getVirtualMachinesName(clusterName))); tags.add(new Tag(clusterNodeType, "SUPERNODE")); DescribeInstancesRequest iRequest = getDescribeInstancesRequest(tags, filters); return amazonClient.describeInstances(iRequest); } protected static DescribeInstancesRequest getDescribeInstancesRequest(ArrayList<Tag> tags, List<Filter> filters) { DescribeInstancesRequest request = new DescribeInstancesRequest(); for(Tag tag : tags){ Filter filter = getFilterFromTag(tag.getKey(), tag.getValue()); filters.add(filter); } request.setFilters(filters); return request; } protected static Filter getFilterFromTag(String tag, String value) { Filter filter = new Filter(); filter.setName("tag:" + tag); filter.setValues(Collections.singletonList(value)); return filter; } }
19,868
0.622962
0.621049
436
44.568806
35.310776
161
false
false
0
0
0
0
0
0
0.720183
false
false
11
bc9fdac590eac911144f6aee8f86a5020544cdaa
23,313,082,546,769
e38f60b97ef36896dd4d061c1f16ca45601823eb
/src/main/org/uva/qls/ast/Style/StyleProperty/FontSizeProperty.java
cbd3a15afaac41f569e5fb61c4e672f102b117ff
[]
no_license
EdwinOuwehand/ql-dsl
https://github.com/EdwinOuwehand/ql-dsl
dae59af26a6e839ec2fc63cf6334e3461603ae0f
f0895b045606952cb0ed0aef09100a118194e640
refs/heads/master
2020-03-13T10:38:20.647000
2018-10-16T09:25:21
2018-10-16T09:25:21
131,087,386
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.uva.qls.ast.Style.StyleProperty; import org.uva.gui.widgets.QuestionWidget; import org.uva.qls.ast.Value.NumberValue; public class FontSizeProperty extends StyleProperty { private final NumberValue value; public FontSizeProperty(NumberValue numberValue) { this.value = numberValue; } @Override public void apply(QuestionWidget widget) { int fontSize = value.getValue(); widget.setFontSize(fontSize); } }
UTF-8
Java
469
java
FontSizeProperty.java
Java
[]
null
[]
package org.uva.qls.ast.Style.StyleProperty; import org.uva.gui.widgets.QuestionWidget; import org.uva.qls.ast.Value.NumberValue; public class FontSizeProperty extends StyleProperty { private final NumberValue value; public FontSizeProperty(NumberValue numberValue) { this.value = numberValue; } @Override public void apply(QuestionWidget widget) { int fontSize = value.getValue(); widget.setFontSize(fontSize); } }
469
0.720682
0.720682
19
23.68421
20.695925
54
false
false
0
0
0
0
0
0
0.368421
false
false
11
a79a973e550f6010409650ebc7c45ab113106e70
13,666,585,994,421
ade31ac1227b658bceff97d8d6b3669edaf0a4bb
/src/ct/test/Main.java
3948e004ff56099d9a5e11560cc2284390869bad
[]
no_license
faywang19/DS
https://github.com/faywang19/DS
899344e04c5864ff0046611b31ee6cf4406a0194
98b2d06826c82c768d46d47697c9413b69d0d2df
refs/heads/master
2023-02-08T21:43:09.451000
2021-01-05T16:45:10
2021-01-05T16:45:10
327,058,135
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ct.test; public class Main { public static void main(String[] args) { System.out.println("当你看到这句话意味着更新成功了,是第二次提交"); System.out.println("什么鬼"); System.out.println("为什么我没有看到第二次修改的呢"); } }
UTF-8
Java
307
java
Main.java
Java
[]
null
[]
package ct.test; public class Main { public static void main(String[] args) { System.out.println("当你看到这句话意味着更新成功了,是第二次提交"); System.out.println("什么鬼"); System.out.println("为什么我没有看到第二次修改的呢"); } }
307
0.638767
0.638767
9
24.222221
19.377981
53
false
false
0
0
0
0
0
0
0.444444
false
false
11
8505f001f1d5db9fb019b4789fa320ac1014eb89
180,388,637,949
db3914d0ff14629bb1e95cb0ad55e8ffeaf00d69
/game-core/src/main/java/com/wjybxx/fastjgame/core/onlinenode/WarzoneNodeData.java
1f0a90200a92211d677792cead00ae01a93359f6
[ "Apache-2.0" ]
permissive
lochakho/fastjgame
https://github.com/lochakho/fastjgame
63ee5b7630b257ffdfbf63b6eaaeae3701cf55fc
04903847825c91b4f71584e2a78bdda14b22b9b6
refs/heads/master
2020-06-03T18:31:06.915000
2019-06-06T08:14:26
2019-06-06T08:14:26
191,683,558
2
0
Apache-2.0
true
2019-06-13T03:20:50
2019-06-13T03:20:50
2019-06-12T03:40:09
2019-06-10T06:42:22
31,555
0
0
0
null
false
false
/* * Copyright 2019 wjybxx * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wjybxx.fastjgame.core.onlinenode; /** * zookeeper在线WarzoneServer节点信息 * * @author wjybxx * @version 1.0 * @date 2019/5/15 17:22 * @github - https://github.com/hl845740757 */ public class WarzoneNodeData extends OnlineNodeData { private final long processGuid; public WarzoneNodeData(String innerTcpAddress, String innerRpcAddress, String innerHttpAddress, long processGuid) { super(innerTcpAddress, innerRpcAddress, innerHttpAddress); this.processGuid=processGuid; } public long getProcessGuid() { return processGuid; } }
UTF-8
Java
1,191
java
WarzoneNodeData.java
Java
[ { "context": "/*\n * Copyright 2019 wjybxx\n *\n * Licensed under the Apache License, Version ", "end": 27, "score": 0.9996951222419739, "start": 21, "tag": "USERNAME", "value": "wjybxx" }, { "context": "\n/**\n * zookeeper在线WarzoneServer节点信息\n *\n * @author wjybxx\n * @version 1.0\n * @date 2019/5/15 17:22\n * @gith", "end": 694, "score": 0.9997197985649109, "start": 688, "tag": "USERNAME", "value": "wjybxx" }, { "context": "e 2019/5/15 17:22\n * @github - https://github.com/hl845740757\n */\npublic class WarzoneNodeData extends OnlineNo", "end": 779, "score": 0.9996486902236938, "start": 768, "tag": "USERNAME", "value": "hl845740757" } ]
null
[]
/* * Copyright 2019 wjybxx * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wjybxx.fastjgame.core.onlinenode; /** * zookeeper在线WarzoneServer节点信息 * * @author wjybxx * @version 1.0 * @date 2019/5/15 17:22 * @github - https://github.com/hl845740757 */ public class WarzoneNodeData extends OnlineNodeData { private final long processGuid; public WarzoneNodeData(String innerTcpAddress, String innerRpcAddress, String innerHttpAddress, long processGuid) { super(innerTcpAddress, innerRpcAddress, innerHttpAddress); this.processGuid=processGuid; } public long getProcessGuid() { return processGuid; } }
1,191
0.73028
0.704835
39
29.23077
29.189444
119
false
false
0
0
0
0
0
0
0.384615
false
false
11
78b6dbc4f89d3edd53d44c1e00af80a47183a932
27,444,841,026,309
4ec160996cff3fc659b4a1677766830ed5249cc4
/src/main/java/com/jomer/models/Note.java
23bfc8fd0513c09728627bc9908996d4e3ab8514
[]
no_license
fjdgallardo/notes
https://github.com/fjdgallardo/notes
acdbe637518a1585edb034bd91141be8e42580f1
5a6a9de968ef866360429a4957e26d336d4865fd
refs/heads/master
2015-08-14T04:13:23.445000
2014-11-04T02:43:26
2014-11-04T02:43:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jomer.models; import java.sql.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="notes") public class Note { @Id @GeneratedValue private int id; @Column(name="entry") private String entry; @Column(name="title") private String title; @Column(name="dateCreated") private Date dateCreated; @Column(name="lastUpdated") private Date lastUpdated; @ManyToOne @JoinColumn(name="username") private User user; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEntry() { return entry; } public void setEntry(String entry) { this.entry = entry; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Date getDateCreated() { return dateCreated; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } public Date getLastUpdated() { return lastUpdated; } public void setLastUpdated(Date lastUpdated) { this.lastUpdated = lastUpdated; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
UTF-8
Java
1,373
java
Note.java
Java
[ { "context": " lastUpdated;\n\t\n\t@ManyToOne\n @JoinColumn(name=\"username\")\n\tprivate User user;\n\n\tpublic int getId() {\n\t\tre", "end": 640, "score": 0.9994375109672546, "start": 632, "tag": "USERNAME", "value": "username" } ]
null
[]
package com.jomer.models; import java.sql.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="notes") public class Note { @Id @GeneratedValue private int id; @Column(name="entry") private String entry; @Column(name="title") private String title; @Column(name="dateCreated") private Date dateCreated; @Column(name="lastUpdated") private Date lastUpdated; @ManyToOne @JoinColumn(name="username") private User user; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getEntry() { return entry; } public void setEntry(String entry) { this.entry = entry; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Date getDateCreated() { return dateCreated; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } public Date getLastUpdated() { return lastUpdated; } public void setLastUpdated(Date lastUpdated) { this.lastUpdated = lastUpdated; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
1,373
0.713037
0.713037
90
14.255555
13.820726
47
false
false
0
0
0
0
0
0
1.066667
false
false
11
d927d77b8d62176f82094ea43ee8282f7f62bcde
7,567,732,428,742
536f0699240ce00c3e8b620075f98b9242af8b78
/src/com/ttl/designpattern/ch6/person/Tie.java
19cc63d3db012ff027389862a719daaa343c77f4
[]
no_license
Logphi/DesignPattern_chengjie
https://github.com/Logphi/DesignPattern_chengjie
f2cac65069eaf4ec5c3e063ddfc22a6600e41cc9
1747e700b052477dcbd6b3ff595dbec06a6e86b5
refs/heads/master
2022-11-06T13:55:39.747000
2020-07-02T09:03:16
2020-07-02T09:03:16
276,053,239
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ttl.designpattern.ch6.person; /** * @ClassName Tie * @Description TODO * @Author ttl * @Date 2020/6/29 16:27 * Version 1.0 **/ public class Tie extends Finery { @Override public void show() { super.show(); System.out.println("领带"); } }
UTF-8
Java
287
java
Tie.java
Java
[ { "context": "\n * @ClassName Tie\n * @Description TODO\n * @Author ttl\n * @Date 2020/6/29 16:27\n * Version 1.0\n **/\npubl", "end": 100, "score": 0.9977906942367554, "start": 97, "tag": "USERNAME", "value": "ttl" } ]
null
[]
package com.ttl.designpattern.ch6.person; /** * @ClassName Tie * @Description TODO * @Author ttl * @Date 2020/6/29 16:27 * Version 1.0 **/ public class Tie extends Finery { @Override public void show() { super.show(); System.out.println("领带"); } }
287
0.60424
0.55477
16
16.6875
11.982898
41
false
false
0
0
0
0
0
0
0.1875
false
false
11
b72f1f80a8a8ad660543c3f2ca7c64366d8b59fe
28,286,654,657,687
395ca4a218a80e19196175201d4426061dfb9b3b
/Avião.java
ed12b8ce7bdf1838b252ce6213e55b55ce7ff73a
[]
no_license
karooltooledo/Orientacao-a-Objetos
https://github.com/karooltooledo/Orientacao-a-Objetos
1c6e63daf580eeae2ddf015c30cf24fd68e634c1
a0179fbf73822f2e7b93ecbdab0095a30a30ac31
refs/heads/main
2023-07-09T03:44:53.409000
2021-07-07T18:21:00
2021-07-07T18:21:00
383,844,016
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package OrientacaoObjetos; public class Avião { //Atributos int passageiros; int piloto; int aeromocas; int codigoVoo; //Métodos void dadosVoo() { System.out.println("***Avião de número " + codigoVoo + "***"); } }
ISO-8859-1
Java
249
java
Avião.java
Java
[]
null
[]
package OrientacaoObjetos; public class Avião { //Atributos int passageiros; int piloto; int aeromocas; int codigoVoo; //Métodos void dadosVoo() { System.out.println("***Avião de número " + codigoVoo + "***"); } }
249
0.62449
0.62449
15
14.333333
15.460343
64
false
false
0
0
0
0
0
0
1.2
false
false
11
52f1bd9e6ec75095aef0a4b97315f4da06004f91
13,477,607,422,893
37ef00c0f4f703368396af5cb14f1828b6a28a62
/src/ho/command/CommandInsert.java
7974d7259bf4551f35eaa9bc1af1f9cc7c69b303
[]
no_license
oo797942/KostaHanbokWebProject
https://github.com/oo797942/KostaHanbokWebProject
ac6c74055c95bb24302f9e9cb09505350c06b139
c7115e9f55cb7c966d1de94aebd5484d1be00ab5
refs/heads/master
2021-01-18T22:48:37.916000
2016-11-12T06:25:53
2016-11-12T06:25:53
72,606,160
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ho.command; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.Part; import ho.command.CommandException; import ho.model.HoException; import ho.model.HoMember; import ho.service.HoMemberService; public class CommandInsert implements Command{ private String next; public CommandInsert( String _next ){ next = _next; } public String execute(HttpServletRequest request) throws CommandException { try{ request.setCharacterEncoding("utf-8"); HashMap<String, Object> memMap= new HashMap<String,Object>(); System.out.println("CommandInsert에 들어왔음"); String cmd = request.getParameter("cmd"); if(cmd.equals("adminGoodsimgInsert")){ System.out.println("CommandInsert에서 imgInsert부분에 들어왔음"); String GoodsName = request.getParameter("GoodsName"); String GoodsCate = request.getParameter("GoodsCate"); String GoodsInfo = request.getParameter("GoodsInfo"); String GoodsColor = request.getParameter("GoodsColor"); String GoodsSize = "null"; int GoodsSoo = Integer.parseInt(request.getParameter("GoodsSoo")); int GoodsPrice = Integer.parseInt(request.getParameter("GoodsPrice")); int GoodsRentPrice = Integer.parseInt(request.getParameter("GoodsRentPrice")); int GoodsDc = Integer.parseInt(request.getParameter("GoodsDc")); String GoodsLsize = request.getParameter("Lsize"); String GoodsMsize = request.getParameter("Msize"); String GoodsSsize = request.getParameter("Ssize"); Part filePart = request.getPart("GoodsImg"); String realPath = ""; if(filePart.getSize()>0){ realPath = FileSaveHelper.save("C:\\Users\\kosta\\git\\KostaHanbokWebProject\\WebContent\\ho\\upload\\", filePart.getInputStream()); }else{ realPath ="null"; } memMap.put("GoodsName", GoodsName); memMap.put("GoodsCate", GoodsCate); memMap.put("GoodsImg", realPath); memMap.put("GoodsInfo", GoodsInfo); memMap.put("GoodsColor", GoodsColor); memMap.put("GoodsSize", GoodsSize); memMap.put("GoodsSoo", GoodsSoo); memMap.put("GoodsPrice", GoodsPrice); memMap.put("GoodsRentPrice", GoodsRentPrice); memMap.put("GoodsDc", GoodsDc); memMap.put("GoodsLsize", GoodsLsize); memMap.put("GoodsMsize", GoodsMsize); memMap.put("GoodsSsize", GoodsSsize); HoMemberService.getInstance().GoodsInsert(memMap); System.out.println("insert성공"); } if(cmd.equals("adminGoodsInList")){ System.out.println("CommandInsert에서 imgInsert부분에 들어왔음"); String GoodsName = request.getParameter("GoodsName"); Part filePart1 = request.getPart("image1"); String realPath1=""; if(filePart1.getSize()>0){ realPath1 =FileSaveHelper.save("C:\\Users\\kosta\\git\\KostaHanbokWebProject\\WebContent\\ho\\upload\\", filePart1.getInputStream()); }else{ realPath1 ="null"; } Part filePart2 = request.getPart("image2"); String realPath2=""; if(filePart2.getSize()>0){ realPath2 = FileSaveHelper.save("C:\\Users\\kosta\\git\\KostaHanbokWebProject\\WebContent\\ho\\upload\\", filePart2.getInputStream()); }else{ realPath2 ="null"; } Part filePart3 = request.getPart("image3"); String realPath3=""; if(filePart3.getSize()>0){ realPath3 = FileSaveHelper.save("C:\\Users\\kosta\\git\\KostaHanbokWebProject\\WebContent\\ho\\upload\\", filePart3.getInputStream()); }else{ realPath3 ="null"; } memMap.put("GoodsName", GoodsName); memMap.put("image1", realPath1); memMap.put("image2", realPath2); memMap.put("image3", realPath3); HoMemberService.getInstance().GoodsimageInsert(memMap); System.out.println("imageInsert 성공"); } }catch( Exception ex ){ throw new CommandException("CommandInsert.java < 입력시 > " + ex.toString() ); } return next; } private String getFileName(Part part) throws UnsupportedEncodingException { System.out.println("getFileName"); for (String cd : part.getHeader("Content-Disposition").split(";")) { if (cd.trim().startsWith("filename")) { return cd.substring(cd.indexOf('=') + 1).trim().replace("\"", ""); } } return null; } }
UTF-8
Java
4,492
java
CommandInsert.java
Java
[ { "context": "){\r\n\t\t\trealPath = FileSaveHelper.save(\"C:\\\\Users\\\\kosta\\\\git\\\\KostaHanbokWebProject\\\\WebContent\\\\ho\\\\uplo", "end": 1797, "score": 0.7343423366546631, "start": 1792, "tag": "USERNAME", "value": "kosta" }, { "context": "\r\n\t\t\t\trealPath3 = FileSaveHelper.save(\"C:\\\\Users\\\\kosta\\\\git\\\\KostaHanbokWebProject\\\\WebContent\\\\ho\\\\uplo", "end": 3533, "score": 0.9984795451164246, "start": 3528, "tag": "USERNAME", "value": "kosta" } ]
null
[]
package ho.command; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.HashMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.Part; import ho.command.CommandException; import ho.model.HoException; import ho.model.HoMember; import ho.service.HoMemberService; public class CommandInsert implements Command{ private String next; public CommandInsert( String _next ){ next = _next; } public String execute(HttpServletRequest request) throws CommandException { try{ request.setCharacterEncoding("utf-8"); HashMap<String, Object> memMap= new HashMap<String,Object>(); System.out.println("CommandInsert에 들어왔음"); String cmd = request.getParameter("cmd"); if(cmd.equals("adminGoodsimgInsert")){ System.out.println("CommandInsert에서 imgInsert부분에 들어왔음"); String GoodsName = request.getParameter("GoodsName"); String GoodsCate = request.getParameter("GoodsCate"); String GoodsInfo = request.getParameter("GoodsInfo"); String GoodsColor = request.getParameter("GoodsColor"); String GoodsSize = "null"; int GoodsSoo = Integer.parseInt(request.getParameter("GoodsSoo")); int GoodsPrice = Integer.parseInt(request.getParameter("GoodsPrice")); int GoodsRentPrice = Integer.parseInt(request.getParameter("GoodsRentPrice")); int GoodsDc = Integer.parseInt(request.getParameter("GoodsDc")); String GoodsLsize = request.getParameter("Lsize"); String GoodsMsize = request.getParameter("Msize"); String GoodsSsize = request.getParameter("Ssize"); Part filePart = request.getPart("GoodsImg"); String realPath = ""; if(filePart.getSize()>0){ realPath = FileSaveHelper.save("C:\\Users\\kosta\\git\\KostaHanbokWebProject\\WebContent\\ho\\upload\\", filePart.getInputStream()); }else{ realPath ="null"; } memMap.put("GoodsName", GoodsName); memMap.put("GoodsCate", GoodsCate); memMap.put("GoodsImg", realPath); memMap.put("GoodsInfo", GoodsInfo); memMap.put("GoodsColor", GoodsColor); memMap.put("GoodsSize", GoodsSize); memMap.put("GoodsSoo", GoodsSoo); memMap.put("GoodsPrice", GoodsPrice); memMap.put("GoodsRentPrice", GoodsRentPrice); memMap.put("GoodsDc", GoodsDc); memMap.put("GoodsLsize", GoodsLsize); memMap.put("GoodsMsize", GoodsMsize); memMap.put("GoodsSsize", GoodsSsize); HoMemberService.getInstance().GoodsInsert(memMap); System.out.println("insert성공"); } if(cmd.equals("adminGoodsInList")){ System.out.println("CommandInsert에서 imgInsert부분에 들어왔음"); String GoodsName = request.getParameter("GoodsName"); Part filePart1 = request.getPart("image1"); String realPath1=""; if(filePart1.getSize()>0){ realPath1 =FileSaveHelper.save("C:\\Users\\kosta\\git\\KostaHanbokWebProject\\WebContent\\ho\\upload\\", filePart1.getInputStream()); }else{ realPath1 ="null"; } Part filePart2 = request.getPart("image2"); String realPath2=""; if(filePart2.getSize()>0){ realPath2 = FileSaveHelper.save("C:\\Users\\kosta\\git\\KostaHanbokWebProject\\WebContent\\ho\\upload\\", filePart2.getInputStream()); }else{ realPath2 ="null"; } Part filePart3 = request.getPart("image3"); String realPath3=""; if(filePart3.getSize()>0){ realPath3 = FileSaveHelper.save("C:\\Users\\kosta\\git\\KostaHanbokWebProject\\WebContent\\ho\\upload\\", filePart3.getInputStream()); }else{ realPath3 ="null"; } memMap.put("GoodsName", GoodsName); memMap.put("image1", realPath1); memMap.put("image2", realPath2); memMap.put("image3", realPath3); HoMemberService.getInstance().GoodsimageInsert(memMap); System.out.println("imageInsert 성공"); } }catch( Exception ex ){ throw new CommandException("CommandInsert.java < 입력시 > " + ex.toString() ); } return next; } private String getFileName(Part part) throws UnsupportedEncodingException { System.out.println("getFileName"); for (String cd : part.getHeader("Content-Disposition").split(";")) { if (cd.trim().startsWith("filename")) { return cd.substring(cd.indexOf('=') + 1).trim().replace("\"", ""); } } return null; } }
4,492
0.673511
0.666065
136
30.588236
25.67915
109
false
false
0
0
0
0
0
0
3.382353
false
false
11
79d69e5b532f6bd3c7fdb7a594f3d0c0d1ce6f2b
23,922,967,874,327
17a379086bcc4d61af83267c5534b0694dd08d1a
/src/test/RecepteurAnalogiqueTest.java
4169652daee4b0d8f238582913c8c9934950f2db
[]
no_license
quentin9696/SIT213
https://github.com/quentin9696/SIT213
13ac6eac7ca109613828ded40d513e3f7cd4ab89
b705bf7461a781be86698262f91db8a49bb1c9bb
refs/heads/master
2021-01-21T12:58:49.449000
2015-10-28T20:00:02
2015-10-28T20:00:02
42,859,971
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test; import static org.junit.Assert.*; import information.Information; import information.InformationNonConforme; import java.util.Objects; import java.util.Random; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Test; import transmetteurs.EmetteurAnalogique; import transmetteurs.RecepteurAnalogique; import transmetteurs.RecepteurNonConforme; import transmetteurs.Transmetteur; import org.junit.Test; public class RecepteurAnalogiqueTest { private RecepteurAnalogique recepteurAnalogique_RZ; private RecepteurAnalogique recepteurAnalogique_NRZ; private RecepteurAnalogique recepteurAnalogique_NRZT; private int nombreEchantillonsRZ=20; private int nombreEchantillons=0; private int nombreEchantillonsNRZ=12; private int nombreEchantillonsNRZT=15; public RecepteurAnalogiqueTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { try { recepteurAnalogique_RZ = new RecepteurAnalogique(-1, 1, "RZ", nombreEchantillonsRZ ); } catch (RecepteurNonConforme e) { e.printStackTrace(); } try { recepteurAnalogique_NRZ = new RecepteurAnalogique(-1, 1, "NRZ", nombreEchantillonsNRZ ); } catch (RecepteurNonConforme e) { e.printStackTrace(); } try { recepteurAnalogique_NRZT = new RecepteurAnalogique(-1, 1, "NRZT", nombreEchantillonsNRZT ); } catch (RecepteurNonConforme e) { e.printStackTrace(); } } @After public void tearDown() { } private Float[] getRandomFloatArray(int n) { Float[] bits = new Float[n]; Random rnd = new Random(); for (int i = 0; i < n; i++) { bits[i] = rnd.nextFloat(); } return bits; } @Test public void testrecepteurAnalogiqueConforme1() throws Exception { System.out.println("Test 0 du constructeur : "); recepteurAnalogique_RZ = new RecepteurAnalogique(-1, 1, "RZ", nombreEchantillonsRZ ); } @Test public void testrecepteurAnalogiqueConforme2() throws Exception { System.out.println("Test 1 du constructeur : "); recepteurAnalogique_NRZ = new RecepteurAnalogique(-1, 1, "NRZ", nombreEchantillonsNRZ ); } @Test public void testrecepteurAnalogiqueConforme3() throws Exception { System.out.println("Test 2 du constructeur : "); recepteurAnalogique_NRZT = new RecepteurAnalogique(-1, 1, "NRZT", nombreEchantillonsNRZT ); } @Test(expected=RecepteurNonConforme.class) public void testrecepteurAnalogiqueAvecUnMinSuperieurAuMax() throws Exception { System.out.println("Test 1 du constructeur : "); recepteurAnalogique_RZ = new RecepteurAnalogique(2, 1, "RZ", nombreEchantillonsRZ ); } @Test(expected=RecepteurNonConforme.class) public void testrecepteurAnalogiqueAvecUnMaxInferieurAuMin() throws Exception { System.out.println("Test 2 du constructeur : "); recepteurAnalogique_RZ = new RecepteurAnalogique(-1, -2, "RZ", nombreEchantillonsRZ ); } @Test(expected=RecepteurNonConforme.class) public void testrecepteurAnalogiqueFormeIncorrecte() throws Exception { System.out.println("Test 3 du constructeur : "); recepteurAnalogique_RZ = new RecepteurAnalogique(-1, 1, "", nombreEchantillonsRZ ); } @Test(expected=RecepteurNonConforme.class) public void testrecepteurAnalogiqueFormeIncorrecteBis() throws Exception { System.out.println("Test 4 du constructeur : "); recepteurAnalogique_RZ = new RecepteurAnalogique(-1, 1, null, nombreEchantillonsRZ ); } @Test(expected=RecepteurNonConforme.class) public void testrecepteurAnalogiqueNombreEchantillonsDeFormeNonConforme() throws Exception { System.out.println("Test 5 du constructeur : "); recepteurAnalogique_RZ = new RecepteurAnalogique(-1, 1, "NRZL", nombreEchantillonsRZ ); } @Test(expected=RecepteurNonConforme.class) public void testrecepteurAnalogiqueNombreEchantillonsNul() throws Exception { System.out.println("Test 5 du constructeur : "); recepteurAnalogique_RZ = new RecepteurAnalogique(-1, 1, "NRZT", nombreEchantillons); } @Test public void testRecevoirNRZ() throws Exception { System.out.println("Test 1 de la méthode recevoir : "); Double[] tabDeDouble= {0.,2.5,0.3}; Information<Double> messageAnalogique= new Information<Double>(tabDeDouble); recepteurAnalogique_NRZ.recevoir(messageAnalogique); //System.out.println(tableauDeBooleens.length); //System.out.println(emetteurAnalogique_NRZ.getInformationRecue().nbElements()); assertEquals(messageAnalogique, recepteurAnalogique_NRZ.getInformationRecue()); } @Test public void testRecevoirNRZT() throws Exception { System.out.println("Test 2 de la méthode recevoir : "); Double[] tableauDeDouble= {2.,3.5,8.9}; Information<Double> messageAnalogique= new Information<Double>(tableauDeDouble); recepteurAnalogique_NRZT.recevoir(messageAnalogique); //System.out.println(tableauDeBooleens.length); //System.out.println(emetteurAnalogique_NRZT.getInformationRecue().nbElements()); assertEquals(messageAnalogique, recepteurAnalogique_NRZT.getInformationRecue()); } @Test public void testRecevoirRZ() throws Exception { System.out.println("Test 3 de la méthode recevoir : "); Double[] tableauDeDouble= {2.5,3.6,2.8}; Information<Double> messageAnalogique= new Information<Double>(tableauDeDouble); recepteurAnalogique_RZ.recevoir(messageAnalogique); //System.out.println(tableauDeBooleens.length); //System.out.println(emetteurAnalogique_RZ.getInformationRecue().nbElements()); assertEquals(messageAnalogique, recepteurAnalogique_RZ.getInformationRecue()); } }
UTF-8
Java
5,866
java
RecepteurAnalogiqueTest.java
Java
[]
null
[]
package test; import static org.junit.Assert.*; import information.Information; import information.InformationNonConforme; import java.util.Objects; import java.util.Random; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Test; import transmetteurs.EmetteurAnalogique; import transmetteurs.RecepteurAnalogique; import transmetteurs.RecepteurNonConforme; import transmetteurs.Transmetteur; import org.junit.Test; public class RecepteurAnalogiqueTest { private RecepteurAnalogique recepteurAnalogique_RZ; private RecepteurAnalogique recepteurAnalogique_NRZ; private RecepteurAnalogique recepteurAnalogique_NRZT; private int nombreEchantillonsRZ=20; private int nombreEchantillons=0; private int nombreEchantillonsNRZ=12; private int nombreEchantillonsNRZT=15; public RecepteurAnalogiqueTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { try { recepteurAnalogique_RZ = new RecepteurAnalogique(-1, 1, "RZ", nombreEchantillonsRZ ); } catch (RecepteurNonConforme e) { e.printStackTrace(); } try { recepteurAnalogique_NRZ = new RecepteurAnalogique(-1, 1, "NRZ", nombreEchantillonsNRZ ); } catch (RecepteurNonConforme e) { e.printStackTrace(); } try { recepteurAnalogique_NRZT = new RecepteurAnalogique(-1, 1, "NRZT", nombreEchantillonsNRZT ); } catch (RecepteurNonConforme e) { e.printStackTrace(); } } @After public void tearDown() { } private Float[] getRandomFloatArray(int n) { Float[] bits = new Float[n]; Random rnd = new Random(); for (int i = 0; i < n; i++) { bits[i] = rnd.nextFloat(); } return bits; } @Test public void testrecepteurAnalogiqueConforme1() throws Exception { System.out.println("Test 0 du constructeur : "); recepteurAnalogique_RZ = new RecepteurAnalogique(-1, 1, "RZ", nombreEchantillonsRZ ); } @Test public void testrecepteurAnalogiqueConforme2() throws Exception { System.out.println("Test 1 du constructeur : "); recepteurAnalogique_NRZ = new RecepteurAnalogique(-1, 1, "NRZ", nombreEchantillonsNRZ ); } @Test public void testrecepteurAnalogiqueConforme3() throws Exception { System.out.println("Test 2 du constructeur : "); recepteurAnalogique_NRZT = new RecepteurAnalogique(-1, 1, "NRZT", nombreEchantillonsNRZT ); } @Test(expected=RecepteurNonConforme.class) public void testrecepteurAnalogiqueAvecUnMinSuperieurAuMax() throws Exception { System.out.println("Test 1 du constructeur : "); recepteurAnalogique_RZ = new RecepteurAnalogique(2, 1, "RZ", nombreEchantillonsRZ ); } @Test(expected=RecepteurNonConforme.class) public void testrecepteurAnalogiqueAvecUnMaxInferieurAuMin() throws Exception { System.out.println("Test 2 du constructeur : "); recepteurAnalogique_RZ = new RecepteurAnalogique(-1, -2, "RZ", nombreEchantillonsRZ ); } @Test(expected=RecepteurNonConforme.class) public void testrecepteurAnalogiqueFormeIncorrecte() throws Exception { System.out.println("Test 3 du constructeur : "); recepteurAnalogique_RZ = new RecepteurAnalogique(-1, 1, "", nombreEchantillonsRZ ); } @Test(expected=RecepteurNonConforme.class) public void testrecepteurAnalogiqueFormeIncorrecteBis() throws Exception { System.out.println("Test 4 du constructeur : "); recepteurAnalogique_RZ = new RecepteurAnalogique(-1, 1, null, nombreEchantillonsRZ ); } @Test(expected=RecepteurNonConforme.class) public void testrecepteurAnalogiqueNombreEchantillonsDeFormeNonConforme() throws Exception { System.out.println("Test 5 du constructeur : "); recepteurAnalogique_RZ = new RecepteurAnalogique(-1, 1, "NRZL", nombreEchantillonsRZ ); } @Test(expected=RecepteurNonConforme.class) public void testrecepteurAnalogiqueNombreEchantillonsNul() throws Exception { System.out.println("Test 5 du constructeur : "); recepteurAnalogique_RZ = new RecepteurAnalogique(-1, 1, "NRZT", nombreEchantillons); } @Test public void testRecevoirNRZ() throws Exception { System.out.println("Test 1 de la méthode recevoir : "); Double[] tabDeDouble= {0.,2.5,0.3}; Information<Double> messageAnalogique= new Information<Double>(tabDeDouble); recepteurAnalogique_NRZ.recevoir(messageAnalogique); //System.out.println(tableauDeBooleens.length); //System.out.println(emetteurAnalogique_NRZ.getInformationRecue().nbElements()); assertEquals(messageAnalogique, recepteurAnalogique_NRZ.getInformationRecue()); } @Test public void testRecevoirNRZT() throws Exception { System.out.println("Test 2 de la méthode recevoir : "); Double[] tableauDeDouble= {2.,3.5,8.9}; Information<Double> messageAnalogique= new Information<Double>(tableauDeDouble); recepteurAnalogique_NRZT.recevoir(messageAnalogique); //System.out.println(tableauDeBooleens.length); //System.out.println(emetteurAnalogique_NRZT.getInformationRecue().nbElements()); assertEquals(messageAnalogique, recepteurAnalogique_NRZT.getInformationRecue()); } @Test public void testRecevoirRZ() throws Exception { System.out.println("Test 3 de la méthode recevoir : "); Double[] tableauDeDouble= {2.5,3.6,2.8}; Information<Double> messageAnalogique= new Information<Double>(tableauDeDouble); recepteurAnalogique_RZ.recevoir(messageAnalogique); //System.out.println(tableauDeBooleens.length); //System.out.println(emetteurAnalogique_RZ.getInformationRecue().nbElements()); assertEquals(messageAnalogique, recepteurAnalogique_RZ.getInformationRecue()); } }
5,866
0.736995
0.726249
165
34.533333
29.565651
96
false
false
0
0
0
0
0
0
2.6
false
false
11
59238c1c0b51b2b2aaabe198a35d570f7c0e63d6
1,949,915,212,031
faf7b826c1fac99529a4b6c1a64e1849b85fd57a
/magazyny/src/model/Samochod.java
67a66030b1bf1907988ec3c5d4f60f5cb4670028
[]
no_license
izoslav/gui-serf
https://github.com/izoslav/gui-serf
615eb6780d09602bcbfd6829db8283ced2452291
b8c2ba7767bd8f9f00a0944fa36555c87191c47d
refs/heads/master
2020-05-17T09:08:41.950000
2019-04-26T19:16:24
2019-04-26T19:16:24
183,624,174
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package model; public class Samochod extends Przedmiot { final private int pojemnoscSilnika; final private String rodzajPaliwa; public Samochod(String nazwa, int rozmiar, int pojemnoscSilnika, String rodzajPaliwa) { super(nazwa, rozmiar); this.pojemnoscSilnika = pojemnoscSilnika; this.rodzajPaliwa = rodzajPaliwa; } public Samochod(String nazwa, int dlugosc, int szerokosc, int wysokosc, int pojemnoscSilnika, String rodzajPaliwa) { this(nazwa, dlugosc * szerokosc * wysokosc, pojemnoscSilnika, rodzajPaliwa); } @Override public String toString() { return "Samochod{" + "pojemnoscSilnika=" + pojemnoscSilnika + ", rodzajPaliwa='" + rodzajPaliwa + '\'' + '}'; } }
UTF-8
Java
816
java
Samochod.java
Java
[]
null
[]
package model; public class Samochod extends Przedmiot { final private int pojemnoscSilnika; final private String rodzajPaliwa; public Samochod(String nazwa, int rozmiar, int pojemnoscSilnika, String rodzajPaliwa) { super(nazwa, rozmiar); this.pojemnoscSilnika = pojemnoscSilnika; this.rodzajPaliwa = rodzajPaliwa; } public Samochod(String nazwa, int dlugosc, int szerokosc, int wysokosc, int pojemnoscSilnika, String rodzajPaliwa) { this(nazwa, dlugosc * szerokosc * wysokosc, pojemnoscSilnika, rodzajPaliwa); } @Override public String toString() { return "Samochod{" + "pojemnoscSilnika=" + pojemnoscSilnika + ", rodzajPaliwa='" + rodzajPaliwa + '\'' + '}'; } }
816
0.631127
0.631127
24
32
31.5
120
false
false
0
0
0
0
0
0
0.875
false
false
11
7b29a0488d73502c93616fecdb699a74e32be5ba
26,637,387,239,183
1bff47a5e5f2c5800a64b9e3c809cdf4e51815e5
/smt-cloudformation-objects/src/main/java/shiver/me/timbers/aws/iot/ThingPrincipalAttachment.java
d788612d352ee2d4bab4a0d05c841f214c48e551
[ "Apache-2.0" ]
permissive
shiver-me-timbers/smt-cloudformation-parent
https://github.com/shiver-me-timbers/smt-cloudformation-parent
d773863ce52c5de154d909498a7546e0da545556
e2600814428a92ff8ea5977408ccc6a8f511a561
refs/heads/master
2021-06-09T09:13:17.335000
2020-06-19T08:24:16
2020-06-19T08:24:16
149,845,802
4
0
Apache-2.0
false
2021-04-26T16:53:04
2018-09-22T04:39:40
2020-06-19T08:24:24
2021-04-26T16:53:04
7,914
3
0
1
Java
false
false
package shiver.me.timbers.aws.iot; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; /** * ThingPrincipalAttachment * <p> * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html * */ @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonPropertyOrder({ "Principal", "ThingName" }) public class ThingPrincipalAttachment { /** * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html#cfn-iot-thingprincipalattachment-principal * */ @JsonProperty("Principal") @JsonPropertyDescription("http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html#cfn-iot-thingprincipalattachment-principal") private CharSequence principal; /** * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html#cfn-iot-thingprincipalattachment-thingname * */ @JsonProperty("ThingName") @JsonPropertyDescription("http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html#cfn-iot-thingprincipalattachment-thingname") private CharSequence thingName; /** * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html#cfn-iot-thingprincipalattachment-principal * */ @JsonIgnore public CharSequence getPrincipal() { return principal; } /** * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html#cfn-iot-thingprincipalattachment-principal * */ @JsonIgnore public void setPrincipal(CharSequence principal) { this.principal = principal; } public ThingPrincipalAttachment withPrincipal(CharSequence principal) { this.principal = principal; return this; } /** * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html#cfn-iot-thingprincipalattachment-thingname * */ @JsonIgnore public CharSequence getThingName() { return thingName; } /** * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html#cfn-iot-thingprincipalattachment-thingname * */ @JsonIgnore public void setThingName(CharSequence thingName) { this.thingName = thingName; } public ThingPrincipalAttachment withThingName(CharSequence thingName) { this.thingName = thingName; return this; } @Override public String toString() { return new ToStringBuilder(this).append("principal", principal).append("thingName", thingName).toString(); } @Override public int hashCode() { return new HashCodeBuilder().append(principal).append(thingName).toHashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } if ((other instanceof ThingPrincipalAttachment) == false) { return false; } ThingPrincipalAttachment rhs = ((ThingPrincipalAttachment) other); return new EqualsBuilder().append(principal, rhs.principal).append(thingName, rhs.thingName).isEquals(); } }
UTF-8
Java
3,802
java
ThingPrincipalAttachment.java
Java
[]
null
[]
package shiver.me.timbers.aws.iot; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.lang.builder.ToStringBuilder; /** * ThingPrincipalAttachment * <p> * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html * */ @JsonInclude(JsonInclude.Include.NON_EMPTY) @JsonPropertyOrder({ "Principal", "ThingName" }) public class ThingPrincipalAttachment { /** * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html#cfn-iot-thingprincipalattachment-principal * */ @JsonProperty("Principal") @JsonPropertyDescription("http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html#cfn-iot-thingprincipalattachment-principal") private CharSequence principal; /** * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html#cfn-iot-thingprincipalattachment-thingname * */ @JsonProperty("ThingName") @JsonPropertyDescription("http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html#cfn-iot-thingprincipalattachment-thingname") private CharSequence thingName; /** * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html#cfn-iot-thingprincipalattachment-principal * */ @JsonIgnore public CharSequence getPrincipal() { return principal; } /** * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html#cfn-iot-thingprincipalattachment-principal * */ @JsonIgnore public void setPrincipal(CharSequence principal) { this.principal = principal; } public ThingPrincipalAttachment withPrincipal(CharSequence principal) { this.principal = principal; return this; } /** * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html#cfn-iot-thingprincipalattachment-thingname * */ @JsonIgnore public CharSequence getThingName() { return thingName; } /** * http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-thingprincipalattachment.html#cfn-iot-thingprincipalattachment-thingname * */ @JsonIgnore public void setThingName(CharSequence thingName) { this.thingName = thingName; } public ThingPrincipalAttachment withThingName(CharSequence thingName) { this.thingName = thingName; return this; } @Override public String toString() { return new ToStringBuilder(this).append("principal", principal).append("thingName", thingName).toString(); } @Override public int hashCode() { return new HashCodeBuilder().append(principal).append(thingName).toHashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } if ((other instanceof ThingPrincipalAttachment) == false) { return false; } ThingPrincipalAttachment rhs = ((ThingPrincipalAttachment) other); return new EqualsBuilder().append(principal, rhs.principal).append(thingName, rhs.thingName).isEquals(); } }
3,802
0.726197
0.726197
109
33.871559
44.620747
183
false
false
0
0
0
0
0
0
0.275229
false
false
11
315bbc149428483361e1cba11ee4a813efdad632
33,672,543,649,685
d545ae4e7a46f98f7c0bdf53d20b7f239fbc3ccc
/Data structure and algorithm/algorithm/FloydAlgorithm.java
9af59c6a5b3706d2956058991c076b9d3a338ebc
[]
no_license
Ramelon/Data-structure-and-algorithm
https://github.com/Ramelon/Data-structure-and-algorithm
88e6ca603373d1271f0a8a0e25a4e4aff5ffa515
478bfeda0e56fddf862d03f23e0d75e7e8538014
refs/heads/master
2021-05-24T09:55:30.735000
2020-04-06T13:41:43
2020-04-06T13:41:43
253,507,525
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package algorithm; import java.util.Arrays; public class FloydAlgorithm { public static void main(String[] args) { int min = 32767; char[] vertexs = { 'A', 'B', 'C', 'D', 'E', 'F', 'G' }; int[][] matrix = { { 0, 7, min, 5, min, min, min }, { 7, 0, 8, 9, 7, min, min }, { min, 8, 0, min, 5, min, min }, { 5, 9, min, 0, 15, 6, min }, { min, 7, 5, 15, 0, 8, 9 }, { min, min, min, 6, 8, 0, 11 }, { min, min, min, min, 9, 11, 0 } }; Grapg3 grapg3 = new Grapg3(vertexs, matrix); FloydDemo floydDemo = new FloydDemo(); floydDemo.floyd(matrix); grapg3.showGraph(); } } class FloydDemo { public void floyd(int[][] matrix) { // 遍历{ 'A', 'B', 'C', 'D', 'E', 'F', 'G' } 把其中每一个顶点当做中间节点 for (int k = 0; k < matrix.length; k++) { // 矩阵,二维数据 对应的是matrix[i][j] for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix.length; j++) { // G[i][j] = min( G[i][j], G[i][k]+G[k][j] ) int temp = matrix[i][k] + matrix[k][j]; if(temp < matrix[i][j]) { matrix[i][j] = temp; } } } } } } class Grapg3 { private char[] vertexs; private int[][] matrix; public Grapg3(char[] vertexs, int[][] matrix) { // TODO Auto-generated constructor stub this.vertexs = vertexs; this.matrix = matrix; } public void showGraph() { for (int[] m : matrix) { System.out.println(Arrays.toString(m)); } } }
GB18030
Java
1,427
java
FloydAlgorithm.java
Java
[]
null
[]
package algorithm; import java.util.Arrays; public class FloydAlgorithm { public static void main(String[] args) { int min = 32767; char[] vertexs = { 'A', 'B', 'C', 'D', 'E', 'F', 'G' }; int[][] matrix = { { 0, 7, min, 5, min, min, min }, { 7, 0, 8, 9, 7, min, min }, { min, 8, 0, min, 5, min, min }, { 5, 9, min, 0, 15, 6, min }, { min, 7, 5, 15, 0, 8, 9 }, { min, min, min, 6, 8, 0, 11 }, { min, min, min, min, 9, 11, 0 } }; Grapg3 grapg3 = new Grapg3(vertexs, matrix); FloydDemo floydDemo = new FloydDemo(); floydDemo.floyd(matrix); grapg3.showGraph(); } } class FloydDemo { public void floyd(int[][] matrix) { // 遍历{ 'A', 'B', 'C', 'D', 'E', 'F', 'G' } 把其中每一个顶点当做中间节点 for (int k = 0; k < matrix.length; k++) { // 矩阵,二维数据 对应的是matrix[i][j] for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix.length; j++) { // G[i][j] = min( G[i][j], G[i][k]+G[k][j] ) int temp = matrix[i][k] + matrix[k][j]; if(temp < matrix[i][j]) { matrix[i][j] = temp; } } } } } } class Grapg3 { private char[] vertexs; private int[][] matrix; public Grapg3(char[] vertexs, int[][] matrix) { // TODO Auto-generated constructor stub this.vertexs = vertexs; this.matrix = matrix; } public void showGraph() { for (int[] m : matrix) { System.out.println(Arrays.toString(m)); } } }
1,427
0.536052
0.501821
55
23.981817
22.64789
94
false
false
0
0
0
0
0
0
3.327273
false
false
11
019c7c81d9b66c38ef2b0aec6c5c0a6c45f2933b
31,576,599,601,566
b9f270a150e3706b61aed0f118caf69db91f57aa
/app/src/main/java/cn/qatime/player/activity/PersonalInformationChangeActivity.java
7a570a343672303f0cae6cccbf231417a4632b3d
[]
no_license
chuanjiabao1981/qatime-android-student
https://github.com/chuanjiabao1981/qatime-android-student
ac583a49d2a59d1ff5f9f635d9ba2d75445188ae
2034a39f2168cd426553dbbdef2b3030bda443b1
refs/heads/master
2021-03-27T19:47:52.257000
2018-01-09T08:49:54
2018-01-09T08:49:54
66,045,440
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.qatime.player.activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.content.FileProvider; import android.text.Editable; import android.text.InputFilter; import android.text.Selection; import android.view.KeyEvent; import android.view.View; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.orhanobut.logger.Logger; import com.umeng.analytics.MobclickAgent; import java.io.File; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import cn.qatime.player.R; import cn.qatime.player.base.BaseActivity; import cn.qatime.player.base.BaseApplication; import cn.qatime.player.utils.Constant; import cn.qatime.player.utils.UpLoadUtil; import cn.qatime.player.utils.UrlUtils; import libraryextra.bean.CityBean; import libraryextra.bean.GradeBean; import libraryextra.bean.ImageItem; import libraryextra.bean.PersonalInformationBean; import libraryextra.bean.Profile; import libraryextra.bean.ProvincesBean; import libraryextra.bean.SchoolBean; import libraryextra.transformation.GlideCircleTransform; import libraryextra.utils.DialogUtils; import libraryextra.utils.FileUtil; import libraryextra.utils.JsonUtils; import libraryextra.utils.StringUtils; import libraryextra.view.CustomProgressDialog; import libraryextra.view.MDatePickerDialog; import libraryextra.view.WheelView; public class PersonalInformationChangeActivity extends BaseActivity implements View.OnClickListener { ImageView headsculpture; View replace; EditText name; TextView men; TextView women; TextView textGrade; TextView complete; private EditText describe; private TextView birthday; private TextView region; private View regionView; private View birthdayView; private View gradeView; private SimpleDateFormat parse = new SimpleDateFormat("yyyy-MM-dd"); private SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日"); private String imageUrl = "http://qatime-testing.oss-cn-beijing.aliyuncs.com/avatars/e24edc0acfe48710fce2b2224bfee8ab.png"; private String select = "2000-01-01";//生日所选日期 private CustomProgressDialog progress; private AlertDialog alertDialog; private String gender = ""; private List<String> grades; private ProvincesBean.DataBean regionProvince; private CityBean.Data regionCity; private ProvincesBean provincesBean; private CityBean cityBean; private SchoolBean schoolBean; private TextView school; private View schoolView; private SchoolBean.Data schoolData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_personal_information_change); setTitles(getResources().getString(R.string.change_information)); initView(); provincesBean = JsonUtils.objectFromJson(FileUtil.readFile(getFilesDir() + "/provinces.txt").toString(), ProvincesBean.class); cityBean = JsonUtils.objectFromJson(FileUtil.readFile(getFilesDir() + "/cities.txt").toString(), CityBean.class); schoolBean = JsonUtils.objectFromJson(FileUtil.readFile(getFilesDir() + "/school.txt").toString(), SchoolBean.class); String gradeString = FileUtil.readFile(getFilesDir() + "/grade.txt"); // LogUtils.e("班级基础信息" + gradeString); grades = new ArrayList<>(); if (!StringUtils.isNullOrBlanK(gradeString)) { GradeBean gradeBean = JsonUtils.objectFromJson(gradeString, GradeBean.class); grades = gradeBean.getData().getGrades(); } PersonalInformationBean data = (PersonalInformationBean) getIntent().getSerializableExtra("data"); if (data != null && data.getData() != null) { initData(data); } replace.setOnClickListener(this); men.setOnClickListener(this); women.setOnClickListener(this); birthdayView.setOnClickListener(this); complete.setOnClickListener(this); gradeView.setOnClickListener(this); regionView.setOnClickListener(this); schoolView.setOnClickListener(this); } private void initData(PersonalInformationBean data) { Glide.with(PersonalInformationChangeActivity.this).load(data.getData().getAvatar_url()).placeholder(R.mipmap.personal_information_head).transform(new GlideCircleTransform(PersonalInformationChangeActivity.this)).crossFade().into(headsculpture); name.setText(data.getData().getName()); Editable etext = name.getText(); imageUrl = data.getData().getAvatar_url(); Selection.setSelection(etext, etext.length()); if (!StringUtils.isNullOrBlanK(data.getData().getGender())) { if (data.getData().getGender().equals("male")) { men.setSelected(true); women.setSelected(false); } else { men.setSelected(false); women.setSelected(true); } } if (!StringUtils.isNullOrBlanK(data.getData().getBirthday())) { try { birthday.setText(format.format(parse.parse(data.getData().getBirthday()))); select = data.getData().getBirthday(); } catch (ParseException e) { e.printStackTrace(); } } else { birthday.setText(format.format(new Date())); select = parse.format(new Date()); } if (!StringUtils.isNullOrBlanK(data.getData().getGrade())) { for (int i = 0; i < grades.size(); i++) { if (data.getData().getGrade().equals(grades.get(i))) { textGrade.setText(data.getData().getGrade()); break; } } } if (provincesBean != null && provincesBean.getData() != null) { for (int i = 0; i < provincesBean.getData().size(); i++) { if (provincesBean.getData().get(i).getId().equals(data.getData().getProvince())) { regionProvince = provincesBean.getData().get(i); break; } } } if (cityBean != null && cityBean.getData() != null) { for (int i = 0; i < cityBean.getData().size(); i++) { if (cityBean.getData().get(i).getId().equals(data.getData().getCity())) { regionCity = cityBean.getData().get(i); break; } } } if (regionCity != null && regionProvince != null) { region.setText(regionProvince.getName() + regionCity.getName()); } if (schoolBean != null && schoolBean.getData() != null) { for (int i = 0; i < schoolBean.getData().size(); i++) { if (schoolBean.getData().get(i).getId() == data.getData().getSchool()) { schoolData = schoolBean.getData().get(i); school.setText(schoolBean.getData().get(i).getName()); break; } } } describe.setText(data.getData().getDesc()); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.region_view: Intent regionIntent = new Intent(this, RegionSelectActivity1.class); // if (regionProvince != null && regionCity != null) { // regionIntent.putExtra("region_province", regionProvince); // regionIntent.putExtra("region_city", regionCity); // } startActivityForResult(regionIntent, Constant.REQUEST_REGION_SELECT); break; case R.id.school_view: Intent schoolIntent = new Intent(this, SchoolSelectActivity.class); startActivityForResult(schoolIntent, Constant.REQUEST_SCHOOL_SELECT); break; case R.id.men: men.setSelected(true); women.setSelected(false); gender = "male"; break; case R.id.women: women.setSelected(true); men.setSelected(false); gender = "female"; break; case R.id.grade_view: showGradePickerDialog(); break; case R.id.replace://去选择图片 final Intent intent = new Intent(PersonalInformationChangeActivity.this, PictureSelectActivity.class); startActivityForResult(intent, Constant.REQUEST_PICTURE_SELECT); break; case R.id.birthday_view://生日 try { MDatePickerDialog dataDialog = new MDatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { select = (year + "-" + ((monthOfYear + 1) >= 10 ? String.valueOf((monthOfYear + 1)) : ("0" + (monthOfYear + 1))) + "-" + ((dayOfMonth) >= 10 ? String.valueOf((dayOfMonth)) : ("0" + (dayOfMonth)))); try { birthday.setText(format.format(parse.parse(select))); } catch (ParseException e) { e.printStackTrace(); } } }, parse.parse(select).getYear() + 1900, parse.parse(select).getMonth() + 1, parse.parse(select).getDate()); dataDialog.getDatePicker().setMaxDate(System.currentTimeMillis()); dataDialog.show(); } catch (ParseException e) { e.printStackTrace(); } break; case R.id.complete://完成 String url = UrlUtils.urlPersonalInformation + BaseApplication.getInstance().getUserId(); UpLoadUtil util = new UpLoadUtil(url) { @Override public void httpStart() { progress = DialogUtils.startProgressDialog(progress, PersonalInformationChangeActivity.this); progress.setCanceledOnTouchOutside(false); progress.setCancelable(false); } @Override protected void httpSuccess(String result) { DialogUtils.dismissDialog(progress); PersonalInformationBean sData = JsonUtils.objectFromJson(result, PersonalInformationBean.class); BaseApplication.getInstance().getProfile().getData().getUser().setAvatar_url(sData.getData().getAvatar_url()); Profile profile = BaseApplication.getInstance().getProfile(); Profile.User user = profile.getData().getUser(); user.setId(sData.getData().getId()); user.setName(sData.getData().getName()); user.setNick_name(sData.getData().getNick_name()); user.setAvatar_url(sData.getData().getAvatar_url()); user.setEx_big_avatar_url(sData.getData().getEx_big_avatar_url()); user.setEmail(sData.getData().getEmail()); user.setLogin_mobile(sData.getData().getLogin_mobile()); user.setChat_account(sData.getData().getChat_account()); profile.getData().setUser(user); BaseApplication.getInstance().setProfile(profile); Intent data = new Intent(); data.putExtra("data", result); setResult(Constant.RESPONSE, data); Toast.makeText(PersonalInformationChangeActivity.this, getResources().getString(R.string.change_information_successful), Toast.LENGTH_SHORT).show(); finish(); } @Override protected void httpFailed(String result) { Toast.makeText(PersonalInformationChangeActivity.this, getResourceString(R.string.server_error), Toast.LENGTH_SHORT).show(); DialogUtils.dismissDialog(progress); } }; if (StringUtils.isNullOrBlanK(BaseApplication.getInstance().getUserId())) { Toast.makeText(PersonalInformationChangeActivity.this, getResources().getString(R.string.id_is_empty), Toast.LENGTH_SHORT).show(); return; } String sName = name.getText().toString(); if (StringUtils.isNullOrBlanK(sName)) { Toast.makeText(this, getResources().getString(R.string.name_can_not_be_empty), Toast.LENGTH_SHORT).show(); return; } String grade = textGrade.getText().toString(); if (StringUtils.isNullOrBlanK(grade)) { Toast.makeText(this, getResources().getString(R.string.grade_can_not_be_empty), Toast.LENGTH_SHORT).show(); return; } if (regionCity == null || regionProvince == null) { Toast.makeText(this, "请选择城市", Toast.LENGTH_SHORT).show(); return; } if (StringUtils.isNullOrBlanK(imageUrl)) { imageUrl = "http://qatime-testing.oss-cn-beijing.aliyuncs.com/avatars/e24edc0acfe48710fce2b2224bfee8ab.png"; Logger.e("使用默认头像"); } String birthday = select.equals(parse.format(new Date())) ? "" : select; String desc = describe.getText().toString(); Map<String, String> map = new HashMap<>(); map.put("name", sName); map.put("grade", grade); map.put("avatar", imageUrl); map.put("gender", gender); map.put("birthday", birthday); map.put("province_id", regionProvince.getId()); map.put("city_id", regionCity.getId()); if(schoolData!=null){ map.put("school_id", schoolData.getId() + ""); } map.put("desc", desc); Logger.e("--" + sName + "--" + grade + "--" + imageUrl + "--" + gender + "--" + birthday + "--" + desc + "--"); util.execute(map); break; } } private void showGradePickerDialog() { if (alertDialog == null) { final View view = View.inflate(PersonalInformationChangeActivity.this, R.layout.dialog_grade_picker, null); final WheelView grade = (WheelView) view.findViewById(R.id.grade); grade.setOffset(1); grade.setItems(grades); grade.setSeletion(grades.indexOf(textGrade.getText())); grade.setonItemClickListener(new WheelView.OnItemClickListener() { @Override public void onItemClick() { alertDialog.dismiss(); } }); AlertDialog.Builder builder = new AlertDialog.Builder(PersonalInformationChangeActivity.this); alertDialog = builder.create(); alertDialog.show(); alertDialog.setContentView(view); alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { textGrade.setText(grade.getSeletedItem()); } }); // WindowManager.LayoutParams attributes = alertDialog.getWindow().getAttributes(); // attributes.width= ScreenUtils.getScreenWidth(getApplicationContext())- DensityUtils.dp2px(getApplicationContext(),20)*2; // alertDialog.getWindow().setAttributes(attributes); } else { alertDialog.show(); } } private void initView() { headsculpture = (ImageView) findViewById(R.id.head_sculpture); replace = findViewById(R.id.replace); name = (EditText) findViewById(R.id.name); name.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { return event.getKeyCode() == KeyEvent.KEYCODE_ENTER; } }); men = (TextView) findViewById(R.id.men); women = (TextView) findViewById(R.id.women); textGrade = (TextView) findViewById(R.id.text_grade); describe = (EditText) findViewById(R.id.describe); describe.setFilters(new InputFilter[]{new InputFilter.LengthFilter(30)}); name.setFilters(new InputFilter[]{new InputFilter.LengthFilter(7)}); birthday = (TextView) findViewById(R.id.birthday); birthdayView = findViewById(R.id.birthday_view); gradeView = findViewById(R.id.grade_view); complete = (TextView) findViewById(R.id.complete); region = (TextView) findViewById(R.id.region); regionView = findViewById(R.id.region_view); school = (TextView) findViewById(R.id.school); schoolView = findViewById(R.id.school_view); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == Constant.REQUEST_PICTURE_SELECT) { if (resultCode == Constant.RESPONSE_CAMERA) {//拍照返回的照片 if (data != null) { String url = data.getStringExtra("url"); if (url != null && !StringUtils.isNullOrBlanK(url)) { Uri uri = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { uri = FileProvider.getUriForFile(this, "com.qatime.player.fileprovider", new File(url)); // Bitmap bitmap = BitmapFactory.decodeFile(url); // uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null, null)); // bitmap.recycle(); } else { uri = Uri.fromFile(new File(url)); } Intent intent = new Intent(PersonalInformationChangeActivity.this, CropImageActivity.class); intent.putExtra("id", uri.toString()); startActivityForResult(intent, Constant.PHOTO_CROP); } } } else if (resultCode == Constant.RESPONSE_PICTURE_SELECT) {//选择照片返回的照片 if (data != null) { ImageItem image = (ImageItem) data.getSerializableExtra("data"); if (image != null && !StringUtils.isNullOrBlanK(image.imageId)) { Intent intent = new Intent(PersonalInformationChangeActivity.this, CropImageActivity.class); intent.putExtra("id", "content://media/external/images/media/" + image.imageId); startActivityForResult(intent, Constant.PHOTO_CROP); } } } } else if (resultCode == Constant.PHOTO_CROP) { Logger.e("裁剪", "回来"); if (data != null) { imageUrl = data.getStringExtra("bitmap"); Logger.e(imageUrl); if (new File(imageUrl).exists()) { Logger.e("回来成功"); } if (!StringUtils.isNullOrBlanK(imageUrl)) { Glide.with(this).load(Uri.fromFile(new File(imageUrl))).transform(new GlideCircleTransform(this)).crossFade().into(headsculpture); } } } else if (requestCode == Constant.REQUEST_REGION_SELECT && resultCode == Constant.RESPONSE_REGION_SELECT) { regionCity = (CityBean.Data) data.getSerializableExtra("region_city"); regionProvince = (ProvincesBean.DataBean) data.getSerializableExtra("region_province"); if (regionCity != null && regionProvince != null) { region.setText(regionProvince.getName() + regionCity.getName()); } } else if (requestCode == Constant.REQUEST_SCHOOL_SELECT && resultCode == Constant.RESPONSE_SCHOOL_SELECT) { schoolData = (SchoolBean.Data) data.getSerializableExtra("school"); if (schoolData != null) { school.setText(schoolData.getName()); } } } @Override protected void onResume() { super.onResume(); MobclickAgent.onResume(this); } @Override protected void onPause() { super.onPause(); MobclickAgent.onPause(this); } }
UTF-8
Java
21,457
java
PersonalInformationChangeActivity.java
Java
[ { "context": " new HashMap<>();\n\n map.put(\"name\", sName);\n map.put(\"grade\", grade);\n ", "end": 14379, "score": 0.8381556868553162, "start": 14378, "tag": "NAME", "value": "s" } ]
null
[]
package cn.qatime.player.activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.content.FileProvider; import android.text.Editable; import android.text.InputFilter; import android.text.Selection; import android.view.KeyEvent; import android.view.View; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.orhanobut.logger.Logger; import com.umeng.analytics.MobclickAgent; import java.io.File; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import cn.qatime.player.R; import cn.qatime.player.base.BaseActivity; import cn.qatime.player.base.BaseApplication; import cn.qatime.player.utils.Constant; import cn.qatime.player.utils.UpLoadUtil; import cn.qatime.player.utils.UrlUtils; import libraryextra.bean.CityBean; import libraryextra.bean.GradeBean; import libraryextra.bean.ImageItem; import libraryextra.bean.PersonalInformationBean; import libraryextra.bean.Profile; import libraryextra.bean.ProvincesBean; import libraryextra.bean.SchoolBean; import libraryextra.transformation.GlideCircleTransform; import libraryextra.utils.DialogUtils; import libraryextra.utils.FileUtil; import libraryextra.utils.JsonUtils; import libraryextra.utils.StringUtils; import libraryextra.view.CustomProgressDialog; import libraryextra.view.MDatePickerDialog; import libraryextra.view.WheelView; public class PersonalInformationChangeActivity extends BaseActivity implements View.OnClickListener { ImageView headsculpture; View replace; EditText name; TextView men; TextView women; TextView textGrade; TextView complete; private EditText describe; private TextView birthday; private TextView region; private View regionView; private View birthdayView; private View gradeView; private SimpleDateFormat parse = new SimpleDateFormat("yyyy-MM-dd"); private SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日"); private String imageUrl = "http://qatime-testing.oss-cn-beijing.aliyuncs.com/avatars/e24edc0acfe48710fce2b2224bfee8ab.png"; private String select = "2000-01-01";//生日所选日期 private CustomProgressDialog progress; private AlertDialog alertDialog; private String gender = ""; private List<String> grades; private ProvincesBean.DataBean regionProvince; private CityBean.Data regionCity; private ProvincesBean provincesBean; private CityBean cityBean; private SchoolBean schoolBean; private TextView school; private View schoolView; private SchoolBean.Data schoolData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_personal_information_change); setTitles(getResources().getString(R.string.change_information)); initView(); provincesBean = JsonUtils.objectFromJson(FileUtil.readFile(getFilesDir() + "/provinces.txt").toString(), ProvincesBean.class); cityBean = JsonUtils.objectFromJson(FileUtil.readFile(getFilesDir() + "/cities.txt").toString(), CityBean.class); schoolBean = JsonUtils.objectFromJson(FileUtil.readFile(getFilesDir() + "/school.txt").toString(), SchoolBean.class); String gradeString = FileUtil.readFile(getFilesDir() + "/grade.txt"); // LogUtils.e("班级基础信息" + gradeString); grades = new ArrayList<>(); if (!StringUtils.isNullOrBlanK(gradeString)) { GradeBean gradeBean = JsonUtils.objectFromJson(gradeString, GradeBean.class); grades = gradeBean.getData().getGrades(); } PersonalInformationBean data = (PersonalInformationBean) getIntent().getSerializableExtra("data"); if (data != null && data.getData() != null) { initData(data); } replace.setOnClickListener(this); men.setOnClickListener(this); women.setOnClickListener(this); birthdayView.setOnClickListener(this); complete.setOnClickListener(this); gradeView.setOnClickListener(this); regionView.setOnClickListener(this); schoolView.setOnClickListener(this); } private void initData(PersonalInformationBean data) { Glide.with(PersonalInformationChangeActivity.this).load(data.getData().getAvatar_url()).placeholder(R.mipmap.personal_information_head).transform(new GlideCircleTransform(PersonalInformationChangeActivity.this)).crossFade().into(headsculpture); name.setText(data.getData().getName()); Editable etext = name.getText(); imageUrl = data.getData().getAvatar_url(); Selection.setSelection(etext, etext.length()); if (!StringUtils.isNullOrBlanK(data.getData().getGender())) { if (data.getData().getGender().equals("male")) { men.setSelected(true); women.setSelected(false); } else { men.setSelected(false); women.setSelected(true); } } if (!StringUtils.isNullOrBlanK(data.getData().getBirthday())) { try { birthday.setText(format.format(parse.parse(data.getData().getBirthday()))); select = data.getData().getBirthday(); } catch (ParseException e) { e.printStackTrace(); } } else { birthday.setText(format.format(new Date())); select = parse.format(new Date()); } if (!StringUtils.isNullOrBlanK(data.getData().getGrade())) { for (int i = 0; i < grades.size(); i++) { if (data.getData().getGrade().equals(grades.get(i))) { textGrade.setText(data.getData().getGrade()); break; } } } if (provincesBean != null && provincesBean.getData() != null) { for (int i = 0; i < provincesBean.getData().size(); i++) { if (provincesBean.getData().get(i).getId().equals(data.getData().getProvince())) { regionProvince = provincesBean.getData().get(i); break; } } } if (cityBean != null && cityBean.getData() != null) { for (int i = 0; i < cityBean.getData().size(); i++) { if (cityBean.getData().get(i).getId().equals(data.getData().getCity())) { regionCity = cityBean.getData().get(i); break; } } } if (regionCity != null && regionProvince != null) { region.setText(regionProvince.getName() + regionCity.getName()); } if (schoolBean != null && schoolBean.getData() != null) { for (int i = 0; i < schoolBean.getData().size(); i++) { if (schoolBean.getData().get(i).getId() == data.getData().getSchool()) { schoolData = schoolBean.getData().get(i); school.setText(schoolBean.getData().get(i).getName()); break; } } } describe.setText(data.getData().getDesc()); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.region_view: Intent regionIntent = new Intent(this, RegionSelectActivity1.class); // if (regionProvince != null && regionCity != null) { // regionIntent.putExtra("region_province", regionProvince); // regionIntent.putExtra("region_city", regionCity); // } startActivityForResult(regionIntent, Constant.REQUEST_REGION_SELECT); break; case R.id.school_view: Intent schoolIntent = new Intent(this, SchoolSelectActivity.class); startActivityForResult(schoolIntent, Constant.REQUEST_SCHOOL_SELECT); break; case R.id.men: men.setSelected(true); women.setSelected(false); gender = "male"; break; case R.id.women: women.setSelected(true); men.setSelected(false); gender = "female"; break; case R.id.grade_view: showGradePickerDialog(); break; case R.id.replace://去选择图片 final Intent intent = new Intent(PersonalInformationChangeActivity.this, PictureSelectActivity.class); startActivityForResult(intent, Constant.REQUEST_PICTURE_SELECT); break; case R.id.birthday_view://生日 try { MDatePickerDialog dataDialog = new MDatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { select = (year + "-" + ((monthOfYear + 1) >= 10 ? String.valueOf((monthOfYear + 1)) : ("0" + (monthOfYear + 1))) + "-" + ((dayOfMonth) >= 10 ? String.valueOf((dayOfMonth)) : ("0" + (dayOfMonth)))); try { birthday.setText(format.format(parse.parse(select))); } catch (ParseException e) { e.printStackTrace(); } } }, parse.parse(select).getYear() + 1900, parse.parse(select).getMonth() + 1, parse.parse(select).getDate()); dataDialog.getDatePicker().setMaxDate(System.currentTimeMillis()); dataDialog.show(); } catch (ParseException e) { e.printStackTrace(); } break; case R.id.complete://完成 String url = UrlUtils.urlPersonalInformation + BaseApplication.getInstance().getUserId(); UpLoadUtil util = new UpLoadUtil(url) { @Override public void httpStart() { progress = DialogUtils.startProgressDialog(progress, PersonalInformationChangeActivity.this); progress.setCanceledOnTouchOutside(false); progress.setCancelable(false); } @Override protected void httpSuccess(String result) { DialogUtils.dismissDialog(progress); PersonalInformationBean sData = JsonUtils.objectFromJson(result, PersonalInformationBean.class); BaseApplication.getInstance().getProfile().getData().getUser().setAvatar_url(sData.getData().getAvatar_url()); Profile profile = BaseApplication.getInstance().getProfile(); Profile.User user = profile.getData().getUser(); user.setId(sData.getData().getId()); user.setName(sData.getData().getName()); user.setNick_name(sData.getData().getNick_name()); user.setAvatar_url(sData.getData().getAvatar_url()); user.setEx_big_avatar_url(sData.getData().getEx_big_avatar_url()); user.setEmail(sData.getData().getEmail()); user.setLogin_mobile(sData.getData().getLogin_mobile()); user.setChat_account(sData.getData().getChat_account()); profile.getData().setUser(user); BaseApplication.getInstance().setProfile(profile); Intent data = new Intent(); data.putExtra("data", result); setResult(Constant.RESPONSE, data); Toast.makeText(PersonalInformationChangeActivity.this, getResources().getString(R.string.change_information_successful), Toast.LENGTH_SHORT).show(); finish(); } @Override protected void httpFailed(String result) { Toast.makeText(PersonalInformationChangeActivity.this, getResourceString(R.string.server_error), Toast.LENGTH_SHORT).show(); DialogUtils.dismissDialog(progress); } }; if (StringUtils.isNullOrBlanK(BaseApplication.getInstance().getUserId())) { Toast.makeText(PersonalInformationChangeActivity.this, getResources().getString(R.string.id_is_empty), Toast.LENGTH_SHORT).show(); return; } String sName = name.getText().toString(); if (StringUtils.isNullOrBlanK(sName)) { Toast.makeText(this, getResources().getString(R.string.name_can_not_be_empty), Toast.LENGTH_SHORT).show(); return; } String grade = textGrade.getText().toString(); if (StringUtils.isNullOrBlanK(grade)) { Toast.makeText(this, getResources().getString(R.string.grade_can_not_be_empty), Toast.LENGTH_SHORT).show(); return; } if (regionCity == null || regionProvince == null) { Toast.makeText(this, "请选择城市", Toast.LENGTH_SHORT).show(); return; } if (StringUtils.isNullOrBlanK(imageUrl)) { imageUrl = "http://qatime-testing.oss-cn-beijing.aliyuncs.com/avatars/e24edc0acfe48710fce2b2224bfee8ab.png"; Logger.e("使用默认头像"); } String birthday = select.equals(parse.format(new Date())) ? "" : select; String desc = describe.getText().toString(); Map<String, String> map = new HashMap<>(); map.put("name", sName); map.put("grade", grade); map.put("avatar", imageUrl); map.put("gender", gender); map.put("birthday", birthday); map.put("province_id", regionProvince.getId()); map.put("city_id", regionCity.getId()); if(schoolData!=null){ map.put("school_id", schoolData.getId() + ""); } map.put("desc", desc); Logger.e("--" + sName + "--" + grade + "--" + imageUrl + "--" + gender + "--" + birthday + "--" + desc + "--"); util.execute(map); break; } } private void showGradePickerDialog() { if (alertDialog == null) { final View view = View.inflate(PersonalInformationChangeActivity.this, R.layout.dialog_grade_picker, null); final WheelView grade = (WheelView) view.findViewById(R.id.grade); grade.setOffset(1); grade.setItems(grades); grade.setSeletion(grades.indexOf(textGrade.getText())); grade.setonItemClickListener(new WheelView.OnItemClickListener() { @Override public void onItemClick() { alertDialog.dismiss(); } }); AlertDialog.Builder builder = new AlertDialog.Builder(PersonalInformationChangeActivity.this); alertDialog = builder.create(); alertDialog.show(); alertDialog.setContentView(view); alertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { textGrade.setText(grade.getSeletedItem()); } }); // WindowManager.LayoutParams attributes = alertDialog.getWindow().getAttributes(); // attributes.width= ScreenUtils.getScreenWidth(getApplicationContext())- DensityUtils.dp2px(getApplicationContext(),20)*2; // alertDialog.getWindow().setAttributes(attributes); } else { alertDialog.show(); } } private void initView() { headsculpture = (ImageView) findViewById(R.id.head_sculpture); replace = findViewById(R.id.replace); name = (EditText) findViewById(R.id.name); name.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { return event.getKeyCode() == KeyEvent.KEYCODE_ENTER; } }); men = (TextView) findViewById(R.id.men); women = (TextView) findViewById(R.id.women); textGrade = (TextView) findViewById(R.id.text_grade); describe = (EditText) findViewById(R.id.describe); describe.setFilters(new InputFilter[]{new InputFilter.LengthFilter(30)}); name.setFilters(new InputFilter[]{new InputFilter.LengthFilter(7)}); birthday = (TextView) findViewById(R.id.birthday); birthdayView = findViewById(R.id.birthday_view); gradeView = findViewById(R.id.grade_view); complete = (TextView) findViewById(R.id.complete); region = (TextView) findViewById(R.id.region); regionView = findViewById(R.id.region_view); school = (TextView) findViewById(R.id.school); schoolView = findViewById(R.id.school_view); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == Constant.REQUEST_PICTURE_SELECT) { if (resultCode == Constant.RESPONSE_CAMERA) {//拍照返回的照片 if (data != null) { String url = data.getStringExtra("url"); if (url != null && !StringUtils.isNullOrBlanK(url)) { Uri uri = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { uri = FileProvider.getUriForFile(this, "com.qatime.player.fileprovider", new File(url)); // Bitmap bitmap = BitmapFactory.decodeFile(url); // uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, null, null)); // bitmap.recycle(); } else { uri = Uri.fromFile(new File(url)); } Intent intent = new Intent(PersonalInformationChangeActivity.this, CropImageActivity.class); intent.putExtra("id", uri.toString()); startActivityForResult(intent, Constant.PHOTO_CROP); } } } else if (resultCode == Constant.RESPONSE_PICTURE_SELECT) {//选择照片返回的照片 if (data != null) { ImageItem image = (ImageItem) data.getSerializableExtra("data"); if (image != null && !StringUtils.isNullOrBlanK(image.imageId)) { Intent intent = new Intent(PersonalInformationChangeActivity.this, CropImageActivity.class); intent.putExtra("id", "content://media/external/images/media/" + image.imageId); startActivityForResult(intent, Constant.PHOTO_CROP); } } } } else if (resultCode == Constant.PHOTO_CROP) { Logger.e("裁剪", "回来"); if (data != null) { imageUrl = data.getStringExtra("bitmap"); Logger.e(imageUrl); if (new File(imageUrl).exists()) { Logger.e("回来成功"); } if (!StringUtils.isNullOrBlanK(imageUrl)) { Glide.with(this).load(Uri.fromFile(new File(imageUrl))).transform(new GlideCircleTransform(this)).crossFade().into(headsculpture); } } } else if (requestCode == Constant.REQUEST_REGION_SELECT && resultCode == Constant.RESPONSE_REGION_SELECT) { regionCity = (CityBean.Data) data.getSerializableExtra("region_city"); regionProvince = (ProvincesBean.DataBean) data.getSerializableExtra("region_province"); if (regionCity != null && regionProvince != null) { region.setText(regionProvince.getName() + regionCity.getName()); } } else if (requestCode == Constant.REQUEST_SCHOOL_SELECT && resultCode == Constant.RESPONSE_SCHOOL_SELECT) { schoolData = (SchoolBean.Data) data.getSerializableExtra("school"); if (schoolData != null) { school.setText(schoolData.getName()); } } } @Override protected void onResume() { super.onResume(); MobclickAgent.onResume(this); } @Override protected void onPause() { super.onPause(); MobclickAgent.onPause(this); } }
21,457
0.584657
0.581658
456
45.796051
34.367149
252
false
false
0
0
0
0
0
0
0.765351
false
false
11
f358a648dc07a285ec99465393686b60dc5701ac
23,502,061,110,878
8fff393afa2da75cbc25c2a1baa1ba2a7cbf627a
/AM_Rkanoid/src/puppynoid/modifiers/KeyEventModifier.java
3ab42b3a0fb0cdce84a1825b79b18d85bfce971f
[]
no_license
AlessioMoraschini/ScreepT-public
https://github.com/AlessioMoraschini/ScreepT-public
8fbb699d2c8e7e7739303c38156476e63e45f498
099a239a1cb678586bc6cf8b08035b2297c9e3a7
refs/heads/master
2023-04-01T14:58:39.550000
2023-03-15T23:26:13
2023-03-15T23:26:13
349,549,969
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package puppynoid.modifiers; import java.awt.event.KeyEvent; @FunctionalInterface public interface KeyEventModifier { public void applyModifier(KeyEvent event); }
UTF-8
Java
176
java
KeyEventModifier.java
Java
[]
null
[]
package puppynoid.modifiers; import java.awt.event.KeyEvent; @FunctionalInterface public interface KeyEventModifier { public void applyModifier(KeyEvent event); }
176
0.778409
0.778409
9
17.555555
16.486433
43
false
false
0
0
0
0
0
0
0.444444
false
false
11
21b0db4137cb892ca97b3f9113e1cf4416443bcb
13,340,168,427,121
a8c27091412a0155497bb975825d08e490fc8111
/algo-study/src/main/java/com/junhua/algorithm/leetcode/datastructure/linkedList/PalindromeLinkedList.java
4b5c256e3e297535f058eda0617aa60a920d823e
[ "MIT" ]
permissive
Junhua91/tornesol
https://github.com/Junhua91/tornesol
4cd7f6cf14245a03ff36a2e79a34aa6782d02b01
42bde375149654a9f2e902ce182b6a30426f22d8
refs/heads/master
2022-12-21T15:55:09.458000
2019-10-30T07:00:46
2019-10-30T07:00:46
153,586,630
4
0
MIT
false
2022-12-16T08:31:48
2018-10-18T08:05:32
2019-11-04T03:40:00
2022-12-16T08:31:45
1,989
3
0
16
Java
false
false
package com.junhua.algorithm.leetcode.datastructure.linkedList; import java.util.ArrayList; import java.util.List; public class PalindromeLinkedList { /** * space O(N) * * @param head * @return */ static public boolean isPalindrome(ListNode head) { if (head == null) return false; List<Integer> list = new ArrayList<>(); while (head != null) { list.add(head.val); head = head.next; } int start = 0; int end = list.size() - 1; while (start <= end) { if (!list.get(start).equals(list.get(end))) return false; start++; end--; } return true; } static public boolean isPalindrome2(ListNode head) { ListNode fast = head; ListNode slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; } if (fast != null) slow = slow.next; cutListNode(head, slow); return isEqual(head, reverse(slow)); } static public void cutListNode(ListNode head, ListNode slow) { while (head.next.val != slow.val) { head = head.next; } head.next = null; } static public boolean isEqual(ListNode l1, ListNode l2) { while (l1 != null && l2 != null) { if (l1.val != l2.val) return false; l1 = l1.next; l2 = l2.next; } return true; } static public ListNode reverse(ListNode cur) { ListNode pre = null; while (cur != null) { ListNode temp = cur.next; cur.next = pre; pre = cur; cur = temp; } return pre; } public static void main(String[] args) { ListNode listNode = new ListNode(1) .setNext(new ListNode(2).setNext(new ListNode(2).setNext(new ListNode(1)))); ListNode listNode1 = new ListNode(-129).setNext(new ListNode(-129)); ListNode testNode = new ListNode(1).setNext(new ListNode(2).setNext(new ListNode(3))); ListNode reverseNode = reverse(testNode); System.out.println(isPalindrome2(listNode)); System.out.println(-129 == -129); } }
UTF-8
Java
2,297
java
PalindromeLinkedList.java
Java
[]
null
[]
package com.junhua.algorithm.leetcode.datastructure.linkedList; import java.util.ArrayList; import java.util.List; public class PalindromeLinkedList { /** * space O(N) * * @param head * @return */ static public boolean isPalindrome(ListNode head) { if (head == null) return false; List<Integer> list = new ArrayList<>(); while (head != null) { list.add(head.val); head = head.next; } int start = 0; int end = list.size() - 1; while (start <= end) { if (!list.get(start).equals(list.get(end))) return false; start++; end--; } return true; } static public boolean isPalindrome2(ListNode head) { ListNode fast = head; ListNode slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; } if (fast != null) slow = slow.next; cutListNode(head, slow); return isEqual(head, reverse(slow)); } static public void cutListNode(ListNode head, ListNode slow) { while (head.next.val != slow.val) { head = head.next; } head.next = null; } static public boolean isEqual(ListNode l1, ListNode l2) { while (l1 != null && l2 != null) { if (l1.val != l2.val) return false; l1 = l1.next; l2 = l2.next; } return true; } static public ListNode reverse(ListNode cur) { ListNode pre = null; while (cur != null) { ListNode temp = cur.next; cur.next = pre; pre = cur; cur = temp; } return pre; } public static void main(String[] args) { ListNode listNode = new ListNode(1) .setNext(new ListNode(2).setNext(new ListNode(2).setNext(new ListNode(1)))); ListNode listNode1 = new ListNode(-129).setNext(new ListNode(-129)); ListNode testNode = new ListNode(1).setNext(new ListNode(2).setNext(new ListNode(3))); ListNode reverseNode = reverse(testNode); System.out.println(isPalindrome2(listNode)); System.out.println(-129 == -129); } }
2,297
0.53374
0.518938
96
22.927084
22.335157
94
false
false
0
0
0
0
0
0
0.4375
false
false
11
fd41a5a92cfd53663c7798a1f21c3f928223d7ed
27,943,057,278,258
33f3bfd1d3e52c60218197930a7a91a6c2e72f98
/tztf/src/main/java/cn/movinginfo/tztf/sen/mapper/DangerPointMapper.java
26e36a801d072c6a214b6bee21ef7f6fadacc140
[]
no_license
TomZD/tzqx
https://github.com/TomZD/tzqx
f1840e5e761a32cb3ff3485ad31988224f767622
76ad3a74aef642e231e72e40826401034cedc775
refs/heads/master
2022-12-08T20:10:29.578000
2020-08-30T09:50:08
2020-08-30T09:50:08
290,946,669
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.movinginfo.tztf.sen.mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import cn.movinginfo.tztf.sen.domain.DangerPoint; import tk.mybatis.mapper.common.Mapper; import java.util.List; /** * @description: * @author: autoCode * @history: */ public interface DangerPointMapper extends Mapper<DangerPoint>{ //查询所有隐患点 @Select("SELECT * FROM sen_t_danger_point") public List<DangerPoint> selectAll(); @Select("select * from sen_t_danger_point where CONCAT(',',rel_station,',') LIKE concat('%,',#{relStation},',%') AND valid=1") @Results(value = { @Result(property = "historicalDisaster", column = "historical_disaster"), @Result(property = "dangerTypeId", column = "danger_type_id"), @Result(property = "relStation", column = "rel_station"), @Result(property = "alertruleId", column = "alertrule_id"), @Result(property = "alertruleTwoId", column = "alertruleTwo_id"), @Result(property = "alertruleThreeId", column = "alertruleThree_id"), @Result(property = "affectTown", column = "affect_town"), @Result(property = "watershedPopulation", column = "watershed_population"), @Result(property = "riverLength", column = "river_length"), @Result(property = "alertruleThreeId", column = "alertruleThree_id"), }) public List<DangerPoint> getDangerPointByRelStation(@Param("relStation")String relStation); @Select("Select * from sen_t_danger_point where longitude=#{longitude} and latitude=#{latitude} and danger_type_id=#{dangerTypeId} and valid=1") @Results(value = { @Result(property = "historicalDisaster", column = "historical_disaster"), @Result(property = "dangerTypeId", column = "danger_type_id"), @Result(property = "relStation", column = "rel_station"), @Result(property = "alertruleId", column = "alertrule_id"), @Result(property = "alertruleTwoId", column = "alertruleTwo_id"), @Result(property = "alertruleThreeId", column = "alertruleThree_id"), @Result(property = "affectTown", column = "affect_town"), @Result(property = "watershedPopulation", column = "watershed_population"), @Result(property = "riverLength", column = "river_length"), @Result(property = "alertruleThreeId", column = "alertruleThree_id"), }) DangerPoint getDangerPointByLonLatTypeId(@Param("longitude")String longitude,@Param("latitude")String latitude,@Param("dangerTypeId")Long dangerTypeId); @Select("SELECT * FROM sen_t_danger_point WHERE danger_type_id =#{dangerTypeId} and valid=1 LIMIT 1") @Results(value = { @Result(property = "historicalDisaster", column = "historical_disaster"), @Result(property = "dangerTypeId", column = "danger_type_id"), @Result(property = "relStation", column = "rel_station"), @Result(property = "alertruleId", column = "alertrule_id"), @Result(property = "alertruleTwoId", column = "alertruleTwo_id"), @Result(property = "alertruleThreeId", column = "alertruleThree_id"), @Result(property = "affectTown", column = "affect_town"), @Result(property = "watershedPopulation", column = "watershed_population"), @Result(property = "riverLength", column = "river_length"), @Result(property = "alertruleThreeId", column = "alertruleThree_id"), }) public DangerPoint getFirstDangerPointByDangerTypeId(@Param("dangerTypeId")Long dangerTypeId); @Select("SELECT * FROM sen_t_danger_point WHERE danger_type_id =#{dangerTypeId} and valid=1 LIMIT 1") @Results(value = { @Result(property = "historicalDisaster", column = "historical_disaster"), @Result(property = "dangerTypeId", column = "danger_type_id"), @Result(property = "relStation", column = "rel_station"), @Result(property = "alertruleId", column = "alertrule_id"), @Result(property = "alertruleTwoId", column = "alertruleTwo_id"), @Result(property = "alertruleThreeId", column = "alertruleThree_id"), @Result(property = "affectTown", column = "affect_town"), @Result(property = "watershedPopulation", column = "watershed_population"), @Result(property = "riverLength", column = "river_length"), @Result(property = "alertruleThreeId", column = "alertruleThree_id"), }) public DangerPoint save(DangerPoint dangerPoint); }
UTF-8
Java
4,665
java
DangerPointMapper.java
Java
[ { "context": "rt java.util.List;\n\n/**\n* @description:\n* @author: autoCode\n* @history:\n*/\npublic interface DangerPointMapper", "end": 375, "score": 0.9994434118270874, "start": 367, "tag": "USERNAME", "value": "autoCode" } ]
null
[]
package cn.movinginfo.tztf.sen.mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import cn.movinginfo.tztf.sen.domain.DangerPoint; import tk.mybatis.mapper.common.Mapper; import java.util.List; /** * @description: * @author: autoCode * @history: */ public interface DangerPointMapper extends Mapper<DangerPoint>{ //查询所有隐患点 @Select("SELECT * FROM sen_t_danger_point") public List<DangerPoint> selectAll(); @Select("select * from sen_t_danger_point where CONCAT(',',rel_station,',') LIKE concat('%,',#{relStation},',%') AND valid=1") @Results(value = { @Result(property = "historicalDisaster", column = "historical_disaster"), @Result(property = "dangerTypeId", column = "danger_type_id"), @Result(property = "relStation", column = "rel_station"), @Result(property = "alertruleId", column = "alertrule_id"), @Result(property = "alertruleTwoId", column = "alertruleTwo_id"), @Result(property = "alertruleThreeId", column = "alertruleThree_id"), @Result(property = "affectTown", column = "affect_town"), @Result(property = "watershedPopulation", column = "watershed_population"), @Result(property = "riverLength", column = "river_length"), @Result(property = "alertruleThreeId", column = "alertruleThree_id"), }) public List<DangerPoint> getDangerPointByRelStation(@Param("relStation")String relStation); @Select("Select * from sen_t_danger_point where longitude=#{longitude} and latitude=#{latitude} and danger_type_id=#{dangerTypeId} and valid=1") @Results(value = { @Result(property = "historicalDisaster", column = "historical_disaster"), @Result(property = "dangerTypeId", column = "danger_type_id"), @Result(property = "relStation", column = "rel_station"), @Result(property = "alertruleId", column = "alertrule_id"), @Result(property = "alertruleTwoId", column = "alertruleTwo_id"), @Result(property = "alertruleThreeId", column = "alertruleThree_id"), @Result(property = "affectTown", column = "affect_town"), @Result(property = "watershedPopulation", column = "watershed_population"), @Result(property = "riverLength", column = "river_length"), @Result(property = "alertruleThreeId", column = "alertruleThree_id"), }) DangerPoint getDangerPointByLonLatTypeId(@Param("longitude")String longitude,@Param("latitude")String latitude,@Param("dangerTypeId")Long dangerTypeId); @Select("SELECT * FROM sen_t_danger_point WHERE danger_type_id =#{dangerTypeId} and valid=1 LIMIT 1") @Results(value = { @Result(property = "historicalDisaster", column = "historical_disaster"), @Result(property = "dangerTypeId", column = "danger_type_id"), @Result(property = "relStation", column = "rel_station"), @Result(property = "alertruleId", column = "alertrule_id"), @Result(property = "alertruleTwoId", column = "alertruleTwo_id"), @Result(property = "alertruleThreeId", column = "alertruleThree_id"), @Result(property = "affectTown", column = "affect_town"), @Result(property = "watershedPopulation", column = "watershed_population"), @Result(property = "riverLength", column = "river_length"), @Result(property = "alertruleThreeId", column = "alertruleThree_id"), }) public DangerPoint getFirstDangerPointByDangerTypeId(@Param("dangerTypeId")Long dangerTypeId); @Select("SELECT * FROM sen_t_danger_point WHERE danger_type_id =#{dangerTypeId} and valid=1 LIMIT 1") @Results(value = { @Result(property = "historicalDisaster", column = "historical_disaster"), @Result(property = "dangerTypeId", column = "danger_type_id"), @Result(property = "relStation", column = "rel_station"), @Result(property = "alertruleId", column = "alertrule_id"), @Result(property = "alertruleTwoId", column = "alertruleTwo_id"), @Result(property = "alertruleThreeId", column = "alertruleThree_id"), @Result(property = "affectTown", column = "affect_town"), @Result(property = "watershedPopulation", column = "watershed_population"), @Result(property = "riverLength", column = "river_length"), @Result(property = "alertruleThreeId", column = "alertruleThree_id"), }) public DangerPoint save(DangerPoint dangerPoint); }
4,665
0.655558
0.654268
86
53.081394
36.923622
156
false
false
0
0
0
0
0
0
1.383721
false
false
11
daa2b5cf94f2aa16010cd43cfe020e2edc00d3f9
13,443,247,697,604
3438e8c139a5833836a91140af412311aebf9e86
/chrome/android/java/src/org/chromium/chrome/browser/ntp/cards/SignInPromo.java
e57c679349a2d57193969408d3e6638c21911907
[ "BSD-3-Clause" ]
permissive
Exstream-OpenSource/Chromium
https://github.com/Exstream-OpenSource/Chromium
345b4336b2fbc1d5609ac5a67dbf361812b84f54
718ca933938a85c6d5548c5fad97ea7ca1128751
refs/heads/master
2022-12-21T20:07:40.786000
2016-10-18T04:53:43
2016-10-18T04:53:43
71,210,435
0
2
BSD-3-Clause
false
2022-12-18T12:14:22
2016-10-18T04:58:13
2016-10-18T04:58:13
2022-12-18T12:14:22
713,301
0
1
1
null
false
false
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.ntp.cards; import android.content.Context; import android.support.annotation.DrawableRes; import android.support.annotation.StringRes; import android.support.v7.widget.RecyclerView; import org.chromium.base.ContextUtils; import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.R; import org.chromium.chrome.browser.ntp.UiConfig; import org.chromium.chrome.browser.ntp.snippets.SnippetArticle; import org.chromium.chrome.browser.preferences.ChromePreferenceManager; import org.chromium.chrome.browser.signin.AccountSigninActivity; import org.chromium.chrome.browser.signin.SigninAccessPoint; import org.chromium.chrome.browser.signin.SigninManager; /** * Shows a card prompting the user to sign in. This item is also a {@link TreeNode}, and calling * {@link #hide()} or {@link #maybeShow()} will control its visibility. */ public class SignInPromo extends ChildNode implements StatusCardViewHolder.DataSource { /** * Whether the promo should be visible, according to the parent object. * * The {@link NewTabPageAdapter} calls to {@link #maybeShow()} and {@link #hide()} modify this * when the sign in status changes. */ private boolean mVisible; /** * Whether the user has seen the promo and dismissed it at some point. When this is set, * the promo will never be shown. */ private boolean mDismissed; public SignInPromo(NodeParent parent) { super(parent); mDismissed = ChromePreferenceManager.getInstance(ContextUtils.getApplicationContext()) .getNewTabPageSigninPromoDismissed(); SigninManager signinManager = SigninManager.get(ContextUtils.getApplicationContext()); mVisible = signinManager.isSignInAllowed() && !signinManager.isSignedInOnNative(); } @Override public int getItemCount() { if (!isShown()) return 0; return 1; } @Override @ItemViewType public int getItemViewType(int position) { checkIndex(position); return ItemViewType.PROMO; } @Override public void onBindViewHolder(NewTabPageViewHolder holder, int position) { checkIndex(position); assert holder instanceof StatusCardViewHolder; ((StatusCardViewHolder) holder).onBindViewHolder(this); } @Override public SnippetArticle getSuggestionAt(int position) { checkIndex(position); return null; } @Override @StringRes public int getHeader() { return R.string.snippets_disabled_generic_prompt; } @Override @StringRes public int getDescription() { return R.string.snippets_disabled_signed_out_instructions; } @Override @StringRes public int getActionLabel() { return R.string.sign_in_button; } @Override public void performAction(Context context) { AccountSigninActivity.startIfAllowed(context, SigninAccessPoint.NTP_CONTENT_SUGGESTIONS); } public boolean isShown() { return !mDismissed && mVisible; } /** Attempts to show the sign in promo. If the user dismissed it before, it will not be shown.*/ public void maybeShow() { if (mVisible) return; mVisible = true; if (mDismissed) return; RecordUserAction.record("Signin_Impression_FromNTPContentSuggestions"); notifyItemInserted(0); } /** Hides the sign in promo. */ public void hide() { if (!mVisible) return; mVisible = false; if (mDismissed) return; notifyItemRemoved(0); } /** Hides the sign in promo and sets a preference to make sure it is not shown again. */ public void dismiss() { hide(); mDismissed = true; ChromePreferenceManager.getInstance(ContextUtils.getApplicationContext()) .setNewTabPageSigninPromoDismissed(true); } /** * View Holder for {@link SignInPromo}. */ public static class ViewHolder extends StatusCardViewHolder { private final int mSeparationSpaceSize; public ViewHolder(NewTabPageRecyclerView parent, UiConfig config) { super(parent, config); mSeparationSpaceSize = parent.getResources().getDimensionPixelSize( R.dimen.ntp_sign_in_promo_margin_top); } @DrawableRes @Override protected int selectBackground(boolean hasCardAbove, boolean hasCardBelow) { assert !hasCardBelow; if (hasCardAbove) return R.drawable.ntp_signin_promo_card_bottom; return R.drawable.ntp_signin_promo_card_single; } @Override public void updateLayoutParams() { super.updateLayoutParams(); if (getAdapterPosition() == RecyclerView.NO_POSITION) return; @ItemViewType int precedingCardType = getRecyclerView().getAdapter().getItemViewType(getAdapterPosition() - 1); // The sign in promo should stick to the articles of the preceding section, but have // some space otherwise. if (precedingCardType != ItemViewType.SNIPPET) { getParams().topMargin = mSeparationSpaceSize; } else { getParams().topMargin = 0; } } } private void checkIndex(int position) { if (position < 0 || position >= getItemCount()) { throw new IndexOutOfBoundsException(position + "/" + getItemCount()); } } }
UTF-8
Java
5,731
java
SignInPromo.java
Java
[]
null
[]
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.ntp.cards; import android.content.Context; import android.support.annotation.DrawableRes; import android.support.annotation.StringRes; import android.support.v7.widget.RecyclerView; import org.chromium.base.ContextUtils; import org.chromium.base.metrics.RecordUserAction; import org.chromium.chrome.R; import org.chromium.chrome.browser.ntp.UiConfig; import org.chromium.chrome.browser.ntp.snippets.SnippetArticle; import org.chromium.chrome.browser.preferences.ChromePreferenceManager; import org.chromium.chrome.browser.signin.AccountSigninActivity; import org.chromium.chrome.browser.signin.SigninAccessPoint; import org.chromium.chrome.browser.signin.SigninManager; /** * Shows a card prompting the user to sign in. This item is also a {@link TreeNode}, and calling * {@link #hide()} or {@link #maybeShow()} will control its visibility. */ public class SignInPromo extends ChildNode implements StatusCardViewHolder.DataSource { /** * Whether the promo should be visible, according to the parent object. * * The {@link NewTabPageAdapter} calls to {@link #maybeShow()} and {@link #hide()} modify this * when the sign in status changes. */ private boolean mVisible; /** * Whether the user has seen the promo and dismissed it at some point. When this is set, * the promo will never be shown. */ private boolean mDismissed; public SignInPromo(NodeParent parent) { super(parent); mDismissed = ChromePreferenceManager.getInstance(ContextUtils.getApplicationContext()) .getNewTabPageSigninPromoDismissed(); SigninManager signinManager = SigninManager.get(ContextUtils.getApplicationContext()); mVisible = signinManager.isSignInAllowed() && !signinManager.isSignedInOnNative(); } @Override public int getItemCount() { if (!isShown()) return 0; return 1; } @Override @ItemViewType public int getItemViewType(int position) { checkIndex(position); return ItemViewType.PROMO; } @Override public void onBindViewHolder(NewTabPageViewHolder holder, int position) { checkIndex(position); assert holder instanceof StatusCardViewHolder; ((StatusCardViewHolder) holder).onBindViewHolder(this); } @Override public SnippetArticle getSuggestionAt(int position) { checkIndex(position); return null; } @Override @StringRes public int getHeader() { return R.string.snippets_disabled_generic_prompt; } @Override @StringRes public int getDescription() { return R.string.snippets_disabled_signed_out_instructions; } @Override @StringRes public int getActionLabel() { return R.string.sign_in_button; } @Override public void performAction(Context context) { AccountSigninActivity.startIfAllowed(context, SigninAccessPoint.NTP_CONTENT_SUGGESTIONS); } public boolean isShown() { return !mDismissed && mVisible; } /** Attempts to show the sign in promo. If the user dismissed it before, it will not be shown.*/ public void maybeShow() { if (mVisible) return; mVisible = true; if (mDismissed) return; RecordUserAction.record("Signin_Impression_FromNTPContentSuggestions"); notifyItemInserted(0); } /** Hides the sign in promo. */ public void hide() { if (!mVisible) return; mVisible = false; if (mDismissed) return; notifyItemRemoved(0); } /** Hides the sign in promo and sets a preference to make sure it is not shown again. */ public void dismiss() { hide(); mDismissed = true; ChromePreferenceManager.getInstance(ContextUtils.getApplicationContext()) .setNewTabPageSigninPromoDismissed(true); } /** * View Holder for {@link SignInPromo}. */ public static class ViewHolder extends StatusCardViewHolder { private final int mSeparationSpaceSize; public ViewHolder(NewTabPageRecyclerView parent, UiConfig config) { super(parent, config); mSeparationSpaceSize = parent.getResources().getDimensionPixelSize( R.dimen.ntp_sign_in_promo_margin_top); } @DrawableRes @Override protected int selectBackground(boolean hasCardAbove, boolean hasCardBelow) { assert !hasCardBelow; if (hasCardAbove) return R.drawable.ntp_signin_promo_card_bottom; return R.drawable.ntp_signin_promo_card_single; } @Override public void updateLayoutParams() { super.updateLayoutParams(); if (getAdapterPosition() == RecyclerView.NO_POSITION) return; @ItemViewType int precedingCardType = getRecyclerView().getAdapter().getItemViewType(getAdapterPosition() - 1); // The sign in promo should stick to the articles of the preceding section, but have // some space otherwise. if (precedingCardType != ItemViewType.SNIPPET) { getParams().topMargin = mSeparationSpaceSize; } else { getParams().topMargin = 0; } } } private void checkIndex(int position) { if (position < 0 || position >= getItemCount()) { throw new IndexOutOfBoundsException(position + "/" + getItemCount()); } } }
5,731
0.663933
0.661839
177
31.378531
28.913433
100
false
false
0
0
0
0
0
0
0.39548
false
false
11
c1218fef25b959efcb010c5094ab3adadf9d131e
29,334,626,687,468
b399f24bbf7f9308335fdb7f47fb2e0b8b1a6c0d
/MWST.java
38db25fc4410760617f8c27b54bda29316eb0420
[]
no_license
ahendy0/226-Kruskal-s-Algorithm
https://github.com/ahendy0/226-Kruskal-s-Algorithm
b6f3e9a23e8f55151eff4bfa35711712b39cd606
0e81054af00a0eee1d52d607e40dc4a6e8c53891
refs/heads/master
2020-12-29T03:31:50.575000
2016-04-12T03:51:43
2016-04-12T03:51:43
42,700,553
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* MWST.java CSC 226 - Fall 2015 Assignment 1 - Minimum Weight Spanning Tree Template This template includes some testing code to help verify the implementation. To interactively provide test inputs, run the program with java MWST To conveniently test the algorithm with a large input, create a text file containing one or more test graphs (in the format described below) and run the program with java MWST file.txt where file.txt is replaced by the name of the text file. The input consists of a series of graphs in the following format: <number of vertices> <adjacency matrix row 1> ... <adjacency matrix row n> Entry A[i][j] of the adjacency matrix gives the weight of the edge from vertex i to vertex j (if A[i][j] is 0, then the edge does not exist). Note that since the graph is undirected, it is assumed that A[i][j] is always equal to A[j][i]. An input file can contain an unlimited number of graphs; each will be processed separately. B. Bird - 08/02/2014 */ import java.util.Arrays; import java.util.Scanner; import java.util.Vector; import java.io.File; //Do not change the name of the MWST class public class MWST{ /* mwst(G) Given an adjacency matrix for graph G, return the total weight of all edges in a minimum weight spanning tree. If G[i][j] == 0, there is no edge between vertex i and vertex j If G[i][j] > 0, there is an edge between vertices i and j, and the value of G[i][j] gives the weight of the edge. No entries of G will be negative. */ static int MWST(int[][] G){ int numVerts = G.length; ListNode toSort = new ListNode(new Edge(0,0,0,new Vert[numVerts]) ); ListNode p = toSort;; int totalWeight = 0; Vert[] ref = new Vert[numVerts]; for(int i = 0;i<numVerts;i++){ ref[i] = new Vert(i); } int count2 = 0; //save pos for diagonal traversal for(int row = 0; row <numVerts;row++){ count2++; //each time we travel down a row, begin column by 1 for(int column=count2; column< numVerts;column++){ if(G[row][column]>0){ p.next = new ListNode(new Edge(row,column, G[row][column],ref)); //push to ListNode p = p.next; } } } toSort = removeFront(toSort); //removes extra object on listnode, was unpreventable ListNode sorted = MergeSort(toSort); //sort //printList(sorted); //sorted now contains a sorted ListNode of edge objects. ListNode sorted2 = sorted; while(sorted!= null){ //traverse through sorted nodes Edge a = sorted.value; int leastEdge = a.weight; sorted = sorted.next; totalWeight+= union(findSet(a.x),findSet(a.y),leastEdge); } return totalWeight; } public static Vert findSet(Vert a){ if(a.parent != a){ a.parent = findSet(a.parent); //sets parent to whatever highest parent on tree is } // uses tree compression for faster speed return a.parent; } public static int union(Vert a, Vert b, int leastEdge){ //System.out.println("(a.val,a.parent.val), ("+a.val+", "+ a.parent.val+ ")....(b.val,b.parent.val), ("+ b.val +","+b.parent.val+")\n"); if(a==b){ //case that a cycle will exist, unnessecary to have cycletest branch return 0; //totalweight += 0 } else if(a.rank>b.rank){ //use Union b.parent = a; } else if (a.rank<b.rank){ a.parent = b; }else if (a.rank == b.rank){ a.parent = b; b.rank ++; } return leastEdge; } public static ListNode removeFront(ListNode head){ ListNode f = head; head = head.next; f = null; return head; } public static int listLength(ListNode node){ if (node == null) return 0; return 1 + listLength(node.next); } public static ListNode addBack(ListNode head, ListNode value){ ListNode sorted; if(value == null){ return head; } if(head == null){ return value; } if ( head.value.weight< value.value.weight){ sorted = new ListNode( head.value, addBack(head.next,value)); } else{ sorted = new ListNode( value.value, addBack(head,value.next)); } return sorted; } public static ListNode findMid(ListNode head,ListNode end){ ListNode mid = head; if (end == null||end.next == null||end.next.next==null){ //end.next.next is required or else null pointers would happen on a few cases. return mid; // also size n = 4, middle pointer would be too far. } end = end.next; return findMid(head.next,end.next); // recursively increment back pointer by 2, front by one making front pointer be at middle. } public static ListNode MergeSort(ListNode head){ if(listLength(head)<=1 || head ==null ){ return head; } ListNode middle = findMid(head,head); ListNode tail = middle.next; //break from middle pointer.next to make tail middle.next = null; //middle pointer edits head linked list, breaking it into head nodes ListNode left = MergeSort(head); //recursively create lists of size one ListNode right = MergeSort(tail); //by continuously splitting in half by findMid return addBack(left,right); //originally was listMerge, edited my add to back function to create a sort and merge function } public static void printList(ListNode node){ if (node == null) System.out.println(); else{ System.out.print(node.value.weight + " "); printList(node.next); } } public static class ListNode{ Edge value; ListNode next; public ListNode(){ next = null; } public ListNode(Edge value){ this.value = value; this.next = null; } public ListNode(Edge value, ListNode next){ this.value = value; this.next = next; } } public static class Edge{ public Vert x; public Vert y; public int weight; //public boolean visited = false; public Edge(int a,int b,int weight, Vert[] ref){ this.weight = weight; this.x = ref[a]; this.y = ref[b]; } } public static class Vert{ public Vert parent; public int val; public int rank= 0; public Vert(int val){ this.val = val; this.parent = this; } public Vert(int val, Vert parent){ this.val = val; this.parent = parent; } } /* main() Contains code to test the MWST function. You may modify the testing code if needed, but nothing in this function will be considered during marking, and the testing process used for marking will not execute any of the code below. */ public static void main(String[] args){ Scanner s; if (args.length > 0){ try{ s = new Scanner(new File(args[0])); } catch(java.io.FileNotFoundException e){ System.out.printf("Unable to open %s\n",args[0]); return; } System.out.printf("Reading input values from %s.\n",args[0]); }else{ s = new Scanner(System.in); System.out.printf("Reading input values from stdin.\n"); } int graphNum = 0; double totalTimeSeconds = 0; //Read graphs until EOF is encountered (or an error occurs) while(true){ graphNum++; if(graphNum != 1 && !s.hasNextInt()) break; System.out.printf("Reading graph %d\n",graphNum); int n = s.nextInt(); int[][] G = new int[n][n]; int valuesRead = 0; for (int i = 0; i < n && s.hasNextInt(); i++){ for (int j = 0; j < n && s.hasNextInt(); j++){ G[i][j] = s.nextInt(); valuesRead++; } } if (valuesRead < n*n){ System.out.printf("Adjacency matrix for graph %d contains too few values.\n",graphNum); break; } long startTime = System.currentTimeMillis(); int totalWeight = MWST(G); long endTime = System.currentTimeMillis(); totalTimeSeconds += (endTime-startTime)/1000.0; System.out.printf("Graph %d: Total weight is %d\n",graphNum,totalWeight); } graphNum--; System.out.printf("Processed %d graph%s.\nAverage Time (seconds): %.2f\n",graphNum,(graphNum != 1)?"s":"",(graphNum>0)?totalTimeSeconds/graphNum:0); } }
UTF-8
Java
7,855
java
MWST.java
Java
[ { "context": "raphs; each will be \n processed separately.\n\n\n B. Bird - 08/02/2014\n*/\n\nimport java.util.Arrays;\nimport ", "end": 1030, "score": 0.9995629787445068, "start": 1023, "tag": "NAME", "value": "B. Bird" } ]
null
[]
/* MWST.java CSC 226 - Fall 2015 Assignment 1 - Minimum Weight Spanning Tree Template This template includes some testing code to help verify the implementation. To interactively provide test inputs, run the program with java MWST To conveniently test the algorithm with a large input, create a text file containing one or more test graphs (in the format described below) and run the program with java MWST file.txt where file.txt is replaced by the name of the text file. The input consists of a series of graphs in the following format: <number of vertices> <adjacency matrix row 1> ... <adjacency matrix row n> Entry A[i][j] of the adjacency matrix gives the weight of the edge from vertex i to vertex j (if A[i][j] is 0, then the edge does not exist). Note that since the graph is undirected, it is assumed that A[i][j] is always equal to A[j][i]. An input file can contain an unlimited number of graphs; each will be processed separately. <NAME> - 08/02/2014 */ import java.util.Arrays; import java.util.Scanner; import java.util.Vector; import java.io.File; //Do not change the name of the MWST class public class MWST{ /* mwst(G) Given an adjacency matrix for graph G, return the total weight of all edges in a minimum weight spanning tree. If G[i][j] == 0, there is no edge between vertex i and vertex j If G[i][j] > 0, there is an edge between vertices i and j, and the value of G[i][j] gives the weight of the edge. No entries of G will be negative. */ static int MWST(int[][] G){ int numVerts = G.length; ListNode toSort = new ListNode(new Edge(0,0,0,new Vert[numVerts]) ); ListNode p = toSort;; int totalWeight = 0; Vert[] ref = new Vert[numVerts]; for(int i = 0;i<numVerts;i++){ ref[i] = new Vert(i); } int count2 = 0; //save pos for diagonal traversal for(int row = 0; row <numVerts;row++){ count2++; //each time we travel down a row, begin column by 1 for(int column=count2; column< numVerts;column++){ if(G[row][column]>0){ p.next = new ListNode(new Edge(row,column, G[row][column],ref)); //push to ListNode p = p.next; } } } toSort = removeFront(toSort); //removes extra object on listnode, was unpreventable ListNode sorted = MergeSort(toSort); //sort //printList(sorted); //sorted now contains a sorted ListNode of edge objects. ListNode sorted2 = sorted; while(sorted!= null){ //traverse through sorted nodes Edge a = sorted.value; int leastEdge = a.weight; sorted = sorted.next; totalWeight+= union(findSet(a.x),findSet(a.y),leastEdge); } return totalWeight; } public static Vert findSet(Vert a){ if(a.parent != a){ a.parent = findSet(a.parent); //sets parent to whatever highest parent on tree is } // uses tree compression for faster speed return a.parent; } public static int union(Vert a, Vert b, int leastEdge){ //System.out.println("(a.val,a.parent.val), ("+a.val+", "+ a.parent.val+ ")....(b.val,b.parent.val), ("+ b.val +","+b.parent.val+")\n"); if(a==b){ //case that a cycle will exist, unnessecary to have cycletest branch return 0; //totalweight += 0 } else if(a.rank>b.rank){ //use Union b.parent = a; } else if (a.rank<b.rank){ a.parent = b; }else if (a.rank == b.rank){ a.parent = b; b.rank ++; } return leastEdge; } public static ListNode removeFront(ListNode head){ ListNode f = head; head = head.next; f = null; return head; } public static int listLength(ListNode node){ if (node == null) return 0; return 1 + listLength(node.next); } public static ListNode addBack(ListNode head, ListNode value){ ListNode sorted; if(value == null){ return head; } if(head == null){ return value; } if ( head.value.weight< value.value.weight){ sorted = new ListNode( head.value, addBack(head.next,value)); } else{ sorted = new ListNode( value.value, addBack(head,value.next)); } return sorted; } public static ListNode findMid(ListNode head,ListNode end){ ListNode mid = head; if (end == null||end.next == null||end.next.next==null){ //end.next.next is required or else null pointers would happen on a few cases. return mid; // also size n = 4, middle pointer would be too far. } end = end.next; return findMid(head.next,end.next); // recursively increment back pointer by 2, front by one making front pointer be at middle. } public static ListNode MergeSort(ListNode head){ if(listLength(head)<=1 || head ==null ){ return head; } ListNode middle = findMid(head,head); ListNode tail = middle.next; //break from middle pointer.next to make tail middle.next = null; //middle pointer edits head linked list, breaking it into head nodes ListNode left = MergeSort(head); //recursively create lists of size one ListNode right = MergeSort(tail); //by continuously splitting in half by findMid return addBack(left,right); //originally was listMerge, edited my add to back function to create a sort and merge function } public static void printList(ListNode node){ if (node == null) System.out.println(); else{ System.out.print(node.value.weight + " "); printList(node.next); } } public static class ListNode{ Edge value; ListNode next; public ListNode(){ next = null; } public ListNode(Edge value){ this.value = value; this.next = null; } public ListNode(Edge value, ListNode next){ this.value = value; this.next = next; } } public static class Edge{ public Vert x; public Vert y; public int weight; //public boolean visited = false; public Edge(int a,int b,int weight, Vert[] ref){ this.weight = weight; this.x = ref[a]; this.y = ref[b]; } } public static class Vert{ public Vert parent; public int val; public int rank= 0; public Vert(int val){ this.val = val; this.parent = this; } public Vert(int val, Vert parent){ this.val = val; this.parent = parent; } } /* main() Contains code to test the MWST function. You may modify the testing code if needed, but nothing in this function will be considered during marking, and the testing process used for marking will not execute any of the code below. */ public static void main(String[] args){ Scanner s; if (args.length > 0){ try{ s = new Scanner(new File(args[0])); } catch(java.io.FileNotFoundException e){ System.out.printf("Unable to open %s\n",args[0]); return; } System.out.printf("Reading input values from %s.\n",args[0]); }else{ s = new Scanner(System.in); System.out.printf("Reading input values from stdin.\n"); } int graphNum = 0; double totalTimeSeconds = 0; //Read graphs until EOF is encountered (or an error occurs) while(true){ graphNum++; if(graphNum != 1 && !s.hasNextInt()) break; System.out.printf("Reading graph %d\n",graphNum); int n = s.nextInt(); int[][] G = new int[n][n]; int valuesRead = 0; for (int i = 0; i < n && s.hasNextInt(); i++){ for (int j = 0; j < n && s.hasNextInt(); j++){ G[i][j] = s.nextInt(); valuesRead++; } } if (valuesRead < n*n){ System.out.printf("Adjacency matrix for graph %d contains too few values.\n",graphNum); break; } long startTime = System.currentTimeMillis(); int totalWeight = MWST(G); long endTime = System.currentTimeMillis(); totalTimeSeconds += (endTime-startTime)/1000.0; System.out.printf("Graph %d: Total weight is %d\n",graphNum,totalWeight); } graphNum--; System.out.printf("Processed %d graph%s.\nAverage Time (seconds): %.2f\n",graphNum,(graphNum != 1)?"s":"",(graphNum>0)?totalTimeSeconds/graphNum:0); } }
7,854
0.654488
0.646849
301
25.096346
27.729364
150
false
false
0
0
0
0
0
0
2.475083
false
false
11
0052b20991fccee9840763e3e667c7d48fb72686
3,238,405,398,159
a25e9afa164db40f7a8a8c78c5c887e8db3e067f
/src/main/java/service/TransactionService.java
72f5c1081f7bdc7a59e5f9d1b9c2fb24adeec3cd
[]
no_license
elenafol/movieApp
https://github.com/elenafol/movieApp
8d5fc10d9ee989ce931f0a1ab419f3222b86e8ab
761dd3ef85ab9ed29d369563f45f04510f3b59f6
refs/heads/master
2021-01-10T20:46:30.928000
2015-08-23T08:07:16
2015-08-23T08:07:16
40,356,738
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package service; import domain.Client; import domain.SeatReservation; import domain.SnackReservation; import domain.Transaction; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; //@Stateless public class TransactionService { @PersistenceContext(unitName = "movieServicePU") public EntityManager em; private long tnc=0; public long getTnc() { return tnc; } public void setTnc(int tnc) { this.tnc = tnc; } public Transaction addTransaction(Client client) { Transaction transaction = new Transaction(); long cId= client.getcId(); em.persist(transaction); return transaction; } public Transaction findTransactionBySnackReservation(SnackReservation snackReservation) { return em.createQuery( "select t from Transaction t where t.lastTnc = :lastTnc",Transaction.class) .setParameter("lastTnc",snackReservation.getLastTnc()) .getSingleResult(); } public Transaction findTransactionBySeatReservation(SeatReservation seatReservation) { return em.createQuery( "select t from Transaction t where t.lastTnc = :lastTnc",Transaction.class) .setParameter("lastTnc",seatReservation.getLastTnc()) .getSingleResult(); } public Transaction findTransactionByTnc(long tnc) { return em.find(Transaction.class, tnc); } public Long getGlobalLastTncNumber(){ return (Long)em.createQuery("select max(t.lastTnc) from Transaction t").getSingleResult(); } }
UTF-8
Java
1,664
java
TransactionService.java
Java
[]
null
[]
package service; import domain.Client; import domain.SeatReservation; import domain.SnackReservation; import domain.Transaction; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; //@Stateless public class TransactionService { @PersistenceContext(unitName = "movieServicePU") public EntityManager em; private long tnc=0; public long getTnc() { return tnc; } public void setTnc(int tnc) { this.tnc = tnc; } public Transaction addTransaction(Client client) { Transaction transaction = new Transaction(); long cId= client.getcId(); em.persist(transaction); return transaction; } public Transaction findTransactionBySnackReservation(SnackReservation snackReservation) { return em.createQuery( "select t from Transaction t where t.lastTnc = :lastTnc",Transaction.class) .setParameter("lastTnc",snackReservation.getLastTnc()) .getSingleResult(); } public Transaction findTransactionBySeatReservation(SeatReservation seatReservation) { return em.createQuery( "select t from Transaction t where t.lastTnc = :lastTnc",Transaction.class) .setParameter("lastTnc",seatReservation.getLastTnc()) .getSingleResult(); } public Transaction findTransactionByTnc(long tnc) { return em.find(Transaction.class, tnc); } public Long getGlobalLastTncNumber(){ return (Long)em.createQuery("select max(t.lastTnc) from Transaction t").getSingleResult(); } }
1,664
0.677885
0.677284
63
25.412699
27.361563
98
false
false
0
0
0
0
0
0
0.396825
false
false
11
e0e81351be3b57b0cb74a620065108c925769a15
24,970,939,926,075
22f6c9631a13fffba57b5325f60d80334dbde267
/controlAcceso/src/controlacceso/modelo/seguridadModelo.java
ef626929485bb2c4fc7f56104ff154c5441654e9
[]
no_license
bitsystemsgt/nova
https://github.com/bitsystemsgt/nova
d7cb9207e5eeeada8a13d587652cf69c508e402f
06c9d0a7c482071bcfc01aad8040ec35534f1a1d
refs/heads/master
2021-02-28T14:53:43.971000
2020-03-26T18:34:07
2020-03-26T18:34:07
245,683,410
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 controlacceso.modelo; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; import controlacceso.controlador.controlaIngreso; import java.sql.SQLException; import java.sql.ResultSet; /** * * @author Dell */ public class seguridadModelo { public static boolean consultaUsuario(String user, String pass)throws SQLException{ Connection conexion; conexion = conecta.conexion(); Statement s = (Statement) conexion.createStatement(); ResultSet resultadoBD = s.executeQuery("select * from tbl_usuarios where usuarios_nombre = '" + user + "'"); boolean concedeAcceso = controlaIngreso.comparaLogin(resultadoBD, user, pass); conexion.close(); System.out.println("conexion cerrada"); return concedeAcceso; } }
UTF-8
Java
1,090
java
seguridadModelo.java
Java
[ { "context": "\nimport java.sql.ResultSet;\r\n\r\n/**\r\n *\r\n * @author Dell\r\n */\r\npublic class seguridadModelo {\r\n public ", "end": 428, "score": 0.7628318071365356, "start": 424, "tag": "NAME", "value": "Dell" }, { "context": "rt java.sql.ResultSet;\r\n\r\n/**\r\n *\r\n * @author Dell\r\n */\r\npublic class seguridadModelo {\r\n public st", "end": 428, "score": 0.6640174984931946, "start": 428, "tag": "USERNAME", "value": "" } ]
null
[]
/* * 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 controlacceso.modelo; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; import controlacceso.controlador.controlaIngreso; import java.sql.SQLException; import java.sql.ResultSet; /** * * @author Dell */ public class seguridadModelo { public static boolean consultaUsuario(String user, String pass)throws SQLException{ Connection conexion; conexion = conecta.conexion(); Statement s = (Statement) conexion.createStatement(); ResultSet resultadoBD = s.executeQuery("select * from tbl_usuarios where usuarios_nombre = '" + user + "'"); boolean concedeAcceso = controlaIngreso.comparaLogin(resultadoBD, user, pass); conexion.close(); System.out.println("conexion cerrada"); return concedeAcceso; } }
1,090
0.648624
0.648624
36
28.277779
28.577002
116
false
false
0
0
0
0
0
0
0.555556
false
false
11
f87858d5d8ea0ae04dc39430bdc0a1ff4fbd44a3
7,413,113,566,906
57f001ced03e5e7f90548fb5a159a0f1b5177a1e
/exercise26/src/test/java/PaymentCalculatorTest.java
3c518fbc998c8d88edf06f7060bf52935b2ba60c
[]
no_license
DetrichLange/lange-a03
https://github.com/DetrichLange/lange-a03
b970fde5b9d330528f8c3c28cdea8499e9b84759
8465e100c168dc6f7038b01ad0b8acd907cde7e6
refs/heads/main
2023-08-04T19:54:19.633000
2021-10-03T20:31:28
2021-10-03T20:31:28
409,764,235
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import baseline.PaymentCalculator; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class PaymentCalculatorTest { @Test void paymentCalculatorTest(){ PaymentCalculator testCalculator = new PaymentCalculator(6000, 0.12, 100); int expected = 92; int actual = testCalculator.calculateMonthsUntilPaidOff(); assertEquals(expected, actual); } }
UTF-8
Java
473
java
PaymentCalculatorTest.java
Java
[]
null
[]
import baseline.PaymentCalculator; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class PaymentCalculatorTest { @Test void paymentCalculatorTest(){ PaymentCalculator testCalculator = new PaymentCalculator(6000, 0.12, 100); int expected = 92; int actual = testCalculator.calculateMonthsUntilPaidOff(); assertEquals(expected, actual); } }
473
0.727273
0.701903
18
25.333334
24.580933
82
false
false
0
0
0
0
0
0
0.611111
false
false
11
8e8cf0cf4791aeb5dd65b0f8656f6ecad9c8f0a0
19,954,418,106,383
3069045ffb0addcd26e3ba3ef3fb14e31d32c2ca
/java_practice/src/testcodes/practice_jvm_memory_leaks/StaticVarMemoryLeak.java
10f2ca97b408dbf91d2a7a1904f3bcced485f41a
[]
no_license
kr-zephyr/private_exmaple
https://github.com/kr-zephyr/private_exmaple
6168bf631ac83cb7381891cff62b125177e9858b
45454fa818d73f84f92e0589efe3bc2a788e96f5
refs/heads/master
2021-05-01T09:22:39.660000
2018-12-18T16:40:02
2018-12-18T16:40:02
22,383,777
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package testcodes.practice_jvm_memory_leaks; import org.junit.Test; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Random; /** * VisualVM을 이용하여 heap 메모리 사용 및 변화를 검토해보자. */ public class StaticVarMemoryLeak { private Random random = new Random(); public static ArrayList<Double> list = new ArrayList<>(1000000); /** * static 변수인 list를 사용했으므로, for문이 동작할 때 heap에 메모리가 잡히고 해제되지 않을 것임. * @throws InterruptedException */ @Test public void givenStaticField_whenLotsOfOperations_thenMemoryLeak() throws InterruptedException { Thread.sleep(10000); System.out.println("[" + LocalDateTime.now() + "] start"); for(int i = 0; i < 1000000; i++) { list.add(random.nextDouble()); } System.out.println("[" + LocalDateTime.now() + "] end data"); System.gc(); System.out.println("[" + LocalDateTime.now() + "] end"); Thread.sleep(100000); } /** * 로컬변수 localList를 사용했으므로, for문이 완료된 후 localList의 메모리 사용량은 반환될 것임. * @throws InterruptedException */ @Test public void givenNormalField_whenLotsOfOperations_thenGCWorksFine() throws InterruptedException { Thread.sleep(10000); System.out.println("[" + LocalDateTime.now() + "] start"); addElementsToTheList(); System.out.println("[" + LocalDateTime.now() + "] end data"); System.gc(); System.out.println("[" + LocalDateTime.now() + "] end"); Thread.sleep(100000); } private void addElementsToTheList() { ArrayList<Double> localList = new ArrayList<>(1000000); for(int i = 0; i < 1000000; i++) { localList.add(random.nextDouble()); } } }
UTF-8
Java
1,741
java
StaticVarMemoryLeak.java
Java
[]
null
[]
package testcodes.practice_jvm_memory_leaks; import org.junit.Test; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Random; /** * VisualVM을 이용하여 heap 메모리 사용 및 변화를 검토해보자. */ public class StaticVarMemoryLeak { private Random random = new Random(); public static ArrayList<Double> list = new ArrayList<>(1000000); /** * static 변수인 list를 사용했으므로, for문이 동작할 때 heap에 메모리가 잡히고 해제되지 않을 것임. * @throws InterruptedException */ @Test public void givenStaticField_whenLotsOfOperations_thenMemoryLeak() throws InterruptedException { Thread.sleep(10000); System.out.println("[" + LocalDateTime.now() + "] start"); for(int i = 0; i < 1000000; i++) { list.add(random.nextDouble()); } System.out.println("[" + LocalDateTime.now() + "] end data"); System.gc(); System.out.println("[" + LocalDateTime.now() + "] end"); Thread.sleep(100000); } /** * 로컬변수 localList를 사용했으므로, for문이 완료된 후 localList의 메모리 사용량은 반환될 것임. * @throws InterruptedException */ @Test public void givenNormalField_whenLotsOfOperations_thenGCWorksFine() throws InterruptedException { Thread.sleep(10000); System.out.println("[" + LocalDateTime.now() + "] start"); addElementsToTheList(); System.out.println("[" + LocalDateTime.now() + "] end data"); System.gc(); System.out.println("[" + LocalDateTime.now() + "] end"); Thread.sleep(100000); } private void addElementsToTheList() { ArrayList<Double> localList = new ArrayList<>(1000000); for(int i = 0; i < 1000000; i++) { localList.add(random.nextDouble()); } } }
1,741
0.68461
0.651678
58
26.224138
25.716654
98
false
false
0
0
0
0
0
0
1.724138
false
false
11
90842fb1bbc4d26b5cca472c7ce6b67df4f8cb3b
7,344,394,115,297
9a275d7c692145c28c63fa740d0f73050388b1cf
/src/sort/Utils.java
5d68539cb20b67023a60e43cbe9b5fadc2a8cb87
[]
no_license
Cheryl-Hs/testarray
https://github.com/Cheryl-Hs/testarray
9f1e3cd60032ca36fcf1555a2bf6569ded899adc
047606bdec0a115cde9b5333c24980c5b137bbd0
refs/heads/master
2021-01-17T19:59:39.425000
2016-07-25T12:06:02
2016-07-25T12:06:02
64,001,156
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sort; import java.util.Comparator; import java.util.List; /** * 排序(降序) * @author Administrator * */ public class Utils { /** * 容器排序(使用泛型方法)+ Comparator * @param arr */ public static <T> void sort(List<T> list,Comparator<T> com) { //第一步:转成数组 Object[] arr = list.toArray(); sort(arr, com); //第二步:改变容器中对应的值 for(int i = 0; i<arr.length; i++) { list.set(i, (T)arr[i]); } } /** * 数组的排序(降序) + Comparator接口 * @param arr */ public static <T> void sort(Object[] arr, Comparator<T> com) { int len = arr.length; boolean sorted = true; for(int i = 0; i<len-1; i++) { //趟数 sorted = true; //假定有序 for(int j = 0; j<len-1-i/*减少趟数*/; j++) { //次数 if(com.compare((T)arr[j], (T)arr[j+1]) < 0) { Object temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; sorted = false; //假定失败 } } if(sorted) { break; } } } /** * 容器排序(使用泛型方法) * @param arr */ public static <T extends Comparable<T>> void sort(List<T> list) { //第一步:转成数组 Object[] arr = list.toArray(); sort(arr); //第二步:改变容器中对应的值 for(int i = 0; i<arr.length; i++) { list.set(i, (T)arr[i]); } } /** * 数组排序(使用泛型方法) * @param arr */ public static <T extends Comparable<T>> void sort(T[] arr) { int len = arr.length; boolean sorted = true; for(int i = 0; i<len-1; i++) { //趟数 sorted = true; //假定有序 for(int j = 0; j<len-1-i/*减少趟数*/; j++) { //次数 if(((Comparable)arr[j]).compareTo(arr[j+1])>0) { T temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; sorted = false; //假定失败 } } if(sorted) { break; } } } /** * 数组的排序 * @param arr */ public static void sort(Object[] arr) { int len = arr.length; boolean sorted = true; for(int i = 0; i<len-1; i++) { //趟数 sorted = true; //假定有序 for(int j = 0; j<len-1-i/*减少趟数*/; j++) { //次数 if(((Comparable)arr[j]).compareTo(arr[j+1])>0) { Object temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; sorted = false; //假定失败 } } if(sorted) { break; } } } }
UTF-8
Java
2,513
java
Utils.java
Java
[ { "context": "port java.util.List;\r\n\r\n/**\r\n * 排序(降序)\r\n * @author Administrator\r\n *\r\n */\r\npublic class Utils {\r\n\t\r\n\t\r\n\t/**\r\n\t * 容", "end": 113, "score": 0.8921524882316589, "start": 100, "tag": "NAME", "value": "Administrator" } ]
null
[]
package sort; import java.util.Comparator; import java.util.List; /** * 排序(降序) * @author Administrator * */ public class Utils { /** * 容器排序(使用泛型方法)+ Comparator * @param arr */ public static <T> void sort(List<T> list,Comparator<T> com) { //第一步:转成数组 Object[] arr = list.toArray(); sort(arr, com); //第二步:改变容器中对应的值 for(int i = 0; i<arr.length; i++) { list.set(i, (T)arr[i]); } } /** * 数组的排序(降序) + Comparator接口 * @param arr */ public static <T> void sort(Object[] arr, Comparator<T> com) { int len = arr.length; boolean sorted = true; for(int i = 0; i<len-1; i++) { //趟数 sorted = true; //假定有序 for(int j = 0; j<len-1-i/*减少趟数*/; j++) { //次数 if(com.compare((T)arr[j], (T)arr[j+1]) < 0) { Object temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; sorted = false; //假定失败 } } if(sorted) { break; } } } /** * 容器排序(使用泛型方法) * @param arr */ public static <T extends Comparable<T>> void sort(List<T> list) { //第一步:转成数组 Object[] arr = list.toArray(); sort(arr); //第二步:改变容器中对应的值 for(int i = 0; i<arr.length; i++) { list.set(i, (T)arr[i]); } } /** * 数组排序(使用泛型方法) * @param arr */ public static <T extends Comparable<T>> void sort(T[] arr) { int len = arr.length; boolean sorted = true; for(int i = 0; i<len-1; i++) { //趟数 sorted = true; //假定有序 for(int j = 0; j<len-1-i/*减少趟数*/; j++) { //次数 if(((Comparable)arr[j]).compareTo(arr[j+1])>0) { T temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; sorted = false; //假定失败 } } if(sorted) { break; } } } /** * 数组的排序 * @param arr */ public static void sort(Object[] arr) { int len = arr.length; boolean sorted = true; for(int i = 0; i<len-1; i++) { //趟数 sorted = true; //假定有序 for(int j = 0; j<len-1-i/*减少趟数*/; j++) { //次数 if(((Comparable)arr[j]).compareTo(arr[j+1])>0) { Object temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; sorted = false; //假定失败 } } if(sorted) { break; } } } }
2,513
0.483987
0.47226
116
17.112068
15.981547
66
false
false
0
0
0
0
0
0
2.663793
false
false
11
97e3a307b2622577e929d633d0b07da51528bd67
27,367,531,650,214
ccf274a082eb1d95d822537b36498bc4014443f0
/app/src/androidTest/java/test/dao/SaunasDaoTest.java
e9c7c4b32debade4fe33ddb4d0b871104eef7234
[]
no_license
Bladecaller/ReExam_SEP4_Android
https://github.com/Bladecaller/ReExam_SEP4_Android
2fef020baff851378caefc4f7efb3c777d8c2baf
05f111069f2bfabe86ce81922fd986336b3142c4
refs/heads/master
2023-07-12T03:57:32.813000
2021-08-12T12:54:04
2021-08-12T12:54:04
381,963,354
0
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package test.dao; import android.content.Context; import androidx.arch.core.executor.testing.InstantTaskExecutorRule; import androidx.lifecycle.Observer; import androidx.room.Room; import androidx.test.platform.app.InstrumentationRegistry; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import java.util.List; import model.room.dao.DataPointDao; import model.room.dao.SaunasDao; import model.room.entity.Sauna.DataPoint; import model.room.entity.Sauna.Sauna; import model.room.roomdatabase.MyRoomDatabase; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.doReturn; public class SaunasDaoTest { @Rule public TestRule rule = new InstantTaskExecutorRule(); MyRoomDatabase db; SaunasDao dao; Observer<List<Sauna>> observer; List<Sauna> list; @Before public void setUp() throws Exception { observer = new Observer<List<Sauna>>() { @Override public void onChanged(List<Sauna> saunas) { list = saunas; } }; Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); db = Room.inMemoryDatabaseBuilder( context, MyRoomDatabase.class ).allowMainThreadQueries().build(); dao = db.saunaDao(); } @After public void tearDown() throws Exception { db.close(); } @Test public void insertGetRemoveGet(){ Sauna sauna = new Sauna(1,12,12,4,2,null); dao.getAllSaunas().observeForever(observer); dao.insert(sauna); Assert.assertEquals(1,list.get(0).getSaunaID()); dao.deleteAll(); Assert.assertEquals(true,list.isEmpty()); } }
UTF-8
Java
1,862
java
SaunasDaoTest.java
Java
[]
null
[]
package test.dao; import android.content.Context; import androidx.arch.core.executor.testing.InstantTaskExecutorRule; import androidx.lifecycle.Observer; import androidx.room.Room; import androidx.test.platform.app.InstrumentationRegistry; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import java.util.List; import model.room.dao.DataPointDao; import model.room.dao.SaunasDao; import model.room.entity.Sauna.DataPoint; import model.room.entity.Sauna.Sauna; import model.room.roomdatabase.MyRoomDatabase; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.doReturn; public class SaunasDaoTest { @Rule public TestRule rule = new InstantTaskExecutorRule(); MyRoomDatabase db; SaunasDao dao; Observer<List<Sauna>> observer; List<Sauna> list; @Before public void setUp() throws Exception { observer = new Observer<List<Sauna>>() { @Override public void onChanged(List<Sauna> saunas) { list = saunas; } }; Context context = InstrumentationRegistry.getInstrumentation().getTargetContext(); db = Room.inMemoryDatabaseBuilder( context, MyRoomDatabase.class ).allowMainThreadQueries().build(); dao = db.saunaDao(); } @After public void tearDown() throws Exception { db.close(); } @Test public void insertGetRemoveGet(){ Sauna sauna = new Sauna(1,12,12,4,2,null); dao.getAllSaunas().observeForever(observer); dao.insert(sauna); Assert.assertEquals(1,list.get(0).getSaunaID()); dao.deleteAll(); Assert.assertEquals(true,list.isEmpty()); } }
1,862
0.684211
0.679377
70
25.614286
19.81579
90
false
false
0
0
0
0
0
0
0.657143
false
false
11
e7f69dc8602cc52197b0cfd0f88a586a2d186fbb
31,920,196,954,077
c7b040d06daf40578fd2827e95e23d799c93e3e3
/RCSBlackBerry/src/blackberry/evidence/Evidence.java
4249bccbc6f8599c124f4491b34504f606070336
[]
no_license
Vigilox/core-blackberry
https://github.com/Vigilox/core-blackberry
d24b17408aabb04bb0bfafc23dd9e839bd0e5f31
977aca189004365f0002766fd318bfc6bc2b4d17
refs/heads/master
2021-05-31T15:00:07.751000
2014-11-03T09:38:29
2014-11-03T09:38:29
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//#preprocess /* ************************************************* * Copyright (c) 2010 - 2010 * HT srl, All rights reserved. * Project : RCS, RCSBlackBerry_lib * File : Log.java * Created : 26-mar-2010 * *************************************************/ package blackberry.evidence; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Vector; import javax.microedition.io.Connector; import javax.microedition.io.file.FileConnection; import net.rim.device.api.util.DataBuffer; import blackberry.Device; import blackberry.Status; import blackberry.config.Globals; import blackberry.config.Keys; import blackberry.crypto.Encryption; import blackberry.debug.Check; import blackberry.debug.Debug; import blackberry.debug.DebugLevel; import blackberry.fs.Path; import blackberry.utils.DateTime; import blackberry.utils.Utils; import blackberry.utils.WChar; /* LOG FORMAT * */ /** * The Class Evidence (formerly known as Log.) */ public final class Evidence { private static final int E_VERSION_01 = 2008121901; /* * Tipi di log (quelli SOLO per mobile DEVONO partire da 0xAA00 */ public static int E_DELIMITER = 0xABADC0DE; private static final long MIN_AVAILABLE_SIZE = 10 * 1024; //#ifdef DEBUG private static Debug debug = new Debug("Evidence", DebugLevel.VERBOSE); //#endif //boolean firstSpace = true; boolean enoughSpace = true; Date timestamp; String logName; String fileName; FileConnection fconn = null; DataOutputStream os = null; Encryption encryption; EvidenceCollector evidenceCollector; EvidenceDescription evidenceDescription; Device device; int evidenceId; int progressive; private byte[] aesKey; private byte[] encData; private int typeEvidenceId; /** * Instantiates a new evidence. */ private Evidence() { evidenceCollector = EvidenceCollector.getInstance(); device = Device.getInstance(); progressive = -1; // timestamp = new Date(); } /** * Instantiates a new log. * * @param typeEvidenceId * the type evidence id * @param aesKey * the aes key */ private Evidence(final int typeEvidenceId, final byte[] aesKey) { this(); //#ifdef DBC Check.requires(aesKey != null, "aesKey null"); //$NON-NLS-1$ //#endif // agent = agent_; this.typeEvidenceId = typeEvidenceId; this.aesKey = aesKey; encryption = new Encryption(aesKey); //#ifdef DBC Check.ensures(encryption != null, "encryption null"); //$NON-NLS-1$ //#endif } /** * Instantiates a new evidence. * * @param typeEvidenceId * the type evidence id */ public Evidence(final int typeEvidenceId) { this(typeEvidenceId, Keys.getInstance().getLogKey()); } public static String memoTypeEvidence(final int typeId) { switch (typeId) { case 0xFFFF: return "NON"; case 0x0000: return "FON"; case 0x0001: return "FCA"; case 0x0040: return "KEY"; case 0x0100: return "PRN"; case 0xB9B9: return "SNP"; case 0xD1D1: return "UPL"; case 0xD0D0: return "DOW"; case 0x0140: return "CAL"; case 0x0141: return "SKY"; case 0x0142: return "GTA"; case 0x0143: return "YMS"; case 0x0144: return "MSN"; case 0x0145: return "MOB"; case 0x0180: return "URL"; case 0xD9D9: return "CLP"; case 0xFAFA: return "PWD"; case 0xC2C2: return "MIC"; case 0xC6C6: return "CHA"; case 0xE9E9: return "CAM"; case 0x0200: return "ADD"; case 0x0201: return "CAL"; case 0x0202: return "TSK"; case 0x0210: return "MAI"; case 0x0211: return "SMS"; case 0x0212: return "MMS"; case 0x0220: return "LOC"; case 0x0230: return "CAL"; case 0x0240: return "DEV"; case 0x0241: return "INF"; case 0x1011: return "APP"; case 0x0300: return "SKI"; case 0x1001: return "MAI"; case 0x0213: return "SMS"; case 0x1220: return "LOC"; case 0xEDA1: return "FSS"; } return "UNK"; } /** * Chiude il file di log. Torna TRUE se il file e' stato chiuso con * successo, FALSE altrimenti. Se bRemove e' impostato a TRUE il file viene * anche cancellato da disco e rimosso dalla coda. Questa funzione NON va * chiamata per i markup perche' la WriteMarkup() e la ReadMarkup() chiudono * automaticamente l'handle. * * @return true, if successful */ public synchronized boolean close() { boolean ret = true; encData = null; if (os != null) { try { os.close(); } catch (final IOException e) { ret = false; } } if (fconn != null) { try { fconn.close(); } catch (final IOException e) { ret = false; } } os = null; fconn = null; return ret; } public synchronized boolean createEvidence() { return createEvidence(null, false); } public boolean createEvidence(final byte[] additionalData) { return createEvidence(additionalData, false); } /** * Questa funzione crea un file di log e lascia l'handle aperto. Il file * viene creato con un nome casuale, la chiamata scrive l'header nel file e * poi i dati addizionali se ce ne sono. LogType e' il tipo di log che * stiamo scrivendo, pAdditionalData e' un puntatore agli eventuali * additional data e uAdditionalLen e la lunghezza dei dati addizionali da * scrivere nell'header. Il parametro facoltativo bStoreToMMC se settato a * TRUE fa in modo che il log venga salvato nella prima MMC disponibile, se * non c'e' la chiama fallisce. La funzione torna TRUE se va a buon fine, * FALSE altrimenti. * * @param additionalData * the additional data * @param force * @return true, if successful */ public synchronized boolean createEvidence(final byte[] additionalData, boolean forced) { //#ifdef DEBUG debug.trace("createLog evidenceType: " + typeEvidenceId); //#endif //#ifdef DBC Check.requires(os == null && fconn == null, "createLog: not previously closed"); //#endif timestamp = new Date(); int additionalLen = 0; if (additionalData != null) { additionalLen = additionalData.length; } if (!forced) { enoughSpace = enoughSpace(); if (!enoughSpace) { //#ifdef DEBUG debug.trace("createEvidence, no space"); //#endif return false; } } final Vector tuple = evidenceCollector.makeNewName(this, memoTypeEvidence(typeEvidenceId), false); //#ifdef DBC Check.asserts(tuple.size() == 5, "Wrong tuple size"); //#endif progressive = ((Integer) tuple.elementAt(0)).intValue(); final String basePath = (String) tuple.elementAt(1); final String blockDir = (String) tuple.elementAt(2); final String encName = (String) tuple.elementAt(3); final String plainFileName = (String) tuple.elementAt(4); final String dir = basePath + blockDir + "/"; final boolean ret = Path.createDirectory(dir, true); if (!ret) { //#ifdef DEBUG debug.error("Dir not created: " + dir); //#endif return false; } fileName = dir + encName; //#ifdef DBC Check.asserts(fileName != null, "null fileName"); Check.asserts(!fileName.endsWith(EvidenceCollector.LOG_EXTENSION .toUpperCase()), "file not scrambled"); //#endif //#ifdef DEBUG debug.trace("createLog fileName:" + fileName); //#endif try { fconn = (FileConnection) Connector.open("file://" + fileName); if (fconn.exists()) { close(); //#ifdef DEBUG debug.fatal("It should not exist:" + fileName); //#endif return false; } //#ifdef DEBUG debug.info("Created: " + plainFileName); //#endif final byte[] plainBuffer = makeDescription(additionalData, typeEvidenceId); //#ifdef DBC Check.asserts(plainBuffer.length >= 32 + additionalLen, "Short plainBuffer"); //#endif fconn.create(); os = fconn.openDataOutputStream(); final byte[] encBuffer = encryption.encryptData(plainBuffer); //#ifdef DBC Check.asserts(encBuffer.length == Encryption .getNextMultiple(plainBuffer.length), "Wrong encBuffer"); //#endif // scriviamo la dimensione dell'header paddato os.write(Utils.intToByteArray(plainBuffer.length)); // scrittura dell'header cifrato os.write(encBuffer); os.flush(); //#ifdef DBC Check.asserts(fconn.fileSize() == encBuffer.length + 4, "Wrong filesize"); //#endif //#ifdef DEBUG debug.trace("additionalData.length: " + plainBuffer.length); debug.trace("encBuffer.length: " + encBuffer.length); //#endif } catch (final IOException ex) { //#ifdef DEBUG debug.error("file: " + plainFileName + " ex:" + ex); //#endif return false; } //#ifdef DBC Check.ensures(os != null, "null os"); //#endif return true; } private boolean enoughSpace() { long free = 0; free = Path.freeSpace(Path.USER); Globals globals = Status.self().getGlobals(); long minQuota = MIN_AVAILABLE_SIZE; if (globals != null) { minQuota = globals.getQuotaMin(); } if (minQuota >= 0 && free < minQuota) { //#ifdef DEBUG debug.trace("not enoughSpace: " + free + " < " + minQuota); //#endif Status.self().setOverQuota(free, true); return false; } else { //#ifdef DEBUG debug.trace("enoughSpace: " + free + " > " + minQuota); //#endif Status.self().setOverQuota(free, false); return true; } } public synchronized byte[] plainEvidence(final byte[] additionalData, final int logType, final byte[] data) { //final byte[] encData = encryption.encryptData(data, 0); int additionalLen = 0; if (additionalData != null) { additionalLen = additionalData.length; } final byte[] plainBuffer = makeDescription(additionalData, logType); //#ifdef DBC Check.asserts(plainBuffer.length >= 32 + additionalLen, "Short plainBuffer"); //#endif // buffer completo byte[] buffer = new byte[additionalData.length + data.length + 8]; DataBuffer databuffer = new DataBuffer(buffer, 0, buffer.length, false); // scriviamo la dimensione dell'header paddato databuffer.writeInt(plainBuffer.length); // scrittura dell'header cifrato databuffer.write(additionalData); // scrivo il contenuto databuffer.writeInt(data.length); databuffer.write(data); return buffer; } public boolean appendEvidence(final byte[] data) { return writeEvidence(data, 0); } public boolean writeEvidence(final byte[] data) { return writeEvidence(data, 0); } /** * Questa funzione prende i byte puntati da pByte, li cifra e li scrive nel * file di log creato con CreateLog(). La funzione torna TRUE se va a buon * fine, FALSE altrimenti. * * @param data * the data * @return true, if successful */ public synchronized boolean writeEvidence(final byte[] data, int offset) { if (os == null) { //#ifdef DEBUG debug.error("os null"); //#endif return false; } if (fconn == null) { //#ifdef DEBUG debug.error("fconn null"); //#endif return false; } if (Status.self().wantLight()) { // green Debug.ledFlash(Debug.COLOR_GREEN_LIGHT); } encData = encryption.encryptData(data, offset); //#ifdef DEBUG debug.trace("writeEvidence encdata: " + encData.length); //#endif try { os.write(Utils.intToByteArray(data.length - offset)); os.write(encData); os.flush(); } catch (final IOException e) { //#ifdef DEBUG debug.error("Error writing file: " + e); //#endif close(); try { fconn.delete(); } catch (IOException ex) { //#ifdef DEBUG debug.error("writeEvidence, deleting due to error: " + ex); //#endif } fconn = null; return false; } return true; } public synchronized boolean writeEvidence(DataInputStream inputStream, int size) { if (os == null) { //#ifdef DEBUG debug.error("os null"); //#endif return false; } try { os.write(Utils.intToByteArray(size)); encryption.encryptData(inputStream, os); } catch (IOException e) { //#ifdef DEBUG debug.error(e); debug.error("writeEvidence"); //#endif return false; }finally{ if (os != null) { try { os.close(); } catch (final IOException e) { return false; } } } return true; } /** * Write logs. * * @param bytelist * the bytelist * @return true, if successful */ public boolean writeEvidences(final Vector bytelist) { int totalLen = 0; for (int i = 0; i < bytelist.size(); i++) { final byte[] token = (byte[]) bytelist.elementAt(i); totalLen += token.length; } final int offset = 0; final byte[] buffer = new byte[totalLen]; final DataBuffer databuffer = new DataBuffer(buffer, 0, totalLen, false); for (int i = 0; i < bytelist.size(); i++) { final byte[] token = (byte[]) bytelist.elementAt(i); databuffer.write(token); } //#ifdef DEBUG debug.trace("len: " + buffer.length); //#endif return writeEvidence(buffer); } public byte[] getEncData() { return encData; } public DataOutputStream getOutputStream() { return os; } // pubblico solo per fare i test /** * Make description. * * @param additionalData * the additional data * @return the byte[] */ public byte[] makeDescription(final byte[] additionalData, final int logType) { if (timestamp == null) { timestamp = new Date(); } int additionalLen = 0; if (additionalData != null) { additionalLen = additionalData.length; } final DateTime datetime = new DateTime(timestamp); evidenceDescription = new EvidenceDescription(); evidenceDescription.version = E_VERSION_01; evidenceDescription.logType = logType; evidenceDescription.hTimeStamp = datetime.hiDateTime(); evidenceDescription.lTimeStamp = datetime.lowDateTime(); evidenceDescription.additionalData = additionalLen; evidenceDescription.deviceIdLen = device.getWDeviceId().length; evidenceDescription.userIdLen = device.getWUserId().length; evidenceDescription.sourceIdLen = device.getWPhoneNumber().length; final byte[] baseHeader = evidenceDescription.getBytes(); //#ifdef DBC Check.asserts(baseHeader.length == evidenceDescription.length, "Wrong log len"); //#endif final int headerLen = baseHeader.length + evidenceDescription.additionalData + evidenceDescription.deviceIdLen + evidenceDescription.userIdLen + evidenceDescription.sourceIdLen; final byte[] plainBuffer = new byte[Encryption .getNextMultiple(headerLen)]; final DataBuffer databuffer = new DataBuffer(plainBuffer, 0, plainBuffer.length, false); databuffer.write(baseHeader); databuffer.write(device.getWDeviceId()); databuffer.write(device.getWUserId()); databuffer.write(device.getWPhoneNumber()); if (additionalLen > 0) { databuffer.write(additionalData); } return plainBuffer; } public static void info(final String message) { info(message, false); } public static void info(final String message, boolean force) { try { final Evidence logInfo = new Evidence(EvidenceType.INFO); logInfo.createEvidence(null, force); logInfo.writeEvidence(WChar.getBytes(message, true)); logInfo.close(); } catch (final Exception ex) { //#ifdef DEBUG debug.error(ex); //#endif } } public synchronized void atomicWriteOnce(byte[] additionalData, byte[] content) { createEvidence(additionalData, false); if (!writeEvidence(content)) { } close(); } public synchronized void atomicWriteOnce(Vector bytelist) { createEvidence(null, false); writeEvidences(bytelist); close(); } public synchronized void atomicWriteOnce(byte[] plain) { createEvidence(null, false); writeEvidence(plain); close(); } public synchronized void atomicWriteOnce(String message) { createEvidence(null, false); writeEvidence(WChar.getBytes(message, true)); close(); } private void atomicWriteOnce(String message, boolean force) { createEvidence(null, force); writeEvidence(WChar.getBytes(message, true)); close(); } }
UTF-8
Java
19,800
java
Evidence.java
Java
[]
null
[]
//#preprocess /* ************************************************* * Copyright (c) 2010 - 2010 * HT srl, All rights reserved. * Project : RCS, RCSBlackBerry_lib * File : Log.java * Created : 26-mar-2010 * *************************************************/ package blackberry.evidence; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.Vector; import javax.microedition.io.Connector; import javax.microedition.io.file.FileConnection; import net.rim.device.api.util.DataBuffer; import blackberry.Device; import blackberry.Status; import blackberry.config.Globals; import blackberry.config.Keys; import blackberry.crypto.Encryption; import blackberry.debug.Check; import blackberry.debug.Debug; import blackberry.debug.DebugLevel; import blackberry.fs.Path; import blackberry.utils.DateTime; import blackberry.utils.Utils; import blackberry.utils.WChar; /* LOG FORMAT * */ /** * The Class Evidence (formerly known as Log.) */ public final class Evidence { private static final int E_VERSION_01 = 2008121901; /* * Tipi di log (quelli SOLO per mobile DEVONO partire da 0xAA00 */ public static int E_DELIMITER = 0xABADC0DE; private static final long MIN_AVAILABLE_SIZE = 10 * 1024; //#ifdef DEBUG private static Debug debug = new Debug("Evidence", DebugLevel.VERBOSE); //#endif //boolean firstSpace = true; boolean enoughSpace = true; Date timestamp; String logName; String fileName; FileConnection fconn = null; DataOutputStream os = null; Encryption encryption; EvidenceCollector evidenceCollector; EvidenceDescription evidenceDescription; Device device; int evidenceId; int progressive; private byte[] aesKey; private byte[] encData; private int typeEvidenceId; /** * Instantiates a new evidence. */ private Evidence() { evidenceCollector = EvidenceCollector.getInstance(); device = Device.getInstance(); progressive = -1; // timestamp = new Date(); } /** * Instantiates a new log. * * @param typeEvidenceId * the type evidence id * @param aesKey * the aes key */ private Evidence(final int typeEvidenceId, final byte[] aesKey) { this(); //#ifdef DBC Check.requires(aesKey != null, "aesKey null"); //$NON-NLS-1$ //#endif // agent = agent_; this.typeEvidenceId = typeEvidenceId; this.aesKey = aesKey; encryption = new Encryption(aesKey); //#ifdef DBC Check.ensures(encryption != null, "encryption null"); //$NON-NLS-1$ //#endif } /** * Instantiates a new evidence. * * @param typeEvidenceId * the type evidence id */ public Evidence(final int typeEvidenceId) { this(typeEvidenceId, Keys.getInstance().getLogKey()); } public static String memoTypeEvidence(final int typeId) { switch (typeId) { case 0xFFFF: return "NON"; case 0x0000: return "FON"; case 0x0001: return "FCA"; case 0x0040: return "KEY"; case 0x0100: return "PRN"; case 0xB9B9: return "SNP"; case 0xD1D1: return "UPL"; case 0xD0D0: return "DOW"; case 0x0140: return "CAL"; case 0x0141: return "SKY"; case 0x0142: return "GTA"; case 0x0143: return "YMS"; case 0x0144: return "MSN"; case 0x0145: return "MOB"; case 0x0180: return "URL"; case 0xD9D9: return "CLP"; case 0xFAFA: return "PWD"; case 0xC2C2: return "MIC"; case 0xC6C6: return "CHA"; case 0xE9E9: return "CAM"; case 0x0200: return "ADD"; case 0x0201: return "CAL"; case 0x0202: return "TSK"; case 0x0210: return "MAI"; case 0x0211: return "SMS"; case 0x0212: return "MMS"; case 0x0220: return "LOC"; case 0x0230: return "CAL"; case 0x0240: return "DEV"; case 0x0241: return "INF"; case 0x1011: return "APP"; case 0x0300: return "SKI"; case 0x1001: return "MAI"; case 0x0213: return "SMS"; case 0x1220: return "LOC"; case 0xEDA1: return "FSS"; } return "UNK"; } /** * Chiude il file di log. Torna TRUE se il file e' stato chiuso con * successo, FALSE altrimenti. Se bRemove e' impostato a TRUE il file viene * anche cancellato da disco e rimosso dalla coda. Questa funzione NON va * chiamata per i markup perche' la WriteMarkup() e la ReadMarkup() chiudono * automaticamente l'handle. * * @return true, if successful */ public synchronized boolean close() { boolean ret = true; encData = null; if (os != null) { try { os.close(); } catch (final IOException e) { ret = false; } } if (fconn != null) { try { fconn.close(); } catch (final IOException e) { ret = false; } } os = null; fconn = null; return ret; } public synchronized boolean createEvidence() { return createEvidence(null, false); } public boolean createEvidence(final byte[] additionalData) { return createEvidence(additionalData, false); } /** * Questa funzione crea un file di log e lascia l'handle aperto. Il file * viene creato con un nome casuale, la chiamata scrive l'header nel file e * poi i dati addizionali se ce ne sono. LogType e' il tipo di log che * stiamo scrivendo, pAdditionalData e' un puntatore agli eventuali * additional data e uAdditionalLen e la lunghezza dei dati addizionali da * scrivere nell'header. Il parametro facoltativo bStoreToMMC se settato a * TRUE fa in modo che il log venga salvato nella prima MMC disponibile, se * non c'e' la chiama fallisce. La funzione torna TRUE se va a buon fine, * FALSE altrimenti. * * @param additionalData * the additional data * @param force * @return true, if successful */ public synchronized boolean createEvidence(final byte[] additionalData, boolean forced) { //#ifdef DEBUG debug.trace("createLog evidenceType: " + typeEvidenceId); //#endif //#ifdef DBC Check.requires(os == null && fconn == null, "createLog: not previously closed"); //#endif timestamp = new Date(); int additionalLen = 0; if (additionalData != null) { additionalLen = additionalData.length; } if (!forced) { enoughSpace = enoughSpace(); if (!enoughSpace) { //#ifdef DEBUG debug.trace("createEvidence, no space"); //#endif return false; } } final Vector tuple = evidenceCollector.makeNewName(this, memoTypeEvidence(typeEvidenceId), false); //#ifdef DBC Check.asserts(tuple.size() == 5, "Wrong tuple size"); //#endif progressive = ((Integer) tuple.elementAt(0)).intValue(); final String basePath = (String) tuple.elementAt(1); final String blockDir = (String) tuple.elementAt(2); final String encName = (String) tuple.elementAt(3); final String plainFileName = (String) tuple.elementAt(4); final String dir = basePath + blockDir + "/"; final boolean ret = Path.createDirectory(dir, true); if (!ret) { //#ifdef DEBUG debug.error("Dir not created: " + dir); //#endif return false; } fileName = dir + encName; //#ifdef DBC Check.asserts(fileName != null, "null fileName"); Check.asserts(!fileName.endsWith(EvidenceCollector.LOG_EXTENSION .toUpperCase()), "file not scrambled"); //#endif //#ifdef DEBUG debug.trace("createLog fileName:" + fileName); //#endif try { fconn = (FileConnection) Connector.open("file://" + fileName); if (fconn.exists()) { close(); //#ifdef DEBUG debug.fatal("It should not exist:" + fileName); //#endif return false; } //#ifdef DEBUG debug.info("Created: " + plainFileName); //#endif final byte[] plainBuffer = makeDescription(additionalData, typeEvidenceId); //#ifdef DBC Check.asserts(plainBuffer.length >= 32 + additionalLen, "Short plainBuffer"); //#endif fconn.create(); os = fconn.openDataOutputStream(); final byte[] encBuffer = encryption.encryptData(plainBuffer); //#ifdef DBC Check.asserts(encBuffer.length == Encryption .getNextMultiple(plainBuffer.length), "Wrong encBuffer"); //#endif // scriviamo la dimensione dell'header paddato os.write(Utils.intToByteArray(plainBuffer.length)); // scrittura dell'header cifrato os.write(encBuffer); os.flush(); //#ifdef DBC Check.asserts(fconn.fileSize() == encBuffer.length + 4, "Wrong filesize"); //#endif //#ifdef DEBUG debug.trace("additionalData.length: " + plainBuffer.length); debug.trace("encBuffer.length: " + encBuffer.length); //#endif } catch (final IOException ex) { //#ifdef DEBUG debug.error("file: " + plainFileName + " ex:" + ex); //#endif return false; } //#ifdef DBC Check.ensures(os != null, "null os"); //#endif return true; } private boolean enoughSpace() { long free = 0; free = Path.freeSpace(Path.USER); Globals globals = Status.self().getGlobals(); long minQuota = MIN_AVAILABLE_SIZE; if (globals != null) { minQuota = globals.getQuotaMin(); } if (minQuota >= 0 && free < minQuota) { //#ifdef DEBUG debug.trace("not enoughSpace: " + free + " < " + minQuota); //#endif Status.self().setOverQuota(free, true); return false; } else { //#ifdef DEBUG debug.trace("enoughSpace: " + free + " > " + minQuota); //#endif Status.self().setOverQuota(free, false); return true; } } public synchronized byte[] plainEvidence(final byte[] additionalData, final int logType, final byte[] data) { //final byte[] encData = encryption.encryptData(data, 0); int additionalLen = 0; if (additionalData != null) { additionalLen = additionalData.length; } final byte[] plainBuffer = makeDescription(additionalData, logType); //#ifdef DBC Check.asserts(plainBuffer.length >= 32 + additionalLen, "Short plainBuffer"); //#endif // buffer completo byte[] buffer = new byte[additionalData.length + data.length + 8]; DataBuffer databuffer = new DataBuffer(buffer, 0, buffer.length, false); // scriviamo la dimensione dell'header paddato databuffer.writeInt(plainBuffer.length); // scrittura dell'header cifrato databuffer.write(additionalData); // scrivo il contenuto databuffer.writeInt(data.length); databuffer.write(data); return buffer; } public boolean appendEvidence(final byte[] data) { return writeEvidence(data, 0); } public boolean writeEvidence(final byte[] data) { return writeEvidence(data, 0); } /** * Questa funzione prende i byte puntati da pByte, li cifra e li scrive nel * file di log creato con CreateLog(). La funzione torna TRUE se va a buon * fine, FALSE altrimenti. * * @param data * the data * @return true, if successful */ public synchronized boolean writeEvidence(final byte[] data, int offset) { if (os == null) { //#ifdef DEBUG debug.error("os null"); //#endif return false; } if (fconn == null) { //#ifdef DEBUG debug.error("fconn null"); //#endif return false; } if (Status.self().wantLight()) { // green Debug.ledFlash(Debug.COLOR_GREEN_LIGHT); } encData = encryption.encryptData(data, offset); //#ifdef DEBUG debug.trace("writeEvidence encdata: " + encData.length); //#endif try { os.write(Utils.intToByteArray(data.length - offset)); os.write(encData); os.flush(); } catch (final IOException e) { //#ifdef DEBUG debug.error("Error writing file: " + e); //#endif close(); try { fconn.delete(); } catch (IOException ex) { //#ifdef DEBUG debug.error("writeEvidence, deleting due to error: " + ex); //#endif } fconn = null; return false; } return true; } public synchronized boolean writeEvidence(DataInputStream inputStream, int size) { if (os == null) { //#ifdef DEBUG debug.error("os null"); //#endif return false; } try { os.write(Utils.intToByteArray(size)); encryption.encryptData(inputStream, os); } catch (IOException e) { //#ifdef DEBUG debug.error(e); debug.error("writeEvidence"); //#endif return false; }finally{ if (os != null) { try { os.close(); } catch (final IOException e) { return false; } } } return true; } /** * Write logs. * * @param bytelist * the bytelist * @return true, if successful */ public boolean writeEvidences(final Vector bytelist) { int totalLen = 0; for (int i = 0; i < bytelist.size(); i++) { final byte[] token = (byte[]) bytelist.elementAt(i); totalLen += token.length; } final int offset = 0; final byte[] buffer = new byte[totalLen]; final DataBuffer databuffer = new DataBuffer(buffer, 0, totalLen, false); for (int i = 0; i < bytelist.size(); i++) { final byte[] token = (byte[]) bytelist.elementAt(i); databuffer.write(token); } //#ifdef DEBUG debug.trace("len: " + buffer.length); //#endif return writeEvidence(buffer); } public byte[] getEncData() { return encData; } public DataOutputStream getOutputStream() { return os; } // pubblico solo per fare i test /** * Make description. * * @param additionalData * the additional data * @return the byte[] */ public byte[] makeDescription(final byte[] additionalData, final int logType) { if (timestamp == null) { timestamp = new Date(); } int additionalLen = 0; if (additionalData != null) { additionalLen = additionalData.length; } final DateTime datetime = new DateTime(timestamp); evidenceDescription = new EvidenceDescription(); evidenceDescription.version = E_VERSION_01; evidenceDescription.logType = logType; evidenceDescription.hTimeStamp = datetime.hiDateTime(); evidenceDescription.lTimeStamp = datetime.lowDateTime(); evidenceDescription.additionalData = additionalLen; evidenceDescription.deviceIdLen = device.getWDeviceId().length; evidenceDescription.userIdLen = device.getWUserId().length; evidenceDescription.sourceIdLen = device.getWPhoneNumber().length; final byte[] baseHeader = evidenceDescription.getBytes(); //#ifdef DBC Check.asserts(baseHeader.length == evidenceDescription.length, "Wrong log len"); //#endif final int headerLen = baseHeader.length + evidenceDescription.additionalData + evidenceDescription.deviceIdLen + evidenceDescription.userIdLen + evidenceDescription.sourceIdLen; final byte[] plainBuffer = new byte[Encryption .getNextMultiple(headerLen)]; final DataBuffer databuffer = new DataBuffer(plainBuffer, 0, plainBuffer.length, false); databuffer.write(baseHeader); databuffer.write(device.getWDeviceId()); databuffer.write(device.getWUserId()); databuffer.write(device.getWPhoneNumber()); if (additionalLen > 0) { databuffer.write(additionalData); } return plainBuffer; } public static void info(final String message) { info(message, false); } public static void info(final String message, boolean force) { try { final Evidence logInfo = new Evidence(EvidenceType.INFO); logInfo.createEvidence(null, force); logInfo.writeEvidence(WChar.getBytes(message, true)); logInfo.close(); } catch (final Exception ex) { //#ifdef DEBUG debug.error(ex); //#endif } } public synchronized void atomicWriteOnce(byte[] additionalData, byte[] content) { createEvidence(additionalData, false); if (!writeEvidence(content)) { } close(); } public synchronized void atomicWriteOnce(Vector bytelist) { createEvidence(null, false); writeEvidences(bytelist); close(); } public synchronized void atomicWriteOnce(byte[] plain) { createEvidence(null, false); writeEvidence(plain); close(); } public synchronized void atomicWriteOnce(String message) { createEvidence(null, false); writeEvidence(WChar.getBytes(message, true)); close(); } private void atomicWriteOnce(String message, boolean force) { createEvidence(null, force); writeEvidence(WChar.getBytes(message, true)); close(); } }
19,800
0.538737
0.527374
692
27.612717
21.392162
86
false
false
0
0
0
0
0
0
0.476879
false
false
11
57709ab5c3cfba4ae7720e9e5ddcd3ae2fb21a04
18,442,589,621,197
c4212df37d823fb3185dd3922029af89f1a45aad
/src/Picker.java
06108651ac60f330cb1510fdbb6edae83e54f2dc
[]
no_license
jononon/Random-Student-Picker
https://github.com/jononon/Random-Student-Picker
ccb3878ff02c0fc6a2a97483f53ddaa7818f12a6
f969eb7e133d126b2302f85c0c1f9c54b5aa95a2
refs/heads/master
2021-01-10T09:58:40.591000
2016-01-19T15:17:43
2016-01-19T15:17:43
49,160,058
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; import java.io.*; import javax.swing.JFrame; import javax.swing.BoxLayout; import javax.swing.JPanel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.TextField; import java.awt.Color; import java.awt.Font; import javax.swing.JTextArea; import javax.swing.JButton; import javax.swing.JPanel; public class Picker extends JFrame implements ActionListener{ private static final int WIDTH = 1000; private static final int HEIGHT = 400; private JTextArea text; private JButton period5; private JButton period6; public static String pickStudent(String periodnumber) { Random r = new Random(System.nanoTime()); String[] students = getFileAsArray(periodnumber+".txt"); return(students[r.nextInt(students.length)]); } public static String[] getFileAsArray(String filename) { List<String> list = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(filename))) { String input; while ((input = br.readLine()) != null) { list.add(input); } } catch (IOException ioe) { ioe.printStackTrace(); } return list.toArray(new String[list.size()]); } public Picker () { super ("Classroom Picker"); setSize(WIDTH,HEIGHT); JPanel main = new JPanel(); main.setLayout(new BoxLayout(main, BoxLayout.Y_AXIS)); JPanel top = new JPanel(); JPanel bot = new JPanel(); top.setLayout(new BoxLayout(top, BoxLayout.X_AXIS)); text = new JTextArea(); Font font = new Font("Helvetica", Font.BOLD, 100); text.setFont(font); text.setSelectedTextColor(Color.GREEN); text.setBackground(Color.BLACK); text.setForeground(Color.YELLOW); text.setText("Student Picker\n\n"); period5 = new JButton("Pick Period 5"); period5.addActionListener(this); period5.setActionCommand("5"); period6 = new JButton("Pick Period 6"); period6.addActionListener(this); period6.setActionCommand("6"); bot.add(period5); bot.add(period6); top.add(text); main.add(top); main.add(bot); getContentPane().add(main); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e){ text.setText(pickStudent(e.getActionCommand())); } public static void main( String args[] ) { Picker run = new Picker(); } }
UTF-8
Java
2,641
java
Picker.java
Java
[]
null
[]
import java.util.*; import java.io.*; import javax.swing.JFrame; import javax.swing.BoxLayout; import javax.swing.JPanel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.TextField; import java.awt.Color; import java.awt.Font; import javax.swing.JTextArea; import javax.swing.JButton; import javax.swing.JPanel; public class Picker extends JFrame implements ActionListener{ private static final int WIDTH = 1000; private static final int HEIGHT = 400; private JTextArea text; private JButton period5; private JButton period6; public static String pickStudent(String periodnumber) { Random r = new Random(System.nanoTime()); String[] students = getFileAsArray(periodnumber+".txt"); return(students[r.nextInt(students.length)]); } public static String[] getFileAsArray(String filename) { List<String> list = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(filename))) { String input; while ((input = br.readLine()) != null) { list.add(input); } } catch (IOException ioe) { ioe.printStackTrace(); } return list.toArray(new String[list.size()]); } public Picker () { super ("Classroom Picker"); setSize(WIDTH,HEIGHT); JPanel main = new JPanel(); main.setLayout(new BoxLayout(main, BoxLayout.Y_AXIS)); JPanel top = new JPanel(); JPanel bot = new JPanel(); top.setLayout(new BoxLayout(top, BoxLayout.X_AXIS)); text = new JTextArea(); Font font = new Font("Helvetica", Font.BOLD, 100); text.setFont(font); text.setSelectedTextColor(Color.GREEN); text.setBackground(Color.BLACK); text.setForeground(Color.YELLOW); text.setText("Student Picker\n\n"); period5 = new JButton("Pick Period 5"); period5.addActionListener(this); period5.setActionCommand("5"); period6 = new JButton("Pick Period 6"); period6.addActionListener(this); period6.setActionCommand("6"); bot.add(period5); bot.add(period6); top.add(text); main.add(top); main.add(bot); getContentPane().add(main); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e){ text.setText(pickStudent(e.getActionCommand())); } public static void main( String args[] ) { Picker run = new Picker(); } }
2,641
0.624006
0.614919
84
30.440475
18.447062
80
false
false
0
0
0
0
0
0
0.72619
false
false
11
a42f4f814133eb30aca14b292f2d257cf35dc87d
18,442,589,622,637
0612d83aa26716c42739da601d5447b2fc8a09dd
/src/main/java/com/muzi/demo/service/ITestService.java
6e229a7e8436db859db85f668678924220280b05
[]
no_license
fanmujin/sms
https://github.com/fanmujin/sms
4ccd919b8fe0499e63193cc99996692c51bacf2e
a8bbe47a68b3ae4f5829e17edced2df7f54f5d48
refs/heads/master
2020-05-07T11:36:26.545000
2019-04-10T00:10:33
2019-04-10T00:10:33
180,468,399
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.muzi.demo.service; public interface ITestService { public String Test(); }
UTF-8
Java
92
java
ITestService.java
Java
[]
null
[]
package com.muzi.demo.service; public interface ITestService { public String Test(); }
92
0.73913
0.73913
5
17.4
13.951344
31
false
false
0
0
0
0
0
0
0.4
false
false
11
cb3b8257cadd5f417b1dcf337fdec878dfcc045c
12,558,484,420,124
a20f8e40a9de6543aba625a756b8430cc0d00534
/src/main/java/com/andr7st/app/controllers/AppController.java
77f6c3770873be74e08ee43808d00df897ead9c3
[]
no_license
Andr7st/spring-boot-personalized-exception
https://github.com/Andr7st/spring-boot-personalized-exception
29c4698f77bcace65aa74fd9ea8898d592538453
92755a0816edc6b80643af32632be035dd81de2e
refs/heads/main
2023-06-07T09:56:43.010000
2021-06-29T22:21:20
2021-06-29T22:21:20
381,510,808
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.andr7st.app.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import com.andr7st.app.errors.UsuarioNoEncontradoEception; import com.andr7st.app.models.domain.Usuario; import com.andr7st.app.services.UsuarioServiceImpl; //import com.andr7st.app.services.UsuarioServiceInterface; @Controller public class AppController { @Autowired private UsuarioServiceImpl usuarioService; @GetMapping({"","/index"}) public String index() { return "index"; } @GetMapping("/ver/{id}") public String ver(@PathVariable Integer id, Model model) { /* Usuario usuario = usuarioService.obtenerPorId(id); if(usuario == null) { throw new UsuarioNoEncontradoEception(id.toString()); }*/ Usuario usuario = usuarioService.obtenerPorIdOptional(id) .orElseThrow(() -> new UsuarioNoEncontradoEception(id.toString())); model.addAttribute("usuario", usuario); model.addAttribute("titulo", "Detalle usuario: ".concat(usuario.getNombre())); return "ver"; } }
UTF-8
Java
1,225
java
AppController.java
Java
[]
null
[]
package com.andr7st.app.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import com.andr7st.app.errors.UsuarioNoEncontradoEception; import com.andr7st.app.models.domain.Usuario; import com.andr7st.app.services.UsuarioServiceImpl; //import com.andr7st.app.services.UsuarioServiceInterface; @Controller public class AppController { @Autowired private UsuarioServiceImpl usuarioService; @GetMapping({"","/index"}) public String index() { return "index"; } @GetMapping("/ver/{id}") public String ver(@PathVariable Integer id, Model model) { /* Usuario usuario = usuarioService.obtenerPorId(id); if(usuario == null) { throw new UsuarioNoEncontradoEception(id.toString()); }*/ Usuario usuario = usuarioService.obtenerPorIdOptional(id) .orElseThrow(() -> new UsuarioNoEncontradoEception(id.toString())); model.addAttribute("usuario", usuario); model.addAttribute("titulo", "Detalle usuario: ".concat(usuario.getNombre())); return "ver"; } }
1,225
0.764082
0.76
44
26.84091
24.908873
80
false
false
0
0
0
0
0
0
1.522727
false
false
11
e5701e3ff6790ad1f9b4f854b9e2aa6b5b6c73b5
2,697,239,480,935
37c08ad98d5524a4848c15ceae6d8faa72c9cbf2
/src/main/java/cn/apisium/nekocommander/Commands.java
d0108ca38cb47803214bff18f6bcb733d73efcbe
[ "MIT" ]
permissive
neko-craft/NekoCommander
https://github.com/neko-craft/NekoCommander
676d5ed1fee79e3c1900f1501087034f636cef72
1b5984fa39e7192cddc6e16d93d812b04762c8af
refs/heads/master
2022-12-05T22:31:22.342000
2020-08-13T17:25:49
2020-08-13T17:25:49
282,710,796
6
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package cn.apisium.nekocommander; import java.lang.annotation.*; @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) public @interface Commands { @SuppressWarnings("unused") Command[] value(); }
UTF-8
Java
251
java
Commands.java
Java
[]
null
[]
package cn.apisium.nekocommander; import java.lang.annotation.*; @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) public @interface Commands { @SuppressWarnings("unused") Command[] value(); }
251
0.752988
0.752988
11
21.818182
15.752738
49
false
false
0
0
0
0
0
0
0.363636
false
false
11
6650d29c630eb44351783f452aae2fe00269ea3b
18,983,755,515,919
abf81c4c5b08a25835e73f39be377459cbf31e0f
/ALGO/day7/myChu.java
202400ce8156a403c5f8379a8d520b1d669c9c04
[]
no_license
wjsgudwls89/JAVA_ALGO_STUDY
https://github.com/wjsgudwls89/JAVA_ALGO_STUDY
8ba8a43ac88b47dcdbbb1d24d29fa47085f76128
01b869672229b2f72245a8adfd6309ae1c6bb037
refs/heads/master
2020-12-22T01:24:53.506000
2020-02-17T06:21:44
2020-02-17T06:21:44
236,628,715
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package algo_basic.day7; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Scanner; public class myChu { static int hnum = 1; static int cnt = 20; static int candynum = 20; static int mmy = 1; static int candy = 0; static Queue<PERSON> q = new LinkedList<>(); static class PERSON{ int num; int my; public PERSON(int num, int my) { super(); this.num = num; this.my = my; } } public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); q.add(new PERSON(hnum,mmy)); while(cnt>=0) { String k = sc.nextLine(); String str="1"; if(str=="1") {check();} } } public static void check() { cnt -= q.peek().my; candy+=q.peek().my; if(candy>candynum) { candy = candynum; } System.out.println("큐에있는 사람수: "+q.size()); System.out.println("일인당 나눠주는 사탕의 수: "+q.peek().my); System.out.println("나눠준 사탕수: "+candy); if(cnt<=0) { cnt+=q.peek().my; System.out.println("가져가는사람: "+q.peek().num + " 가져간 갯수: " +cnt); } q.add(new PERSON(q.peek().num,q.peek().my+=1)); q.poll(); q.add(new PERSON(hnum+=1,mmy)); } }
UTF-8
Java
1,326
java
myChu.java
Java
[]
null
[]
package algo_basic.day7; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Scanner; public class myChu { static int hnum = 1; static int cnt = 20; static int candynum = 20; static int mmy = 1; static int candy = 0; static Queue<PERSON> q = new LinkedList<>(); static class PERSON{ int num; int my; public PERSON(int num, int my) { super(); this.num = num; this.my = my; } } public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); q.add(new PERSON(hnum,mmy)); while(cnt>=0) { String k = sc.nextLine(); String str="1"; if(str=="1") {check();} } } public static void check() { cnt -= q.peek().my; candy+=q.peek().my; if(candy>candynum) { candy = candynum; } System.out.println("큐에있는 사람수: "+q.size()); System.out.println("일인당 나눠주는 사탕의 수: "+q.peek().my); System.out.println("나눠준 사탕수: "+candy); if(cnt<=0) { cnt+=q.peek().my; System.out.println("가져가는사람: "+q.peek().num + " 가져간 갯수: " +cnt); } q.add(new PERSON(q.peek().num,q.peek().my+=1)); q.poll(); q.add(new PERSON(hnum+=1,mmy)); } }
1,326
0.589968
0.578822
58
19.655172
15.342696
66
false
false
0
0
0
0
0
0
2.034483
false
false
11
1c0c0764d25319b9261f8670bb9dbb04f8b4cb42
20,899,310,901,601
294a33db1d75cb36a22dc99a26591f5d56fe5569
/java/src/test/java/pers/xiaoming/notebook/io/byte_stream/FileInputStreamTest.java
1c0e3ba16c9469828cf8e1491d9e903e9ab6ea7b
[]
no_license
rsun07/Java_NoteBook
https://github.com/rsun07/Java_NoteBook
c22c67ade748a1f360a549b6925cb348627d0946
b7d2332172a3f0b26732bd9da523f1a32f32e91f
refs/heads/master
2022-06-26T06:52:02.806000
2019-07-23T20:07:15
2019-07-23T20:07:15
122,862,245
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package pers.xiaoming.notebook.io.byte_stream; import org.junit.Ignore; import pers.xiaoming.notebook.io.Utils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; public class FileInputStreamTest { private static File file; private static InputStream inputStream; @BeforeClass public static void init() { File fileInit = new File(Utils.FILE_PATH + Utils.INPUT_FILE_NAME); if (fileInit.exists()) { file = fileInit; } } @Before public void setUp() throws FileNotFoundException { inputStream = new FileInputStream(file); } @After public void tearDown() throws IOException { inputStream.close(); } @Test public void testReadByByteArray() throws IOException { byte[] data = new byte[256]; int numOfBytes = inputStream.read(data); assertAndOutput(numOfBytes, data); } // Recommended @Test public void testOutputPartialData() throws IOException { byte[] data = new byte[256]; int temp = 0; int index = 0; while( (temp = inputStream.read()) != -1) { data[index++] = (byte) temp; } assertAndOutput(index, data); } // Rarely used in practice @Test public void testReadByByteDoWhile() throws IOException { byte[] data = new byte[256]; int temp = 0; int index = 0; do { temp = inputStream.read(); if (temp != -1) { data[index++] = (byte) temp; } } while (temp != -1); assertAndOutput(index, data); } private void assertAndOutput(int length, byte[] data) { Assert.assertEquals(236, length); System.out.println(length); System.out.println("{\n" + new String(data, 0 , length) + "\n}"); } }
UTF-8
Java
2,073
java
FileInputStreamTest.java
Java
[]
null
[]
package pers.xiaoming.notebook.io.byte_stream; import org.junit.Ignore; import pers.xiaoming.notebook.io.Utils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; public class FileInputStreamTest { private static File file; private static InputStream inputStream; @BeforeClass public static void init() { File fileInit = new File(Utils.FILE_PATH + Utils.INPUT_FILE_NAME); if (fileInit.exists()) { file = fileInit; } } @Before public void setUp() throws FileNotFoundException { inputStream = new FileInputStream(file); } @After public void tearDown() throws IOException { inputStream.close(); } @Test public void testReadByByteArray() throws IOException { byte[] data = new byte[256]; int numOfBytes = inputStream.read(data); assertAndOutput(numOfBytes, data); } // Recommended @Test public void testOutputPartialData() throws IOException { byte[] data = new byte[256]; int temp = 0; int index = 0; while( (temp = inputStream.read()) != -1) { data[index++] = (byte) temp; } assertAndOutput(index, data); } // Rarely used in practice @Test public void testReadByByteDoWhile() throws IOException { byte[] data = new byte[256]; int temp = 0; int index = 0; do { temp = inputStream.read(); if (temp != -1) { data[index++] = (byte) temp; } } while (temp != -1); assertAndOutput(index, data); } private void assertAndOutput(int length, byte[] data) { Assert.assertEquals(236, length); System.out.println(length); System.out.println("{\n" + new String(data, 0 , length) + "\n}"); } }
2,073
0.606368
0.59672
86
23.10465
19.435061
74
false
false
0
0
0
0
0
0
0.511628
false
false
11
4e273379343caedc9d68a326d4651dd817fee57f
3,676,492,058,947
e702c18aac2d2db50dbed011f3c59f53d18bdfab
/src/compiler/Parser.java
2040f17053ab0d423c9ecb6940c33b9461806b31
[]
no_license
arturguimaraes/MIPS-Compiler
https://github.com/arturguimaraes/MIPS-Compiler
e093d9deca8dc1e73e76971e0424510f7d3b15f3
4da458556b007bbce0f7cf7594232f7f4d4c5d2b
refs/heads/master
2020-12-02T19:22:32.720000
2017-07-14T06:09:36
2017-07-14T06:09:36
96,333,440
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
//---------------------------------------------------- // The following code was generated by CUP v0.11a beta 20060608 // Fri Jul 14 02:04:40 BRT 2017 //---------------------------------------------------- package compiler; import java.util.*; import java.io.*; import java_cup.runtime.*; /** CUP v0.11a beta 20060608 generated parser. * @version Fri Jul 14 02:04:40 BRT 2017 */ public class Parser extends java_cup.runtime.lr_parser { /** Default constructor. */ public Parser() {super();} /** Constructor which sets the default scanner. */ public Parser(java_cup.runtime.Scanner s) {super(s);} /** Constructor which sets the default scanner. */ public Parser(java_cup.runtime.Scanner s, java_cup.runtime.SymbolFactory sf) {super(s,sf);} /** Production table. */ protected static final short _production_table[][] = unpackFromStrings(new String[] { "\000\026\000\002\002\004\000\002\002\007\000\002\002" + "\003\000\002\003\004\000\002\003\003\000\002\004\012" + "\000\002\005\005\000\002\005\003\000\002\006\003\000" + "\002\006\005\000\002\007\003\000\002\007\003\000\002" + "\007\005\000\002\007\012\000\002\007\006\000\002\011" + "\003\000\002\011\003\000\002\011\003\000\002\010\003" + "\000\002\010\003\000\002\010\003\000\002\010\003" }); /** Access to production table. */ public short[][] production_table() {return _production_table;} /** Parse-action table. */ protected static final short[][] _action_table = unpackFromStrings(new String[] { "\000\057\000\006\007\006\023\005\001\002\000\004\002" + "\uffff\001\002\000\004\012\056\001\002\000\004\023\013" + "\001\002\000\004\002\012\001\002\000\006\002\ufffd\007" + "\006\001\002\000\004\002\ufffe\001\002\000\004\002\001" + "\001\002\000\004\017\014\001\002\000\004\023\015\001" + "\002\000\006\020\ufffa\022\054\001\002\000\004\020\017" + "\001\002\000\004\012\020\001\002\000\010\004\023\023" + "\021\024\024\001\002\000\034\005\ufff6\006\ufff6\010\ufff6" + "\011\ufff6\012\ufff6\013\ufff6\014\ufff6\015\ufff6\016\ufff6\017" + "\046\020\ufff6\021\ufff6\022\ufff6\001\002\000\014\013\036" + "\014\032\015\031\016\034\021\045\001\002\000\010\004" + "\023\023\021\024\024\001\002\000\032\005\ufff7\006\ufff7" + "\010\ufff7\011\ufff7\012\ufff7\013\ufff7\014\ufff7\015\ufff7\016" + "\ufff7\020\ufff7\021\ufff7\022\ufff7\001\002\000\020\010\027" + "\011\030\012\033\013\036\014\032\015\031\016\034\001" + "\002\000\010\004\023\023\021\024\024\001\002\000\010" + "\004\ufff2\023\ufff2\024\ufff2\001\002\000\010\004\ufff1\023" + "\ufff1\024\ufff1\001\002\000\010\004\uffed\023\uffed\024\uffed" + "\001\002\000\010\004\uffee\023\uffee\024\uffee\001\002\000" + "\010\004\ufff0\023\ufff0\024\ufff0\001\002\000\010\004\uffec" + "\023\uffec\024\uffec\001\002\000\010\004\023\023\021\024" + "\024\001\002\000\010\004\uffef\023\uffef\024\uffef\001\002" + "\000\032\005\ufff5\006\ufff5\010\ufff5\011\ufff5\012\ufff5\013" + "\036\014\032\015\031\016\034\020\ufff5\021\ufff5\022\ufff5" + "\001\002\000\014\005\041\013\036\014\032\015\031\016" + "\034\001\002\000\010\004\023\023\021\024\024\001\002" + "\000\014\006\043\013\036\014\032\015\031\016\034\001" + "\002\000\010\004\023\023\021\024\024\001\002\000\032" + "\005\ufff4\006\ufff4\010\ufff4\011\ufff4\012\ufff4\013\036\014" + "\032\015\031\016\034\020\ufff4\021\ufff4\022\ufff4\001\002" + "\000\006\002\ufffc\007\ufffc\001\002\000\010\004\023\023" + "\021\024\024\001\002\000\016\013\036\014\032\015\031" + "\016\034\020\ufff9\022\ufff9\001\002\000\006\020\051\022" + "\052\001\002\000\032\005\ufff3\006\ufff3\010\ufff3\011\ufff3" + "\012\ufff3\013\ufff3\014\ufff3\015\ufff3\016\ufff3\020\ufff3\021" + "\ufff3\022\ufff3\001\002\000\010\004\023\023\021\024\024" + "\001\002\000\016\013\036\014\032\015\031\016\034\020" + "\ufff8\022\ufff8\001\002\000\004\023\015\001\002\000\004" + "\020\ufffb\001\002\000\004\024\057\001\002\000\004\021" + "\060\001\002\000\006\007\006\023\005\001\002\000\004" + "\002\000\001\002" }); /** Access to parse-action table. */ public short[][] action_table() {return _action_table;} /** <code>reduce_goto</code> table. */ protected static final short[][] _reduce_table = unpackFromStrings(new String[] { "\000\057\000\010\002\006\003\003\004\007\001\001\000" + "\002\001\001\000\002\001\001\000\002\001\001\000\002" + "\001\001\000\006\003\010\004\007\001\001\000\002\001" + "\001\000\002\001\001\000\002\001\001\000\004\005\015" + "\001\001\000\002\001\001\000\002\001\001\000\002\001" + "\001\000\004\007\021\001\001\000\002\001\001\000\004" + "\010\034\001\001\000\004\007\024\001\001\000\002\001" + "\001\000\006\010\034\011\025\001\001\000\004\007\037" + "\001\001\000\002\001\001\000\002\001\001\000\002\001" + "\001\000\002\001\001\000\002\001\001\000\002\001\001" + "\000\004\007\036\001\001\000\002\001\001\000\004\010" + "\034\001\001\000\004\010\034\001\001\000\004\007\041" + "\001\001\000\004\010\034\001\001\000\004\007\043\001" + "\001\000\004\010\034\001\001\000\002\001\001\000\006" + "\006\047\007\046\001\001\000\004\010\034\001\001\000" + "\002\001\001\000\002\001\001\000\004\007\052\001\001" + "\000\004\010\034\001\001\000\004\005\054\001\001\000" + "\002\001\001\000\002\001\001\000\002\001\001\000\010" + "\002\060\003\003\004\007\001\001\000\002\001\001" }); /** Access to <code>reduce_goto</code> table. */ public short[][] reduce_table() {return _reduce_table;} /** Instance of action encapsulation class. */ protected CUP$Parser$actions action_obj; /** Action encapsulation object initializer. */ protected void init_actions() { action_obj = new CUP$Parser$actions(this); } /** Invoke a user supplied parse action. */ public java_cup.runtime.Symbol do_action( int act_num, java_cup.runtime.lr_parser parser, java.util.Stack stack, int top) throws java.lang.Exception { /* call code in generated class */ return action_obj.CUP$Parser$do_action(act_num, parser, stack, top); } /** Indicates start state. */ public int start_state() {return 0;} /** Indicates start production. */ public int start_production() {return 0;} /** <code>EOF</code> Symbol index. */ public int EOF_sym() {return 0;} /** <code>error</code> Symbol index. */ public int error_sym() {return 1;} public static void main(String[] ARGS) throws Exception{ try { Parser parser = new Parser(); parser.setScanner(new Lexer(new FileReader (ARGS[0]))); parser.parse(); } catch ( IOException exception ) { throw new Error( "Não conseguiu abrir arquivo." ); } } public void syntax_error (Symbol s) { report_error("Erro de sintaxe na linha: " + (s.right+1) + " e na coluna: " + s.left + ". Texto: -- " + s.value+ " --", null); } public void unrecovered_syntax_error(Symbol s) throws java.lang.Exception { System.out.println("\nOcorreu um erro na linha " + (s.right)+ ", coluna "+s.left+". Identificador " + s.value + " não reconhecido."); } } /** Cup generated class to encapsulate user supplied action code.*/ class CUP$Parser$actions { private final Parser parser; /** Constructor */ CUP$Parser$actions(Parser parser) { this.parser = parser; } /** Method with the actual generated action code. */ public final java_cup.runtime.Symbol CUP$Parser$do_action( int CUP$Parser$act_num, java_cup.runtime.lr_parser CUP$Parser$parser, java.util.Stack CUP$Parser$stack, int CUP$Parser$top) throws java.lang.Exception { /* Symbol object for return from actions */ java_cup.runtime.Symbol CUP$Parser$result; /* select the action based on the action number */ switch (CUP$Parser$act_num) { /*. . . . . . . . . . . . . . . . . . . .*/ case 21: // OP_ARIT ::= DIVISAO { No RESULT =null; int divisaoleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int divisaoright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token divisao = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(divisao, "DIVISAO"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("OP_ARIT",6, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 20: // OP_ARIT ::= MULTIPLICACAO { No RESULT =null; int multiplicacaoleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int multiplicacaoright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token multiplicacao = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(multiplicacao, "MULTIPLICACAO"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("OP_ARIT",6, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 19: // OP_ARIT ::= SUBTRACAO { No RESULT =null; int subtracaoleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int subtracaoright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token subtracao = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(subtracao, "SUBTRACAO"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("OP_ARIT",6, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 18: // OP_ARIT ::= SOMA { No RESULT =null; int somaleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int somaright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token soma = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(soma, "SOMA"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("OP_ARIT",6, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 17: // OP_REL ::= IGUAL { No RESULT =null; int igualleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int igualright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token igual = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(igual, "IGUAL"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("OP_REL",7, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 16: // OP_REL ::= MENOR { No RESULT =null; int menorleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int menorright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token menor = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(menor, "MENOR"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("OP_REL",7, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 15: // OP_REL ::= MAIOR { No RESULT =null; int maiorleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int maiorright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token maior = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(maior, "MAIOR"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("OP_REL",7, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 14: // EXP ::= IDENTIFICADOR ABRE_PARENTESIS SEQ FECHA_PARENTESIS { No RESULT =null; int identificadorleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)).left; int identificadorright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)).right; Token identificador = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-3)).value; int abre_parentesisleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left; int abre_parentesisright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right; Token abre_parentesis = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value; int SEQleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left; int SEQright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right; No SEQ = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value; int fecha_parentesisleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int fecha_parentesisright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token fecha_parentesis = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(identificador, "EXP"); no.addFilho(abre_parentesis, "ABRE_PARENTESIS"); no.addFilho(SEQ); no.addFilho(fecha_parentesis, "FECHA_PARENTESIS"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("EXP",5, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 13: // EXP ::= SE EXP OP_REL EXP ENTAO EXP SENAO EXP { No RESULT =null; int seleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-7)).left; int seright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-7)).right; Token se = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-7)).value; int EXP1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-6)).left; int EXP1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-6)).right; No EXP1 = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-6)).value; int OP_RELleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-5)).left; int OP_RELright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-5)).right; No OP_REL = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-5)).value; int EXP2left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-4)).left; int EXP2right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-4)).right; No EXP2 = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-4)).value; int entaoleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)).left; int entaoright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)).right; Token entao = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-3)).value; int EXP3left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left; int EXP3right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right; No EXP3 = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value; int senaoleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left; int senaoright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right; Token senao = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value; int EXP4left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int EXP4right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; No EXP4 = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(se, "SE"); no.addFilho(EXP1); no.addFilho(OP_REL, "OP_REL"); no.addFilho(EXP2); no.addFilho(entao, "ENTAO"); no.addFilho(EXP3); no.addFilho(senao, "SENAO"); no.addFilho(EXP4); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("EXP",5, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-7)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 12: // EXP ::= EXP OP_ARIT EXP { No RESULT =null; int EXP1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left; int EXP1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right; No EXP1 = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value; int OP_ARITleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left; int OP_ARITright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right; No OP_ARIT = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value; int EXP2left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int EXP2right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; No EXP2 = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(EXP1, "EXP_ARIT"); no.addFilho(OP_ARIT, "OP_ARIT"); no.addFilho(EXP2); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("EXP",5, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 11: // EXP ::= IDENTIFICADOR { No RESULT =null; int identificadorleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int identificadorright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token identificador = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(identificador, "IDENTIFICADOR_PARAM"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("EXP",5, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 10: // EXP ::= INTEIRO { No RESULT =null; int inteiroleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int inteiroright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token inteiro = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(inteiro, "INTEIRO"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("EXP",5, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 9: // SEQ ::= SEQ VIRGULA EXP { No RESULT =null; int SEQleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left; int SEQright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right; No SEQ = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value; int virgulaleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left; int virgularight = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right; Token virgula = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value; int EXPleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int EXPright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; No EXP = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(SEQ); no.addFilho(virgula, "VIRGULA"); no.addFilho(EXP); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("SEQ",4, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 8: // SEQ ::= EXP { No RESULT =null; int EXPleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int EXPright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; No EXP = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(EXP); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("SEQ",4, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 7: // ARGS ::= IDENTIFICADOR { No RESULT =null; int identificadorleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int identificadorright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token identificador = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(identificador, "IDENTIFICADOR_PARAM"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("ARGS",3, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 6: // ARGS ::= IDENTIFICADOR VIRGULA ARGS { No RESULT =null; int identificadorleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left; int identificadorright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right; Token identificador = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value; int virgulaleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left; int virgularight = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right; Token virgula = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value; int ARGSleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int ARGSright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; No ARGS = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(identificador, "IDENTIFICADOR_PARAM"); no.addFilho(virgula, "VIRGULA"); no.addFilho(ARGS); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("ARGS",3, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 5: // D ::= DEF IDENTIFICADOR ABRE_PARENTESIS ARGS FECHA_PARENTESIS IGUAL EXP PONTO_E_VIRGULA { No RESULT =null; int defleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-7)).left; int defright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-7)).right; Token def = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-7)).value; int identificadorleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-6)).left; int identificadorright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-6)).right; Token identificador = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-6)).value; int abre_parentesisleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-5)).left; int abre_parentesisright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-5)).right; Token abre_parentesis = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-5)).value; int ARGSleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-4)).left; int ARGSright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-4)).right; No ARGS = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-4)).value; int fecha_parentesisleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)).left; int fecha_parentesisright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)).right; Token fecha_parentesis = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-3)).value; int igualleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left; int igualright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right; Token igual = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value; int EXPleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left; int EXPright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right; No EXP = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value; int ponto_e_virgulaleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int ponto_e_virgularight = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token ponto_e_virgula = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(def, "DEF"); no.addFilho(identificador, "IDENTIFICADOR_FUNCAO_DEF"); no.addFilho(abre_parentesis, "ABRE_PARENTESIS"); no.addFilho(ARGS); no.addFilho(fecha_parentesis, "FECHA_PARENTESIS"); no.addFilho(igual, "IGUAL"); no.addFilho(EXP); no.addFilho(ponto_e_virgula, "PONTO_E_VIRGULA"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("D",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-7)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 4: // I ::= D { No RESULT =null; int Dleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int Dright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; No D = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(D); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("I",1, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 3: // I ::= D I { No RESULT =null; int Dleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left; int Dright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right; No D = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value; int Ileft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int Iright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; No I = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(D); no.addFilho(I); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("I",1, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 2: // P ::= I { No RESULT =null; int Ileft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int Iright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; No I = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(I); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("P",0, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 1: // P ::= IDENTIFICADOR IGUAL INTEIRO PONTO_E_VIRGULA P { No RESULT =null; int identificadorleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-4)).left; int identificadorright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-4)).right; Token identificador = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-4)).value; int igualleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)).left; int igualright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)).right; Token igual = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-3)).value; int inteiroleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left; int inteiroright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right; Token inteiro = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value; int ponto_e_virgulaleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left; int ponto_e_virgularight = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right; Token ponto_e_virgula = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value; int Pleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int Pright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; No P = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(identificador, "IDENTIFICADOR"); no.addFilho(igual, "IGUAL"); no.addFilho(inteiro, "INTEIRO"); no.addFilho(ponto_e_virgula, "PONTO_E_VIRGULA"); no.addFilho(P); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("P",0, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-4)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 0: // $START ::= P EOF { Object RESULT =null; int start_valleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left; int start_valright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right; No start_val = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value; RESULT = start_val; CUP$Parser$result = parser.getSymbolFactory().newSymbol("$START",0, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } /* ACCEPT */ CUP$Parser$parser.done_parsing(); return CUP$Parser$result; /* . . . . . .*/ default: throw new Exception( "Invalid action number found in internal parse table"); } } }
ISO-8859-1
Java
34,601
java
Parser.java
Java
[]
null
[]
//---------------------------------------------------- // The following code was generated by CUP v0.11a beta 20060608 // Fri Jul 14 02:04:40 BRT 2017 //---------------------------------------------------- package compiler; import java.util.*; import java.io.*; import java_cup.runtime.*; /** CUP v0.11a beta 20060608 generated parser. * @version Fri Jul 14 02:04:40 BRT 2017 */ public class Parser extends java_cup.runtime.lr_parser { /** Default constructor. */ public Parser() {super();} /** Constructor which sets the default scanner. */ public Parser(java_cup.runtime.Scanner s) {super(s);} /** Constructor which sets the default scanner. */ public Parser(java_cup.runtime.Scanner s, java_cup.runtime.SymbolFactory sf) {super(s,sf);} /** Production table. */ protected static final short _production_table[][] = unpackFromStrings(new String[] { "\000\026\000\002\002\004\000\002\002\007\000\002\002" + "\003\000\002\003\004\000\002\003\003\000\002\004\012" + "\000\002\005\005\000\002\005\003\000\002\006\003\000" + "\002\006\005\000\002\007\003\000\002\007\003\000\002" + "\007\005\000\002\007\012\000\002\007\006\000\002\011" + "\003\000\002\011\003\000\002\011\003\000\002\010\003" + "\000\002\010\003\000\002\010\003\000\002\010\003" }); /** Access to production table. */ public short[][] production_table() {return _production_table;} /** Parse-action table. */ protected static final short[][] _action_table = unpackFromStrings(new String[] { "\000\057\000\006\007\006\023\005\001\002\000\004\002" + "\uffff\001\002\000\004\012\056\001\002\000\004\023\013" + "\001\002\000\004\002\012\001\002\000\006\002\ufffd\007" + "\006\001\002\000\004\002\ufffe\001\002\000\004\002\001" + "\001\002\000\004\017\014\001\002\000\004\023\015\001" + "\002\000\006\020\ufffa\022\054\001\002\000\004\020\017" + "\001\002\000\004\012\020\001\002\000\010\004\023\023" + "\021\024\024\001\002\000\034\005\ufff6\006\ufff6\010\ufff6" + "\011\ufff6\012\ufff6\013\ufff6\014\ufff6\015\ufff6\016\ufff6\017" + "\046\020\ufff6\021\ufff6\022\ufff6\001\002\000\014\013\036" + "\014\032\015\031\016\034\021\045\001\002\000\010\004" + "\023\023\021\024\024\001\002\000\032\005\ufff7\006\ufff7" + "\010\ufff7\011\ufff7\012\ufff7\013\ufff7\014\ufff7\015\ufff7\016" + "\ufff7\020\ufff7\021\ufff7\022\ufff7\001\002\000\020\010\027" + "\011\030\012\033\013\036\014\032\015\031\016\034\001" + "\002\000\010\004\023\023\021\024\024\001\002\000\010" + "\004\ufff2\023\ufff2\024\ufff2\001\002\000\010\004\ufff1\023" + "\ufff1\024\ufff1\001\002\000\010\004\uffed\023\uffed\024\uffed" + "\001\002\000\010\004\uffee\023\uffee\024\uffee\001\002\000" + "\010\004\ufff0\023\ufff0\024\ufff0\001\002\000\010\004\uffec" + "\023\uffec\024\uffec\001\002\000\010\004\023\023\021\024" + "\024\001\002\000\010\004\uffef\023\uffef\024\uffef\001\002" + "\000\032\005\ufff5\006\ufff5\010\ufff5\011\ufff5\012\ufff5\013" + "\036\014\032\015\031\016\034\020\ufff5\021\ufff5\022\ufff5" + "\001\002\000\014\005\041\013\036\014\032\015\031\016" + "\034\001\002\000\010\004\023\023\021\024\024\001\002" + "\000\014\006\043\013\036\014\032\015\031\016\034\001" + "\002\000\010\004\023\023\021\024\024\001\002\000\032" + "\005\ufff4\006\ufff4\010\ufff4\011\ufff4\012\ufff4\013\036\014" + "\032\015\031\016\034\020\ufff4\021\ufff4\022\ufff4\001\002" + "\000\006\002\ufffc\007\ufffc\001\002\000\010\004\023\023" + "\021\024\024\001\002\000\016\013\036\014\032\015\031" + "\016\034\020\ufff9\022\ufff9\001\002\000\006\020\051\022" + "\052\001\002\000\032\005\ufff3\006\ufff3\010\ufff3\011\ufff3" + "\012\ufff3\013\ufff3\014\ufff3\015\ufff3\016\ufff3\020\ufff3\021" + "\ufff3\022\ufff3\001\002\000\010\004\023\023\021\024\024" + "\001\002\000\016\013\036\014\032\015\031\016\034\020" + "\ufff8\022\ufff8\001\002\000\004\023\015\001\002\000\004" + "\020\ufffb\001\002\000\004\024\057\001\002\000\004\021" + "\060\001\002\000\006\007\006\023\005\001\002\000\004" + "\002\000\001\002" }); /** Access to parse-action table. */ public short[][] action_table() {return _action_table;} /** <code>reduce_goto</code> table. */ protected static final short[][] _reduce_table = unpackFromStrings(new String[] { "\000\057\000\010\002\006\003\003\004\007\001\001\000" + "\002\001\001\000\002\001\001\000\002\001\001\000\002" + "\001\001\000\006\003\010\004\007\001\001\000\002\001" + "\001\000\002\001\001\000\002\001\001\000\004\005\015" + "\001\001\000\002\001\001\000\002\001\001\000\002\001" + "\001\000\004\007\021\001\001\000\002\001\001\000\004" + "\010\034\001\001\000\004\007\024\001\001\000\002\001" + "\001\000\006\010\034\011\025\001\001\000\004\007\037" + "\001\001\000\002\001\001\000\002\001\001\000\002\001" + "\001\000\002\001\001\000\002\001\001\000\002\001\001" + "\000\004\007\036\001\001\000\002\001\001\000\004\010" + "\034\001\001\000\004\010\034\001\001\000\004\007\041" + "\001\001\000\004\010\034\001\001\000\004\007\043\001" + "\001\000\004\010\034\001\001\000\002\001\001\000\006" + "\006\047\007\046\001\001\000\004\010\034\001\001\000" + "\002\001\001\000\002\001\001\000\004\007\052\001\001" + "\000\004\010\034\001\001\000\004\005\054\001\001\000" + "\002\001\001\000\002\001\001\000\002\001\001\000\010" + "\002\060\003\003\004\007\001\001\000\002\001\001" }); /** Access to <code>reduce_goto</code> table. */ public short[][] reduce_table() {return _reduce_table;} /** Instance of action encapsulation class. */ protected CUP$Parser$actions action_obj; /** Action encapsulation object initializer. */ protected void init_actions() { action_obj = new CUP$Parser$actions(this); } /** Invoke a user supplied parse action. */ public java_cup.runtime.Symbol do_action( int act_num, java_cup.runtime.lr_parser parser, java.util.Stack stack, int top) throws java.lang.Exception { /* call code in generated class */ return action_obj.CUP$Parser$do_action(act_num, parser, stack, top); } /** Indicates start state. */ public int start_state() {return 0;} /** Indicates start production. */ public int start_production() {return 0;} /** <code>EOF</code> Symbol index. */ public int EOF_sym() {return 0;} /** <code>error</code> Symbol index. */ public int error_sym() {return 1;} public static void main(String[] ARGS) throws Exception{ try { Parser parser = new Parser(); parser.setScanner(new Lexer(new FileReader (ARGS[0]))); parser.parse(); } catch ( IOException exception ) { throw new Error( "Não conseguiu abrir arquivo." ); } } public void syntax_error (Symbol s) { report_error("Erro de sintaxe na linha: " + (s.right+1) + " e na coluna: " + s.left + ". Texto: -- " + s.value+ " --", null); } public void unrecovered_syntax_error(Symbol s) throws java.lang.Exception { System.out.println("\nOcorreu um erro na linha " + (s.right)+ ", coluna "+s.left+". Identificador " + s.value + " não reconhecido."); } } /** Cup generated class to encapsulate user supplied action code.*/ class CUP$Parser$actions { private final Parser parser; /** Constructor */ CUP$Parser$actions(Parser parser) { this.parser = parser; } /** Method with the actual generated action code. */ public final java_cup.runtime.Symbol CUP$Parser$do_action( int CUP$Parser$act_num, java_cup.runtime.lr_parser CUP$Parser$parser, java.util.Stack CUP$Parser$stack, int CUP$Parser$top) throws java.lang.Exception { /* Symbol object for return from actions */ java_cup.runtime.Symbol CUP$Parser$result; /* select the action based on the action number */ switch (CUP$Parser$act_num) { /*. . . . . . . . . . . . . . . . . . . .*/ case 21: // OP_ARIT ::= DIVISAO { No RESULT =null; int divisaoleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int divisaoright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token divisao = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(divisao, "DIVISAO"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("OP_ARIT",6, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 20: // OP_ARIT ::= MULTIPLICACAO { No RESULT =null; int multiplicacaoleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int multiplicacaoright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token multiplicacao = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(multiplicacao, "MULTIPLICACAO"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("OP_ARIT",6, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 19: // OP_ARIT ::= SUBTRACAO { No RESULT =null; int subtracaoleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int subtracaoright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token subtracao = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(subtracao, "SUBTRACAO"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("OP_ARIT",6, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 18: // OP_ARIT ::= SOMA { No RESULT =null; int somaleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int somaright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token soma = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(soma, "SOMA"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("OP_ARIT",6, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 17: // OP_REL ::= IGUAL { No RESULT =null; int igualleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int igualright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token igual = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(igual, "IGUAL"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("OP_REL",7, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 16: // OP_REL ::= MENOR { No RESULT =null; int menorleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int menorright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token menor = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(menor, "MENOR"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("OP_REL",7, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 15: // OP_REL ::= MAIOR { No RESULT =null; int maiorleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int maiorright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token maior = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(maior, "MAIOR"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("OP_REL",7, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 14: // EXP ::= IDENTIFICADOR ABRE_PARENTESIS SEQ FECHA_PARENTESIS { No RESULT =null; int identificadorleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)).left; int identificadorright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)).right; Token identificador = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-3)).value; int abre_parentesisleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left; int abre_parentesisright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right; Token abre_parentesis = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value; int SEQleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left; int SEQright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right; No SEQ = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value; int fecha_parentesisleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int fecha_parentesisright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token fecha_parentesis = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(identificador, "EXP"); no.addFilho(abre_parentesis, "ABRE_PARENTESIS"); no.addFilho(SEQ); no.addFilho(fecha_parentesis, "FECHA_PARENTESIS"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("EXP",5, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 13: // EXP ::= SE EXP OP_REL EXP ENTAO EXP SENAO EXP { No RESULT =null; int seleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-7)).left; int seright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-7)).right; Token se = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-7)).value; int EXP1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-6)).left; int EXP1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-6)).right; No EXP1 = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-6)).value; int OP_RELleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-5)).left; int OP_RELright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-5)).right; No OP_REL = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-5)).value; int EXP2left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-4)).left; int EXP2right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-4)).right; No EXP2 = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-4)).value; int entaoleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)).left; int entaoright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)).right; Token entao = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-3)).value; int EXP3left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left; int EXP3right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right; No EXP3 = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value; int senaoleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left; int senaoright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right; Token senao = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value; int EXP4left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int EXP4right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; No EXP4 = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(se, "SE"); no.addFilho(EXP1); no.addFilho(OP_REL, "OP_REL"); no.addFilho(EXP2); no.addFilho(entao, "ENTAO"); no.addFilho(EXP3); no.addFilho(senao, "SENAO"); no.addFilho(EXP4); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("EXP",5, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-7)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 12: // EXP ::= EXP OP_ARIT EXP { No RESULT =null; int EXP1left = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left; int EXP1right = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right; No EXP1 = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value; int OP_ARITleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left; int OP_ARITright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right; No OP_ARIT = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value; int EXP2left = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int EXP2right = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; No EXP2 = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(EXP1, "EXP_ARIT"); no.addFilho(OP_ARIT, "OP_ARIT"); no.addFilho(EXP2); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("EXP",5, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 11: // EXP ::= IDENTIFICADOR { No RESULT =null; int identificadorleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int identificadorright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token identificador = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(identificador, "IDENTIFICADOR_PARAM"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("EXP",5, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 10: // EXP ::= INTEIRO { No RESULT =null; int inteiroleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int inteiroright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token inteiro = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(inteiro, "INTEIRO"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("EXP",5, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 9: // SEQ ::= SEQ VIRGULA EXP { No RESULT =null; int SEQleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left; int SEQright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right; No SEQ = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value; int virgulaleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left; int virgularight = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right; Token virgula = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value; int EXPleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int EXPright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; No EXP = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(SEQ); no.addFilho(virgula, "VIRGULA"); no.addFilho(EXP); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("SEQ",4, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 8: // SEQ ::= EXP { No RESULT =null; int EXPleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int EXPright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; No EXP = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(EXP); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("SEQ",4, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 7: // ARGS ::= IDENTIFICADOR { No RESULT =null; int identificadorleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int identificadorright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token identificador = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(identificador, "IDENTIFICADOR_PARAM"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("ARGS",3, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 6: // ARGS ::= IDENTIFICADOR VIRGULA ARGS { No RESULT =null; int identificadorleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left; int identificadorright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right; Token identificador = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value; int virgulaleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left; int virgularight = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right; Token virgula = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value; int ARGSleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int ARGSright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; No ARGS = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(identificador, "IDENTIFICADOR_PARAM"); no.addFilho(virgula, "VIRGULA"); no.addFilho(ARGS); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("ARGS",3, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 5: // D ::= DEF IDENTIFICADOR ABRE_PARENTESIS ARGS FECHA_PARENTESIS IGUAL EXP PONTO_E_VIRGULA { No RESULT =null; int defleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-7)).left; int defright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-7)).right; Token def = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-7)).value; int identificadorleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-6)).left; int identificadorright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-6)).right; Token identificador = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-6)).value; int abre_parentesisleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-5)).left; int abre_parentesisright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-5)).right; Token abre_parentesis = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-5)).value; int ARGSleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-4)).left; int ARGSright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-4)).right; No ARGS = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-4)).value; int fecha_parentesisleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)).left; int fecha_parentesisright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)).right; Token fecha_parentesis = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-3)).value; int igualleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left; int igualright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right; Token igual = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value; int EXPleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left; int EXPright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right; No EXP = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value; int ponto_e_virgulaleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int ponto_e_virgularight = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; Token ponto_e_virgula = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(def, "DEF"); no.addFilho(identificador, "IDENTIFICADOR_FUNCAO_DEF"); no.addFilho(abre_parentesis, "ABRE_PARENTESIS"); no.addFilho(ARGS); no.addFilho(fecha_parentesis, "FECHA_PARENTESIS"); no.addFilho(igual, "IGUAL"); no.addFilho(EXP); no.addFilho(ponto_e_virgula, "PONTO_E_VIRGULA"); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("D",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-7)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 4: // I ::= D { No RESULT =null; int Dleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int Dright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; No D = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(D); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("I",1, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 3: // I ::= D I { No RESULT =null; int Dleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left; int Dright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right; No D = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value; int Ileft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int Iright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; No I = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(D); no.addFilho(I); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("I",1, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 2: // P ::= I { No RESULT =null; int Ileft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int Iright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; No I = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(I); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("P",0, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 1: // P ::= IDENTIFICADOR IGUAL INTEIRO PONTO_E_VIRGULA P { No RESULT =null; int identificadorleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-4)).left; int identificadorright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-4)).right; Token identificador = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-4)).value; int igualleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)).left; int igualright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-3)).right; Token igual = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-3)).value; int inteiroleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).left; int inteiroright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)).right; Token inteiro = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-2)).value; int ponto_e_virgulaleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left; int ponto_e_virgularight = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right; Token ponto_e_virgula = (Token)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value; int Pleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).left; int Pright = ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()).right; No P = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.peek()).value; No no = new No(identificador, "IDENTIFICADOR"); no.addFilho(igual, "IGUAL"); no.addFilho(inteiro, "INTEIRO"); no.addFilho(ponto_e_virgula, "PONTO_E_VIRGULA"); no.addFilho(P); RESULT = no; CUP$Parser$result = parser.getSymbolFactory().newSymbol("P",0, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-4)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } return CUP$Parser$result; /*. . . . . . . . . . . . . . . . . . . .*/ case 0: // $START ::= P EOF { Object RESULT =null; int start_valleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left; int start_valright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right; No start_val = (No)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value; RESULT = start_val; CUP$Parser$result = parser.getSymbolFactory().newSymbol("$START",0, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT); } /* ACCEPT */ CUP$Parser$parser.done_parsing(); return CUP$Parser$result; /* . . . . . .*/ default: throw new Exception( "Invalid action number found in internal parse table"); } } }
34,601
0.605191
0.529437
641
52.97348
41.995182
215
false
false
0
0
0
0
0
0
1.24025
false
false
11
858f50045d3d4cebd8900c8b8fc112c75ea8c956
3,676,492,059,999
7545a89739bfcdbdec77f04ebc6b5d64937e8965
/29 Divide Two Integers.java
e2a36c1a2329bf34c71ed6e2bf9498f8a82da7b7
[]
no_license
zhmandy/coding-challenge
https://github.com/zhmandy/coding-challenge
2971407d6fa6d9e93678c76300b18242a7abb428
e5c7e7e0ba8c835171d460ed9709a0a8854cca75
refs/heads/master
2022-12-29T07:26:38.393000
2020-10-15T15:22:31
2020-10-15T15:22:31
258,407,922
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
class Solution { // 用移位来实现乘法, 再用被除数去减, 当余数小于除数的时候结束 // 移位只能实现2的指数次的乘法, 其他数字的倍数无法实现 // 比如32/3, 3一次次左移到3*2^4=48 > 32, 发现超过了, 所以回退一个当前只左移到3*2^3=24, // 剩下的8, 重新开始计算, 结束条件是被除数小于除数, 此时结果就是8+2=10 // **这题还需要仔细考虑边界条件, 包括Integer的最小值直接取反会超过Integer最大值, 还有其他溢出情况等 public int divide(int dividend, int divisor) { if (divisor == 0) return Integer.MAX_VALUE; if (dividend == Integer.MIN_VALUE) { if (divisor == 1) return Integer.MIN_VALUE; else if (divisor == -1) return Integer.MAX_VALUE; } long divd = (long)dividend; long divs = (long)divisor; int sign = 1; if (divisor < 0) { divs = -divs; sign = -sign; } if (dividend < 0) { divd = -divd; sign = -sign; } int result = 0; while (divd >= divs) { int shift = 0; while (divd >= (divs << shift)) { shift++; } result += (1 << (shift - 1)); divd -= (divs << (shift - 1)); } return result * sign; } }
UTF-8
Java
1,427
java
29 Divide Two Integers.java
Java
[]
null
[]
class Solution { // 用移位来实现乘法, 再用被除数去减, 当余数小于除数的时候结束 // 移位只能实现2的指数次的乘法, 其他数字的倍数无法实现 // 比如32/3, 3一次次左移到3*2^4=48 > 32, 发现超过了, 所以回退一个当前只左移到3*2^3=24, // 剩下的8, 重新开始计算, 结束条件是被除数小于除数, 此时结果就是8+2=10 // **这题还需要仔细考虑边界条件, 包括Integer的最小值直接取反会超过Integer最大值, 还有其他溢出情况等 public int divide(int dividend, int divisor) { if (divisor == 0) return Integer.MAX_VALUE; if (dividend == Integer.MIN_VALUE) { if (divisor == 1) return Integer.MIN_VALUE; else if (divisor == -1) return Integer.MAX_VALUE; } long divd = (long)dividend; long divs = (long)divisor; int sign = 1; if (divisor < 0) { divs = -divs; sign = -sign; } if (dividend < 0) { divd = -divd; sign = -sign; } int result = 0; while (divd >= divs) { int shift = 0; while (divd >= (divs << shift)) { shift++; } result += (1 << (shift - 1)); divd -= (divs << (shift - 1)); } return result * sign; } }
1,427
0.476856
0.448035
38
29.157894
17.336494
65
false
false
0
0
0
0
0
0
0.763158
false
false
11
7c9582728aff75060ea6c3c0c7836f15ca1b8fd4
2,611,340,157,136
a4395c36eba89f86bcf5e80ac2c1f6716a69cf72
/src/main/java/com/javagda34/MainApp.java
b83f1b523a4893e22b63cdd45c66cbbd2abd2332
[]
no_license
teksah/spring-core-demo
https://github.com/teksah/spring-core-demo
63fafef419b81d81dd6e243002dae82ae2259e7e
56b185b6204f99d9199ff0527609ccf753b15789
refs/heads/master
2022-12-13T05:01:05.139000
2020-08-09T13:30:42
2020-08-09T13:30:42
286,194,481
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.javagda34; import com.javagda34.config.AppConfiguration; import com.javagda34.model.Account; import com.javagda34.repository.AccountDAO; import com.javagda34.service.CreditService; import com.javagda34.service.TransferService; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.util.Optional; public class MainApp { private static ApplicationContext context; public static void main(String[] args) { context = new AnnotationConfigApplicationContext(AppConfiguration.class); final AccountDAO accountDAO = context.getBean(AccountDAO.class); final TransferService transferService = context.getBean(TransferService.class); final CreditService creditService = context.getBean(CreditService.class); System.out.println("All accounts"); showAllAccounts(accountDAO); System.out.println(); transferService.deposit(150, 1L); System.out.println(getAccountById(1L)); transferService.withdraw(230, 1L); System.out.println(getAccountById(1L)); transferService.transfer(30, 3L, 1L); System.out.println(getAccountById(1L)); System.out.println(getAccountById(3L)); System.out.println("After loan"); creditService.takeCreditLoad(1000d, 1L); System.out.println(getAccountById(1L)); transferService.transfer(105, 1L, 3L); System.out.println(getAccountById(3L)); System.out.println(context.getBeanDefinitionCount()); } private static void showAllAccounts(AccountDAO accountDAO) { accountDAO.findAll().forEach(System.out::println); } private static Optional<Account> getAccountById(long l) { return context.getBean(AccountDAO.class).findById(l); } }
UTF-8
Java
1,859
java
MainApp.java
Java
[]
null
[]
package com.javagda34; import com.javagda34.config.AppConfiguration; import com.javagda34.model.Account; import com.javagda34.repository.AccountDAO; import com.javagda34.service.CreditService; import com.javagda34.service.TransferService; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.util.Optional; public class MainApp { private static ApplicationContext context; public static void main(String[] args) { context = new AnnotationConfigApplicationContext(AppConfiguration.class); final AccountDAO accountDAO = context.getBean(AccountDAO.class); final TransferService transferService = context.getBean(TransferService.class); final CreditService creditService = context.getBean(CreditService.class); System.out.println("All accounts"); showAllAccounts(accountDAO); System.out.println(); transferService.deposit(150, 1L); System.out.println(getAccountById(1L)); transferService.withdraw(230, 1L); System.out.println(getAccountById(1L)); transferService.transfer(30, 3L, 1L); System.out.println(getAccountById(1L)); System.out.println(getAccountById(3L)); System.out.println("After loan"); creditService.takeCreditLoad(1000d, 1L); System.out.println(getAccountById(1L)); transferService.transfer(105, 1L, 3L); System.out.println(getAccountById(3L)); System.out.println(context.getBeanDefinitionCount()); } private static void showAllAccounts(AccountDAO accountDAO) { accountDAO.findAll().forEach(System.out::println); } private static Optional<Account> getAccountById(long l) { return context.getBean(AccountDAO.class).findById(l); } }
1,859
0.725659
0.704142
58
31.051723
26.783566
87
false
false
0
0
0
0
0
0
0.672414
false
false
11
b152dcf7a2f028d30e98cdd31e23438bbcff7c85
12,111,807,829,490
f739f5f68d0335ff05a704d477bb1cbcb9684ea9
/service/service-edu/src/main/java/com/ron/eduservice/controller/EduVideoController.java
05b8da3ccb13bf83da8ec34a2aab5a1e44992bbd
[]
no_license
ronzz66/guli-parent
https://github.com/ronzz66/guli-parent
b564766404bd6d722252bf988df4a87553376f50
2a0579d0f64e08c4554846bf1f14393edf737cba
refs/heads/master
2023-04-24T02:57:25.104000
2021-03-10T11:23:04
2021-03-10T11:23:14
367,304,573
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ron.eduservice.controller; import com.ron.commonutils.R; import com.ron.eduservice.entity.EduVideo; import com.ron.eduservice.feign.VodClitent; import com.ron.eduservice.service.EduVideoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; /** * <p> * 课程视频 前端控制器 * </p> * * @author testjava * @since 2020-10-14 */ @RestController @RequestMapping("/eduservice/edu-video") //@CrossOrigin //小结模块 public class EduVideoController { @Autowired private EduVideoService eduVideoService; @Autowired//远程调用删除小节视频的service private VodClitent vodClitent; //添加小结 @PostMapping("/addVideo") public R addVideo(@RequestBody EduVideo eduVideo){ eduVideoService.save(eduVideo); return R.ok(); } //根据小结id删除小结 //TODO 后面还要继续删除小结里面的视频 @DeleteMapping("/deleteVideo/{id}") public R deleteVideo(@PathVariable("id") String id){ //查询要删除的小结id EduVideo eduVideo = eduVideoService.getById(id); //获取小结的视频id String sourceId = eduVideo.getVideoSourceId(); if(!StringUtils.isEmpty(sourceId)){ //远程调用实现根据视频id删除视频 vodClitent.removeVideo(sourceId); } //删除小结 eduVideoService.removeById(id); return R.ok(); } //修改小结 @PostMapping("/updateVideo") public R updateVideo(@RequestBody EduVideo eduVideo){ eduVideoService.updateById(eduVideo); return R.ok(); } }
UTF-8
Java
1,730
java
EduVideoController.java
Java
[ { "context": "*;\n\n/**\n * <p>\n * 课程视频 前端控制器\n * </p>\n *\n * @author testjava\n * @since 2020-10-14\n */\n@RestController\n@Request", "end": 423, "score": 0.9992450475692749, "start": 415, "tag": "USERNAME", "value": "testjava" } ]
null
[]
package com.ron.eduservice.controller; import com.ron.commonutils.R; import com.ron.eduservice.entity.EduVideo; import com.ron.eduservice.feign.VodClitent; import com.ron.eduservice.service.EduVideoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; /** * <p> * 课程视频 前端控制器 * </p> * * @author testjava * @since 2020-10-14 */ @RestController @RequestMapping("/eduservice/edu-video") //@CrossOrigin //小结模块 public class EduVideoController { @Autowired private EduVideoService eduVideoService; @Autowired//远程调用删除小节视频的service private VodClitent vodClitent; //添加小结 @PostMapping("/addVideo") public R addVideo(@RequestBody EduVideo eduVideo){ eduVideoService.save(eduVideo); return R.ok(); } //根据小结id删除小结 //TODO 后面还要继续删除小结里面的视频 @DeleteMapping("/deleteVideo/{id}") public R deleteVideo(@PathVariable("id") String id){ //查询要删除的小结id EduVideo eduVideo = eduVideoService.getById(id); //获取小结的视频id String sourceId = eduVideo.getVideoSourceId(); if(!StringUtils.isEmpty(sourceId)){ //远程调用实现根据视频id删除视频 vodClitent.removeVideo(sourceId); } //删除小结 eduVideoService.removeById(id); return R.ok(); } //修改小结 @PostMapping("/updateVideo") public R updateVideo(@RequestBody EduVideo eduVideo){ eduVideoService.updateById(eduVideo); return R.ok(); } }
1,730
0.679537
0.674389
65
22.892307
18.981873
62
false
false
0
0
0
0
0
0
0.292308
false
false
11
2450b759809bbe9228aeefc632de4df033b50e78
12,111,807,826,800
611bb43b13358ecfe30cae38195fa4f264ece4a0
/src/main/java/net/wrightnz/util/TagSubstituterException.java
d6d0b32257068c343f73c92b98e7b09a7d23c38f
[]
no_license
richard-o-wright/simple
https://github.com/richard-o-wright/simple
2d32078bb74a8cfb26414837fc1a5b8ca58960e3
d03eba36952f86490d157db728abcd6f61ac63ed
refs/heads/main
2023-09-01T18:06:12.816000
2021-10-15T00:26:36
2021-10-15T00:26:36
386,215,969
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.wrightnz.util; /** * * @author Richard Wright */ public class TagSubstituterException extends Exception { /** * Creates a new instance of TagSubstituterException * * @param message * @param cause */ public TagSubstituterException(String message, Throwable cause) { super(message, cause); } }
UTF-8
Java
335
java
TagSubstituterException.java
Java
[ { "context": "package net.wrightnz.util;\n\n/**\n *\n * @author Richard Wright\n */\npublic class TagSubstituterException extends ", "end": 60, "score": 0.9997907280921936, "start": 46, "tag": "NAME", "value": "Richard Wright" } ]
null
[]
package net.wrightnz.util; /** * * @author <NAME> */ public class TagSubstituterException extends Exception { /** * Creates a new instance of TagSubstituterException * * @param message * @param cause */ public TagSubstituterException(String message, Throwable cause) { super(message, cause); } }
327
0.686567
0.686567
19
16.631578
20.532927
67
false
false
0
0
0
0
0
0
0.210526
false
false
11
8488e3f2900b9de0b79802efc0fc6c7882caa5fb
13,838,384,669,642
8b36cd13e050ac6c6b419c4080efd3b102574789
/src/main/java/com/company/Servlets/CarSupplierGUIServlet.java
15853046998697a0ae77d8da76b5e47f3e2b576e
[]
no_license
IvanioDaVinchi/Hibernate_JSP
https://github.com/IvanioDaVinchi/Hibernate_JSP
6c3ac65c755ac1800e080134b611aa230d0477d2
2f16c846d9a177c074e01f9c1257834348dd04da
refs/heads/master
2023-06-02T18:16:04.443000
2021-06-16T10:19:00
2021-06-16T10:19:00
370,677,600
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company.Servlets; import com.company.CarSupplierEntity; import com.company.CarsEntity; import com.company.SuppliersEntity; import com.company.dao.CarsDao; import com.company.dao.CarsSupplerDao; import com.company.dao.SuppliersDao; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CarSupplierGUIServlet extends HttpServlet { private static final long serialVersionUID = 1; private CarsSupplerDao carsSupplerDao; private CarsDao carsDao; private SuppliersDao suppliersDao; public void init() { carsSupplerDao = new CarsSupplerDao(); carsDao = new CarsDao(); suppliersDao = new SuppliersDao(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if(request.getParameter("filterKnopkaCars") != null) { String brand = request.getParameter("spisokCars"); System.out.println(brand); List <CarsEntity> listCars = carsDao.GetListCars(); List<CarsEntity> listCarsWithFilters = new ArrayList<CarsEntity>(); List<CarSupplierEntity> listCarsSuppliersWithFilters = new ArrayList<CarSupplierEntity>(); for(int i = 0; i < listCars.size(); i++) // берем все машины по названию { System.out.println(listCars.get(i).getCarBrand()); if(listCars.get(i).getCarBrand().equals(brand)) { listCarsWithFilters.add(listCars.get(i)); } } List <CarSupplierEntity> listCarsSupplier = carsSupplerDao.GetListCarsSupplers(); for(int i = 0; i < listCarsSupplier.size(); i++) // берем все поставки по машинам { for(int j = 0; j < listCarsWithFilters.size(); j++) { System.out.println(listCarsSupplier.get(i).getCarsByIdCar().getId() + " - - - " + listCarsWithFilters.get(j).getId()); if(Integer.valueOf(listCarsSupplier.get(i).getCarsByIdCar().getId()).equals(listCarsWithFilters.get(j).getId())) { System.out.println("yvoyvoy"); listCarsSuppliersWithFilters.add(listCarsSupplier.get(i)); } } } request.setAttribute("listCarsSupplier", listCarsSuppliersWithFilters); RequestDispatcher dispatcher = request.getRequestDispatcher("carsSuppliersGui-list.jsp"); dispatcher.forward(request, response); } if(request.getParameter("filterKnopkaSuppliers") != null) { String supplier = request.getParameter("spisokSuppliers"); System.out.println(supplier); List <SuppliersEntity> listSuppliers = suppliersDao.GetListSuppliers(); List<SuppliersEntity> listSuppliersWithFilters = new ArrayList<SuppliersEntity>(); List<CarSupplierEntity> listCarsSuppliersWithFilters = new ArrayList<CarSupplierEntity>(); for(int i = 0; i < listSuppliers.size(); i++) // берем все машины по названию { if(listSuppliers.get(i).getNameSupplier().equals(supplier)) { listSuppliersWithFilters.add(listSuppliers.get(i)); } } List <CarSupplierEntity> listCarsSupplier = carsSupplerDao.GetListCarsSupplers(); for(int i = 0; i < listCarsSupplier.size(); i++) // берем все поставки по машинам { for(int j = 0; j < listSuppliersWithFilters.size(); j++) { System.out.println(listCarsSupplier.get(i).getSupplierByIdSupplier().getId() + " - - - " + listSuppliersWithFilters.get(j).getId()); if(Integer.valueOf(listCarsSupplier.get(i).getSupplierByIdSupplier().getId()).equals(listSuppliersWithFilters.get(j).getId())) { System.out.println("yvoyvoy"); listCarsSuppliersWithFilters.add(listCarsSupplier.get(i)); } } } request.setAttribute("listCarsSupplier", listCarsSuppliersWithFilters); RequestDispatcher dispatcher = request.getRequestDispatcher("carsSuppliersGui-list.jsp"); dispatcher.forward(request, response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { listCarSupplier(request,response); } catch (SQLException e) { e.printStackTrace(); } } private void listCarSupplier(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ServletException { List <CarSupplierEntity> listCarsSupplier = carsSupplerDao.GetListCarsSupplers(); request.setAttribute("listCarsSupplier", listCarsSupplier); RequestDispatcher dispatcher = request.getRequestDispatcher("carsSuppliersGui-list.jsp"); dispatcher.forward(request, response); } }
UTF-8
Java
5,585
java
CarSupplierGUIServlet.java
Java
[]
null
[]
package com.company.Servlets; import com.company.CarSupplierEntity; import com.company.CarsEntity; import com.company.SuppliersEntity; import com.company.dao.CarsDao; import com.company.dao.CarsSupplerDao; import com.company.dao.SuppliersDao; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CarSupplierGUIServlet extends HttpServlet { private static final long serialVersionUID = 1; private CarsSupplerDao carsSupplerDao; private CarsDao carsDao; private SuppliersDao suppliersDao; public void init() { carsSupplerDao = new CarsSupplerDao(); carsDao = new CarsDao(); suppliersDao = new SuppliersDao(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if(request.getParameter("filterKnopkaCars") != null) { String brand = request.getParameter("spisokCars"); System.out.println(brand); List <CarsEntity> listCars = carsDao.GetListCars(); List<CarsEntity> listCarsWithFilters = new ArrayList<CarsEntity>(); List<CarSupplierEntity> listCarsSuppliersWithFilters = new ArrayList<CarSupplierEntity>(); for(int i = 0; i < listCars.size(); i++) // берем все машины по названию { System.out.println(listCars.get(i).getCarBrand()); if(listCars.get(i).getCarBrand().equals(brand)) { listCarsWithFilters.add(listCars.get(i)); } } List <CarSupplierEntity> listCarsSupplier = carsSupplerDao.GetListCarsSupplers(); for(int i = 0; i < listCarsSupplier.size(); i++) // берем все поставки по машинам { for(int j = 0; j < listCarsWithFilters.size(); j++) { System.out.println(listCarsSupplier.get(i).getCarsByIdCar().getId() + " - - - " + listCarsWithFilters.get(j).getId()); if(Integer.valueOf(listCarsSupplier.get(i).getCarsByIdCar().getId()).equals(listCarsWithFilters.get(j).getId())) { System.out.println("yvoyvoy"); listCarsSuppliersWithFilters.add(listCarsSupplier.get(i)); } } } request.setAttribute("listCarsSupplier", listCarsSuppliersWithFilters); RequestDispatcher dispatcher = request.getRequestDispatcher("carsSuppliersGui-list.jsp"); dispatcher.forward(request, response); } if(request.getParameter("filterKnopkaSuppliers") != null) { String supplier = request.getParameter("spisokSuppliers"); System.out.println(supplier); List <SuppliersEntity> listSuppliers = suppliersDao.GetListSuppliers(); List<SuppliersEntity> listSuppliersWithFilters = new ArrayList<SuppliersEntity>(); List<CarSupplierEntity> listCarsSuppliersWithFilters = new ArrayList<CarSupplierEntity>(); for(int i = 0; i < listSuppliers.size(); i++) // берем все машины по названию { if(listSuppliers.get(i).getNameSupplier().equals(supplier)) { listSuppliersWithFilters.add(listSuppliers.get(i)); } } List <CarSupplierEntity> listCarsSupplier = carsSupplerDao.GetListCarsSupplers(); for(int i = 0; i < listCarsSupplier.size(); i++) // берем все поставки по машинам { for(int j = 0; j < listSuppliersWithFilters.size(); j++) { System.out.println(listCarsSupplier.get(i).getSupplierByIdSupplier().getId() + " - - - " + listSuppliersWithFilters.get(j).getId()); if(Integer.valueOf(listCarsSupplier.get(i).getSupplierByIdSupplier().getId()).equals(listSuppliersWithFilters.get(j).getId())) { System.out.println("yvoyvoy"); listCarsSuppliersWithFilters.add(listCarsSupplier.get(i)); } } } request.setAttribute("listCarsSupplier", listCarsSuppliersWithFilters); RequestDispatcher dispatcher = request.getRequestDispatcher("carsSuppliersGui-list.jsp"); dispatcher.forward(request, response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { listCarSupplier(request,response); } catch (SQLException e) { e.printStackTrace(); } } private void listCarSupplier(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException, ServletException { List <CarSupplierEntity> listCarsSupplier = carsSupplerDao.GetListCarsSupplers(); request.setAttribute("listCarsSupplier", listCarsSupplier); RequestDispatcher dispatcher = request.getRequestDispatcher("carsSuppliersGui-list.jsp"); dispatcher.forward(request, response); } }
5,585
0.636231
0.634955
118
45.5
37.101498
152
false
false
0
0
0
0
0
0
0.70339
false
false
11
760f800cf6f104c8cc161200a39064579c640b3e
26,792,006,025,612
956a2ae7ec8da13678c343bcbec84c491bf47c5d
/src/lection4/PhysicKnowledge.java
704103b173bdc34c4bfa4bb7f5189cd0e485e95b
[]
no_license
order12a/InfopulseJavaSecond
https://github.com/order12a/InfopulseJavaSecond
e1983dba9c103382e3677347add339aa558644c5
3f79f8a8b17f9d16e67d8e927ce764d2bb2da272
refs/heads/master
2021-01-10T05:58:04.872000
2016-01-20T19:02:35
2016-01-20T19:02:35
44,688,225
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lection4; import java.util.Arrays; /** * Created by order on 04.11.15. */ public class PhysicKnowledge { private String [] physicKnowledge = {"Mechanic", "Hydraulic", "Thermophysic", "Optic"}; public void setPhysicKnowledge(String[] physicKnowledge) { this.physicKnowledge = physicKnowledge; } public String[] getPhysicKnowledge() { return physicKnowledge; } @Override public int hashCode() { return getPhysicKnowledge() != null ? Arrays.hashCode(getPhysicKnowledge()) : 0; } public PhysicKnowledge(PhysicKnowledge otherPhysicKnowledge){ this.setPhysicKnowledge(otherPhysicKnowledge.getPhysicKnowledge()); } public PhysicKnowledge(){ } }
UTF-8
Java
739
java
PhysicKnowledge.java
Java
[ { "context": "ion4;\n\nimport java.util.Arrays;\n\n/**\n * Created by order on 04.11.15.\n */\npublic class PhysicKnowledge {\n\n", "end": 68, "score": 0.9955801963806152, "start": 63, "tag": "USERNAME", "value": "order" } ]
null
[]
package lection4; import java.util.Arrays; /** * Created by order on 04.11.15. */ public class PhysicKnowledge { private String [] physicKnowledge = {"Mechanic", "Hydraulic", "Thermophysic", "Optic"}; public void setPhysicKnowledge(String[] physicKnowledge) { this.physicKnowledge = physicKnowledge; } public String[] getPhysicKnowledge() { return physicKnowledge; } @Override public int hashCode() { return getPhysicKnowledge() != null ? Arrays.hashCode(getPhysicKnowledge()) : 0; } public PhysicKnowledge(PhysicKnowledge otherPhysicKnowledge){ this.setPhysicKnowledge(otherPhysicKnowledge.getPhysicKnowledge()); } public PhysicKnowledge(){ } }
739
0.679296
0.668471
34
20.735294
26.956728
91
false
false
0
0
0
0
0
0
0.294118
false
false
11
2ab3fdde5737c64e70caa1a8e01319adfebb9342
4,587,025,106,374
a480865f0d157f0d7ad87aa03d298e522c876c4e
/samples/springboot-jersey-server/src/main/java/org/pomegranate/demo/service/impl/ContactEntryServiceImpl.java
9e554a9d5ed5f1ed09dbe136d06123d6cffb15d2
[]
no_license
intuitors/pomegranate
https://github.com/intuitors/pomegranate
efa28a3f2c752be14a763f9c83cc303c269c695e
a4d89e4b99d908bc701fe511370fc1e9e2179d69
refs/heads/master
2021-01-13T11:52:43.866000
2017-02-20T12:13:24
2017-02-20T12:13:24
81,700,009
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.pomegranate.demo.service.impl; import org.pomegranate.demo.dal.dao.ContactDao; import org.pomegranate.demo.dal.entity.Contact; import org.pomegranate.demo.dal.entity.Phone; import org.pomegranate.demo.service.ContactEntryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author sylenthira */ @Service public class ContactEntryServiceImpl implements ContactEntryService { @Autowired private ContactDao contactDao; @Override public List<Contact> getContacts() { return contactDao.getContacts(); } @Override public List<Contact> getContacts(int start, int size) { return contactDao.getContacts(start, size); } @Override public Contact getContactById(int id) { return contactDao.getContactById(id); } @Override public Contact getContactByPhoneNo(String phoneNo) { return contactDao.getContactByPhoneNo(phoneNo); } @Override public Contact addContact(Contact contact) { return contactDao.addContact(contact); } @Override public void updateContact(int id, Contact contact) { contactDao.updateContact(id, contact); } @Override public void deleteContact(int id) { contactDao.deleteContact(getContactById(id)); } @Override public List<Phone> getPhones(int contactId) { return contactDao.getPhonesByContactId(contactId); } @Override public Phone getPhoneByContactIdPhoneId(int contactId, int phoneId) { return contactDao.getPhoneByContactIdPhoneId(contactId, phoneId); } @Override public Phone addPhone(int contactId, Phone phone) { return contactDao.addPhone(contactId, phone); } @Override public void updatePhone(int contactId, int phoneId, Phone phone) { contactDao.updatePhone(contactId, phoneId, phone); } @Override public void deletePhone(int contactId, int phoneId) { contactDao.deletePhone(contactId, getPhoneByContactIdPhoneId(contactId, phoneId)); } }
UTF-8
Java
2,131
java
ContactEntryServiceImpl.java
Java
[ { "context": "e.Service;\n\nimport java.util.List;\n\n/**\n * @author sylenthira\n */\n@Service\npublic class ContactEntryServiceImpl", "end": 404, "score": 0.9960764050483704, "start": 394, "tag": "USERNAME", "value": "sylenthira" } ]
null
[]
package org.pomegranate.demo.service.impl; import org.pomegranate.demo.dal.dao.ContactDao; import org.pomegranate.demo.dal.entity.Contact; import org.pomegranate.demo.dal.entity.Phone; import org.pomegranate.demo.service.ContactEntryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author sylenthira */ @Service public class ContactEntryServiceImpl implements ContactEntryService { @Autowired private ContactDao contactDao; @Override public List<Contact> getContacts() { return contactDao.getContacts(); } @Override public List<Contact> getContacts(int start, int size) { return contactDao.getContacts(start, size); } @Override public Contact getContactById(int id) { return contactDao.getContactById(id); } @Override public Contact getContactByPhoneNo(String phoneNo) { return contactDao.getContactByPhoneNo(phoneNo); } @Override public Contact addContact(Contact contact) { return contactDao.addContact(contact); } @Override public void updateContact(int id, Contact contact) { contactDao.updateContact(id, contact); } @Override public void deleteContact(int id) { contactDao.deleteContact(getContactById(id)); } @Override public List<Phone> getPhones(int contactId) { return contactDao.getPhonesByContactId(contactId); } @Override public Phone getPhoneByContactIdPhoneId(int contactId, int phoneId) { return contactDao.getPhoneByContactIdPhoneId(contactId, phoneId); } @Override public Phone addPhone(int contactId, Phone phone) { return contactDao.addPhone(contactId, phone); } @Override public void updatePhone(int contactId, int phoneId, Phone phone) { contactDao.updatePhone(contactId, phoneId, phone); } @Override public void deletePhone(int contactId, int phoneId) { contactDao.deletePhone(contactId, getPhoneByContactIdPhoneId(contactId, phoneId)); } }
2,131
0.712811
0.712811
82
24.987804
24.875542
90
false
false
0
0
0
0
0
0
0.439024
false
false
11
1016606545ec970a21e7b70d0135a8a97133ecbb
17,523,466,605,995
661fb5bc8f5b143e910917ea2e2fee18f53b2a55
/src/main/java/com/bill/common/metric/DefaultTagTemplate.java
95f2819e120178d703f8f7c47bff1c913eb3c7b4
[]
no_license
fengkidding/bill
https://github.com/fengkidding/bill
9a262d5b2281446263a9056a1affd97bc3b020ac
2513a9db4e3c9a118c3a77502f544422a2153f05
refs/heads/master
2023-04-27T13:13:02.776000
2023-04-23T10:45:00
2023-04-23T10:45:00
218,077,044
0
1
null
false
2022-10-05T18:20:57
2019-10-28T15:18:03
2021-03-24T12:01:05
2022-10-05T18:20:57
352
0
1
5
Java
false
false
package com.bill.common.metric; import java.lang.reflect.Method; /** * aspect中获取tags的方法,默认实现 */ public class DefaultTagTemplate extends BaseTagTemplate { /** * 构建tags * * @param method * @return */ @Override public String buildTags(Method method) { return method.getName(); } }
UTF-8
Java
358
java
DefaultTagTemplate.java
Java
[]
null
[]
package com.bill.common.metric; import java.lang.reflect.Method; /** * aspect中获取tags的方法,默认实现 */ public class DefaultTagTemplate extends BaseTagTemplate { /** * 构建tags * * @param method * @return */ @Override public String buildTags(Method method) { return method.getName(); } }
358
0.623494
0.623494
20
15.6
15.834772
57
false
false
0
0
0
0
0
0
0.15
false
false
11
eb0921934976d2bfd9b29e5bd3164039d8e2d49d
9,723,805,994,759
7b6dd44e6b70bac0ab7fd8fc37b801a19ab53d44
/app/src/main/java/com/example/andres/proyectomvp/UserSessionManager.java
100e1229e52cf4030118180374b6272623986467
[]
no_license
Andres1591/sharePrefenrec
https://github.com/Andres1591/sharePrefenrec
1ed2c31a8b38b10aa63ff4ac255e04f1c6e47853
74895d31ebc8aca31f6f544739d764a3a6c0bc75
refs/heads/master
2021-04-09T10:42:47.040000
2018-03-16T00:08:21
2018-03-16T00:08:21
125,439,890
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.andres.proyectomvp; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import java.util.HashMap; /** * Created by andres on 14-Mar-18. */ public class UserSessionManager { SharedPreferences preferences; Editor editor; Context _context; int PRIVATE_MODE = 0; private static final String PREFER_NAME ="AndroidExamplePref"; private static final String IS_USER_LOGIN = "IsUserLoggedIn"; public static final String KEY_NAME = "name"; public static final String KEY_EMAIL = "email"; public UserSessionManager(Context context){ this._context = context; preferences = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE); editor = preferences.edit(); } public void createUserLoginSession(String name, String email){ editor.putBoolean(IS_USER_LOGIN, true); editor.putString(KEY_NAME, name); editor.putString(KEY_EMAIL, email); editor.commit(); } public boolean checkLogin(){ // Check login status if(!this.isUserLoggedIn()){ Intent i = new Intent(_context, LoginActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); _context.startActivity(i); return true; } return false; } public HashMap<String, String> getUserDetails(){ HashMap<String, String> user = new HashMap<String, String>(); user.put(KEY_NAME, preferences.getString(KEY_NAME, null)); user.put(KEY_EMAIL, preferences.getString(KEY_EMAIL, null)); return user; } public void logoutUser(){ editor.clear(); editor.commit(); Intent i = new Intent(_context, LoginActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); _context.startActivity(i); } public boolean isUserLoggedIn(){ return preferences.getBoolean(IS_USER_LOGIN, false); } }
UTF-8
Java
2,148
java
UserSessionManager.java
Java
[ { "context": "tor;\n\nimport java.util.HashMap;\n\n/**\n * Created by andres on 14-Mar-18.\n */\n\npublic class UserSessionManage", "end": 247, "score": 0.9206562042236328, "start": 241, "tag": "USERNAME", "value": "andres" }, { "context": "\";\n public static final String KEY_NAME = \"name\";\n public static final String KEY_EMAIL = \"ema", "end": 593, "score": 0.5185505747795105, "start": 589, "tag": "KEY", "value": "name" }, { "context": "ame\";\n public static final String KEY_EMAIL = \"email\";\n\n public UserSessionManager(Context context)", "end": 645, "score": 0.6560865640640259, "start": 640, "tag": "KEY", "value": "email" } ]
null
[]
package com.example.andres.proyectomvp; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import java.util.HashMap; /** * Created by andres on 14-Mar-18. */ public class UserSessionManager { SharedPreferences preferences; Editor editor; Context _context; int PRIVATE_MODE = 0; private static final String PREFER_NAME ="AndroidExamplePref"; private static final String IS_USER_LOGIN = "IsUserLoggedIn"; public static final String KEY_NAME = "name"; public static final String KEY_EMAIL = "email"; public UserSessionManager(Context context){ this._context = context; preferences = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE); editor = preferences.edit(); } public void createUserLoginSession(String name, String email){ editor.putBoolean(IS_USER_LOGIN, true); editor.putString(KEY_NAME, name); editor.putString(KEY_EMAIL, email); editor.commit(); } public boolean checkLogin(){ // Check login status if(!this.isUserLoggedIn()){ Intent i = new Intent(_context, LoginActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); _context.startActivity(i); return true; } return false; } public HashMap<String, String> getUserDetails(){ HashMap<String, String> user = new HashMap<String, String>(); user.put(KEY_NAME, preferences.getString(KEY_NAME, null)); user.put(KEY_EMAIL, preferences.getString(KEY_EMAIL, null)); return user; } public void logoutUser(){ editor.clear(); editor.commit(); Intent i = new Intent(_context, LoginActivity.class); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); _context.startActivity(i); } public boolean isUserLoggedIn(){ return preferences.getBoolean(IS_USER_LOGIN, false); } }
2,148
0.655493
0.653166
70
29.685715
23.005306
79
false
false
0
0
0
0
0
0
0.757143
false
false
11
172affa044e93c37150b5b79239b43b5b50f383e
24,567,212,966,089
19911f7caf438a71ad66ab55b3e93c3c970606b9
/celutils/celutils/beans/property/Binding.java
08c7194903021a1d98c9b1b6a80c7503134a6dd5
[]
no_license
maxd0328/CelUtils
https://github.com/maxd0328/CelUtils
d072889f6969a7dddcb91b1e903051dde5223677
e99543fbf540a90b39e9ad17971b4bb748655073
refs/heads/master
2022-07-30T14:32:33.390000
2020-05-18T19:35:14
2020-05-18T19:35:14
265,041,772
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package celutils.beans.property; /** * A package-level class that represents a binding between * two properties. * <p> * It manages the binding of these two properties and ensures * that their values are always the same at all times. This * is done through a regular binding update. * * @param <T> The property type of the two bound properties. * * @author Max D */ public final class Binding<T> implements java.io.Serializable { private static final long serialVersionUID = -3727508078202590800L; /** * The previous values of each bound property. Used for detecting value changes. */ private T rootOld; private T guestOld; /** * Both bound properties. The root property is the one that owns the property * binding. See <a href="#{@link}">{@link Property#bind(Property, BindingOrder)}</a>. * The guest property is the alternate property that has been attached to the * binding. */ private final Property<T> root; private final Property<T> guest; /** * The binding order for this binding. It defines which properties take precedence * in the binding. */ private final BindingOrder order; /** * Package-level constructor. * <p> * Creates a new binding given the root property, guest property, and its associated * binding order. * * @param root The root property to attach to this binding. * @param guest The guest property to attach to this binding. * @param order The binding order to associate with this binding. */ Binding(Property<T> root, Property<T> guest, BindingOrder order) { if(order == null) throw new NullPointerException("order"); this.root = root; this.guest = guest; this.order = order; sync(); rootOld = root.get(); guestOld = guest.get(); } /** * Returns the root property of this binding. The root property is typically the * property that owns this binding. * * @return The root property of this binding. */ public Property<T> getRoot() { return root; } /** * Returns the guest property of this binding. The guest property is typically the * disconnected property that is bound to the root property. * * @return The guest property of this binding. */ public Property<T> getGuest() { return guest; } /** * Returns the binding order associated with this binding. * * @return The binding order associated with this binding. */ public BindingOrder getOrder() { return order; } /** * Updates this binding. * <p> * During a binding update, changes in both properties are determined * and if any changes have occurred, then both bindings are set to be equal * with a precedence determined by the binding order. If no changes have * occurred, then a property synchronization occurs. During property * synchronization, if the properties are not equal, then the property * without precedence according to the binding order is set to the value * of the property with precedence. */ public void update() { T rootNew = root.get(); T guestNew = guest.get(); switch(order) { case BIDIRECTIONAL_DOMINANT: if(!root.equals(rootOld, rootNew) && !root.equals(guestNew, rootNew)) { guest.set(rootNew); guestNew = rootNew; } else if(!root.equals(guestOld, guestNew) && !root.equals(guestNew, rootNew)) { root.set(guestNew); rootNew = guestNew; } break; case BIDIRECTIONAL_RECESSIVE: if(!root.equals(guestOld, guestNew) && !root.equals(guestNew, rootNew)) { root.set(guestNew); rootNew = guestNew; } else if(!root.equals(rootOld, rootNew) && !root.equals(guestNew, rootNew)) { guest.set(rootNew); guestNew = rootNew; } break; case DOMINANT: case RECESSIVE: default: break; } sync(); rootOld = rootNew; guestOld = guestNew; } /** * This method performs property synchronization. * <p> * During synchronization, the property without precedence according to the * binding order is set to the value of the property with precedence if they * are not already equal. */ private void sync() { if(root.equals(root.get(), guest.get())) return; if(order == BindingOrder.DOMINANT || order == BindingOrder.BIDIRECTIONAL_DOMINANT) { guest.set(root.get()); } else { root.set(guest.get()); } } }
UTF-8
Java
4,428
java
Binding.java
Java
[ { "context": "type of the two bound properties.\r\n * \r\n * @author Max D\r\n */\r\npublic final class Binding<T> implements java", "end": 387, "score": 0.8913908004760742, "start": 382, "tag": "NAME", "value": "Max D" } ]
null
[]
package celutils.beans.property; /** * A package-level class that represents a binding between * two properties. * <p> * It manages the binding of these two properties and ensures * that their values are always the same at all times. This * is done through a regular binding update. * * @param <T> The property type of the two bound properties. * * @author <NAME> */ public final class Binding<T> implements java.io.Serializable { private static final long serialVersionUID = -3727508078202590800L; /** * The previous values of each bound property. Used for detecting value changes. */ private T rootOld; private T guestOld; /** * Both bound properties. The root property is the one that owns the property * binding. See <a href="#{@link}">{@link Property#bind(Property, BindingOrder)}</a>. * The guest property is the alternate property that has been attached to the * binding. */ private final Property<T> root; private final Property<T> guest; /** * The binding order for this binding. It defines which properties take precedence * in the binding. */ private final BindingOrder order; /** * Package-level constructor. * <p> * Creates a new binding given the root property, guest property, and its associated * binding order. * * @param root The root property to attach to this binding. * @param guest The guest property to attach to this binding. * @param order The binding order to associate with this binding. */ Binding(Property<T> root, Property<T> guest, BindingOrder order) { if(order == null) throw new NullPointerException("order"); this.root = root; this.guest = guest; this.order = order; sync(); rootOld = root.get(); guestOld = guest.get(); } /** * Returns the root property of this binding. The root property is typically the * property that owns this binding. * * @return The root property of this binding. */ public Property<T> getRoot() { return root; } /** * Returns the guest property of this binding. The guest property is typically the * disconnected property that is bound to the root property. * * @return The guest property of this binding. */ public Property<T> getGuest() { return guest; } /** * Returns the binding order associated with this binding. * * @return The binding order associated with this binding. */ public BindingOrder getOrder() { return order; } /** * Updates this binding. * <p> * During a binding update, changes in both properties are determined * and if any changes have occurred, then both bindings are set to be equal * with a precedence determined by the binding order. If no changes have * occurred, then a property synchronization occurs. During property * synchronization, if the properties are not equal, then the property * without precedence according to the binding order is set to the value * of the property with precedence. */ public void update() { T rootNew = root.get(); T guestNew = guest.get(); switch(order) { case BIDIRECTIONAL_DOMINANT: if(!root.equals(rootOld, rootNew) && !root.equals(guestNew, rootNew)) { guest.set(rootNew); guestNew = rootNew; } else if(!root.equals(guestOld, guestNew) && !root.equals(guestNew, rootNew)) { root.set(guestNew); rootNew = guestNew; } break; case BIDIRECTIONAL_RECESSIVE: if(!root.equals(guestOld, guestNew) && !root.equals(guestNew, rootNew)) { root.set(guestNew); rootNew = guestNew; } else if(!root.equals(rootOld, rootNew) && !root.equals(guestNew, rootNew)) { guest.set(rootNew); guestNew = rootNew; } break; case DOMINANT: case RECESSIVE: default: break; } sync(); rootOld = rootNew; guestOld = guestNew; } /** * This method performs property synchronization. * <p> * During synchronization, the property without precedence according to the * binding order is set to the value of the property with precedence if they * are not already equal. */ private void sync() { if(root.equals(root.get(), guest.get())) return; if(order == BindingOrder.DOMINANT || order == BindingOrder.BIDIRECTIONAL_DOMINANT) { guest.set(root.get()); } else { root.set(guest.get()); } } }
4,429
0.666215
0.661924
154
26.753246
27.019548
86
false
false
0
0
0
0
0
0
1.837662
false
false
11
948420e902b671b583ae96cdd59bcd554a78971a
29,961,691,898,814
dbf44fc282aee9b3c5c8b2a2bd13d1ec26d2e688
/Servidores/MacDonnal/src/java/Controlador/Controlador.java
05d576ee11e8fc804cc11833fab82dda57d65aeb
[]
no_license
vlooy17/2DAW
https://github.com/vlooy17/2DAW
6fc82fafbdbcb0b7d72539022a5e5596c98b5041
8e327768749fd72b8eb8cfb5579e1677c07e7d9a
refs/heads/master
2021-10-22T05:16:03.013000
2019-03-08T10:04:28
2019-03-08T10:04:28
159,320,038
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 Controlador; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author alumno_2DAW */ public class Controlador extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String usuario = request.getParameter("usuario"); String clave = request.getParameter("clave"); HttpSession sesion = request.getSession(); sesion.setAttribute("usuario", usuario); sesion.setAttribute("clave", clave); ServletContext contexto = getServletContext(); RequestDispatcher rd; out.print(usuario); out.print(clave); ArrayList<Usuario> lista; lista = BaseDatos.Base.consultaTitulos(); String usuario1 = lista.get(0).getUsuario(); String clave1 = lista.get(0).getClave(); String nombre = lista.get(0).getNombre(); sesion.setAttribute("nombre", nombre); if(usuario.equals(usuario1)&& clave.equals(clave1)){ rd = contexto.getRequestDispatcher("/pedido.jsp"); rd.forward(request, response); }else{ rd = contexto.getRequestDispatcher("/index.html"); rd.forward(request, response); } } }
UTF-8
Java
1,918
java
Controlador.java
Java
[ { "context": "javax.servlet.http.HttpSession;\n\n/**\n *\n * @author alumno_2DAW\n */\npublic class Controlador extends HttpServlet ", "end": 608, "score": 0.999566376209259, "start": 597, "tag": "USERNAME", "value": "alumno_2DAW" } ]
null
[]
/* * 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 Controlador; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author alumno_2DAW */ public class Controlador extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String usuario = request.getParameter("usuario"); String clave = request.getParameter("clave"); HttpSession sesion = request.getSession(); sesion.setAttribute("usuario", usuario); sesion.setAttribute("clave", clave); ServletContext contexto = getServletContext(); RequestDispatcher rd; out.print(usuario); out.print(clave); ArrayList<Usuario> lista; lista = BaseDatos.Base.consultaTitulos(); String usuario1 = lista.get(0).getUsuario(); String clave1 = lista.get(0).getClave(); String nombre = lista.get(0).getNombre(); sesion.setAttribute("nombre", nombre); if(usuario.equals(usuario1)&& clave.equals(clave1)){ rd = contexto.getRequestDispatcher("/pedido.jsp"); rd.forward(request, response); }else{ rd = contexto.getRequestDispatcher("/index.html"); rd.forward(request, response); } } }
1,918
0.662669
0.658498
61
30.442623
21.8741
83
false
false
0
0
0
0
0
0
0.672131
false
false
11
e697f5ae976a5a0b86a269b256bca2859a3fdc28
26,826,365,783,321
f3abd9d9da8c2300b9b5751f308c517694c615ce
/simple-orm/src/wangzx/orm/annotations/Param.java
2bba76c505801418464098a2273e0ece82fbef1c
[]
no_license
wangzaixiang/wangzaixiang
https://github.com/wangzaixiang/wangzaixiang
9a5f0e3e33a702e87c24acdccfd075a7938ebdd5
9b25ac318b40440e61cb71664cb5f32de191ad4f
refs/heads/master
2021-01-13T02:37:09.333000
2010-11-09T16:33:11
2010-11-09T16:33:11
41,010,367
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package wangzx.orm.annotations; public @interface Param { String value(); }
UTF-8
Java
83
java
Param.java
Java
[]
null
[]
package wangzx.orm.annotations; public @interface Param { String value(); }
83
0.698795
0.698795
5
14.6
12.467558
31
false
false
0
0
0
0
0
0
0.6
false
false
11
f7f5f188a0225f7a309a1f3c6e70d0f4a8b64485
33,148,557,655,935
742930b7fc150528651d0666f7fdafc6b3eeeba6
/practica2/src/tp/pr2/command/Exit.java
936e9c8c09a444c839f0b0b8695b474494e2e9a5
[]
no_license
martapastor/TP-Game-of-Life
https://github.com/martapastor/TP-Game-of-Life
7a43f3b182ad3351097d4d850d209922d5c3e450
1b0c12ec464b4f691d11fecce1b154a0cc1d13d9
refs/heads/master
2020-04-01T19:34:51.581000
2016-10-17T15:49:08
2016-10-17T15:49:08
55,054,639
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tp.pr2.command; import tp.pr2.logic.World; public class Exit extends Command { public void execute(World world){ world.setSimulationFinished(); } public Command parse(String[] commandString){ Command exit = new Exit(); if (commandString.length != 1){ return null; } else { if (commandString[0].equals("exit")){ return exit; } } return null; } public String helpText(){ String ayuda =(" EXIT: exit the game." + System.getProperty("line.separator")); return ayuda; } }
UTF-8
Java
521
java
Exit.java
Java
[]
null
[]
package tp.pr2.command; import tp.pr2.logic.World; public class Exit extends Command { public void execute(World world){ world.setSimulationFinished(); } public Command parse(String[] commandString){ Command exit = new Exit(); if (commandString.length != 1){ return null; } else { if (commandString[0].equals("exit")){ return exit; } } return null; } public String helpText(){ String ayuda =(" EXIT: exit the game." + System.getProperty("line.separator")); return ayuda; } }
521
0.664108
0.65643
26
19.038462
19.073706
82
false
false
0
0
0
0
0
0
1.769231
false
false
11
75bee055379e63f57b25eb0b71bc688f10d533f9
20,031,727,524,627
f727c689c6916cb5d5b7bf986eec3bc1bf0543cd
/src/Accepted/RestoreIPAddress.java
6253ee073ae083f5a82753a9870e5178b58252ff
[]
no_license
lizhieffe/LC150Round2
https://github.com/lizhieffe/LC150Round2
375a3e3f3a637bfdac7fe4babf337cb12b983bcb
07dd4de65291637b96015412978d00bcde139cb4
refs/heads/master
2020-12-04T08:16:13.494000
2015-01-20T14:18:34
2015-01-20T14:18:34
25,339,447
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Accepted; import java.util.ArrayList; import java.util.List; public class RestoreIPAddress { public List<String> restoreIpAddresses(String s) { List<String> result = new ArrayList<String>(); if (s == null || s.length() < 4 || s.length() > 12) return result; List<String> solution = new ArrayList<String>(); restore(s, 0, solution, result); return result; } private void restore(String s, int beg, List<String> solution, List<String> result) { if (solution.size() == 4 && beg == s.length()) { String tmp = solution.get(0) + '.' + solution.get(1) + '.' + solution.get(2) + '.' + solution.get(3); result.add(tmp); return; } if (solution.size() == 4 || beg >= s.length()) return; for (int i = beg; i < beg + Math.min(3, s.length() - beg); i++) { String tmpString = s.substring(beg, i + 1); if ((Integer.parseInt(tmpString) <= 255) && (i == beg || tmpString.charAt(0) != '0')) { List<String> tmpSolution = new ArrayList<String>(solution); tmpSolution.add(tmpString); restore(s, i + 1, tmpSolution, result); } } } public static void main(String[] args) { String s = "010010"; new RestoreIPAddress().restoreIpAddresses(s); } }
UTF-8
Java
1,396
java
RestoreIPAddress.java
Java
[]
null
[]
package Accepted; import java.util.ArrayList; import java.util.List; public class RestoreIPAddress { public List<String> restoreIpAddresses(String s) { List<String> result = new ArrayList<String>(); if (s == null || s.length() < 4 || s.length() > 12) return result; List<String> solution = new ArrayList<String>(); restore(s, 0, solution, result); return result; } private void restore(String s, int beg, List<String> solution, List<String> result) { if (solution.size() == 4 && beg == s.length()) { String tmp = solution.get(0) + '.' + solution.get(1) + '.' + solution.get(2) + '.' + solution.get(3); result.add(tmp); return; } if (solution.size() == 4 || beg >= s.length()) return; for (int i = beg; i < beg + Math.min(3, s.length() - beg); i++) { String tmpString = s.substring(beg, i + 1); if ((Integer.parseInt(tmpString) <= 255) && (i == beg || tmpString.charAt(0) != '0')) { List<String> tmpSolution = new ArrayList<String>(solution); tmpSolution.add(tmpString); restore(s, i + 1, tmpSolution, result); } } } public static void main(String[] args) { String s = "010010"; new RestoreIPAddress().restoreIpAddresses(s); } }
1,396
0.538682
0.52149
39
34.794872
28.88632
113
false
false
0
0
0
0
0
0
1.076923
false
false
5
ba5baad07c18293367d688b14f29d65fe5ff53e2
33,191,507,309,536
0c3cd97b40fe42fcbe2928747541cd279f215319
/Intro.java
168db7053df910658e53b495ca7e98008b90d2c8
[ "MIT" ]
permissive
abhatia25/AP-Computer-Science
https://github.com/abhatia25/AP-Computer-Science
96199ad65ed01f5d35628726be868c140c943c8b
8c98dc781eaccf431af534af219caac868a8c121
refs/heads/master
2021-06-24T00:56:41.279000
2021-03-06T20:51:03
2021-03-06T20:51:03
206,326,506
0
0
MIT
false
2021-03-06T20:39:12
2019-09-04T13:31:17
2019-12-19T03:53:38
2021-03-06T20:39:12
31,280
0
0
0
Java
false
false
import java.io.*; class Intro { public static void main(String args[]) { //Assignment 1 for(int i = 0; i <= 5; i++){ System.out.println("*****"); } //Assignment 2 int int1 = 10; int int2 = 10; float float1 = 12.5f; String string1 = "Java programming"; System.out.println(int1); System.out.println(int2); System.out.println(float1); System.out.println(string1); //Assignment 3 br(); } static void br() { try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter your name: "); String name = reader.readLine(); System.out.println("Hello " + name + "!"); } catch (IOException ioe) { } } }
UTF-8
Java
871
java
Intro.java
Java
[]
null
[]
import java.io.*; class Intro { public static void main(String args[]) { //Assignment 1 for(int i = 0; i <= 5; i++){ System.out.println("*****"); } //Assignment 2 int int1 = 10; int int2 = 10; float float1 = 12.5f; String string1 = "Java programming"; System.out.println(int1); System.out.println(int2); System.out.println(float1); System.out.println(string1); //Assignment 3 br(); } static void br() { try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter your name: "); String name = reader.readLine(); System.out.println("Hello " + name + "!"); } catch (IOException ioe) { } } }
871
0.499426
0.476464
37
21.594595
17.846886
86
false
false
0
0
0
0
0
0
0.459459
false
false
5
50cb616a8f30ac5bfd5a3c1b686e2f8604bae1ab
15,324,443,348,461
a63bf07e2bb26ae62e4b150f7f0bff472e7e83b0
/src/main/java/org/vanautrui/languages/compiler/vmcodegenerator/specialized/WhileStatementDracoVMCodeGenerator.java
b60e49700338028234ebb01e06e504fe26714929
[ "MIT" ]
permissive
pointbazaar/dragon
https://github.com/pointbazaar/dragon
e304b0066e697f58e6cbdba2c207a689134604dd
767ed7f76ea45eaca21ff7e641a57c2ce8b6104c
refs/heads/master
2020-04-04T22:10:12.045000
2020-03-28T22:20:16
2020-03-28T22:20:16
156,312,746
15
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.vanautrui.languages.compiler.vmcodegenerator.specialized; import org.vanautrui.languages.compiler.parsing.astnodes.nonterminal.statements.StatementNode; import org.vanautrui.languages.compiler.parsing.astnodes.nonterminal.statements.controlflow.WhileStatementNode; import org.vanautrui.languages.compiler.parsing.astnodes.nonterminal.upperscopes.MethodNode; import org.vanautrui.languages.compiler.symboltables.util.SymbolTableContext; import java.util.ArrayList; import java.util.List; import static org.vanautrui.languages.compiler.vmcodegenerator.DracoVMCodeGenerator.unique; import static org.vanautrui.languages.compiler.vmcodegenerator.specialized.ExpressionDracoVMCodeGenerator.genDracoVMCodeForExpression; import static org.vanautrui.languages.compiler.vmcodegenerator.specialized.StatementDracoVMCodeGenerator.generateDracoVMCodeForStatement; public final class WhileStatementDracoVMCodeGenerator { public static List<String> genVMCodeForWhileStatement( final WhileStatementNode whileStmt, final MethodNode containerMethod, final SymbolTableContext ctx ) throws Exception { final List<String> vm = new ArrayList<>(); final long unique = unique(); final String startlabel = "whilestart" + unique; final String endlabel = "whileend" + unique; vm.add("label "+startlabel); //push the expression vm.addAll(genDracoVMCodeForExpression(whileStmt.condition, ctx)); //+1 vm.add("not"); //if condition is false, jump to end vm.add("if-goto "+endlabel); //execute statements for (StatementNode stmt : whileStmt.statements) { vm.addAll(generateDracoVMCodeForStatement(stmt, containerMethod, ctx)); } vm.add("goto "+startlabel); vm.add("label "+endlabel); return vm; } }
UTF-8
Java
1,882
java
WhileStatementDracoVMCodeGenerator.java
Java
[]
null
[]
package org.vanautrui.languages.compiler.vmcodegenerator.specialized; import org.vanautrui.languages.compiler.parsing.astnodes.nonterminal.statements.StatementNode; import org.vanautrui.languages.compiler.parsing.astnodes.nonterminal.statements.controlflow.WhileStatementNode; import org.vanautrui.languages.compiler.parsing.astnodes.nonterminal.upperscopes.MethodNode; import org.vanautrui.languages.compiler.symboltables.util.SymbolTableContext; import java.util.ArrayList; import java.util.List; import static org.vanautrui.languages.compiler.vmcodegenerator.DracoVMCodeGenerator.unique; import static org.vanautrui.languages.compiler.vmcodegenerator.specialized.ExpressionDracoVMCodeGenerator.genDracoVMCodeForExpression; import static org.vanautrui.languages.compiler.vmcodegenerator.specialized.StatementDracoVMCodeGenerator.generateDracoVMCodeForStatement; public final class WhileStatementDracoVMCodeGenerator { public static List<String> genVMCodeForWhileStatement( final WhileStatementNode whileStmt, final MethodNode containerMethod, final SymbolTableContext ctx ) throws Exception { final List<String> vm = new ArrayList<>(); final long unique = unique(); final String startlabel = "whilestart" + unique; final String endlabel = "whileend" + unique; vm.add("label "+startlabel); //push the expression vm.addAll(genDracoVMCodeForExpression(whileStmt.condition, ctx)); //+1 vm.add("not"); //if condition is false, jump to end vm.add("if-goto "+endlabel); //execute statements for (StatementNode stmt : whileStmt.statements) { vm.addAll(generateDracoVMCodeForStatement(stmt, containerMethod, ctx)); } vm.add("goto "+startlabel); vm.add("label "+endlabel); return vm; } }
1,882
0.744952
0.744421
49
37.408165
36.739525
137
false
false
0
0
0
0
0
0
0.571429
false
false
5
58a96375d7f7ef6c5d35014770c4e612a96c4713
35,132,832,492,850
13d2288c5edb5cd63516c5584b967e7858188051
/src/com/openmf/tweening/Pointer.java
99f58effdbe8cfb961554a4761eb5e857113bb37
[]
no_license
DCubix/OpenMF
https://github.com/DCubix/OpenMF
4c36c4a8ba0894785769d7c7d822d98df6c347af
459eec38897f7706706c0c96832699bf5396a252
refs/heads/master
2021-01-19T20:45:53.989000
2017-04-18T01:28:27
2017-04-18T01:28:27
88,548,126
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.openmf.tweening; import java.lang.reflect.Field; public class Pointer<T extends Object> { private Object object; private String field; public Pointer(Object object, String field) { this.object = object; this.field = field; } public T getValue() { try { Field f = object.getClass().getDeclaredField(field); return (T) f.get(object); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } return null; } public void setValue(T value) { try { Field f = object.getClass().getDeclaredField(field); f.set(object, value); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } } }
UTF-8
Java
945
java
Pointer.java
Java
[]
null
[]
package com.openmf.tweening; import java.lang.reflect.Field; public class Pointer<T extends Object> { private Object object; private String field; public Pointer(Object object, String field) { this.object = object; this.field = field; } public T getValue() { try { Field f = object.getClass().getDeclaredField(field); return (T) f.get(object); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } return null; } public void setValue(T value) { try { Field f = object.getClass().getDeclaredField(field); f.set(object, value); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } } }
945
0.653968
0.653968
42
20.5
16.105679
55
false
false
0
0
0
0
0
0
2.071429
false
false
5