blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
c1173ba155a91ed2b7b30a164d6d7ea75bd70817
9a6aa71b4b22da732d57db26c3143f9ea0644800
/hx-ktdb/src/main/java/com/gistone/service/impl/LmMarkerRelationPositionServiceImpl.java
2bdcc0729d7498dd0c1f4c7a0cb9bd33f6cb36df
[]
no_license
zjw118/anhui
d9067b57bedda2b59d5bfe06fcf761ef6d5bec83
ec93131a62f2c7709fc61acc53f199ea215ce4ec
refs/heads/master
2022-12-09T20:58:42.925010
2019-12-13T02:41:19
2019-12-13T02:41:19
229,440,319
0
0
null
2022-12-06T00:45:24
2019-12-21T14:38:38
Java
UTF-8
Java
false
false
589
java
package com.gistone.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.gistone.entity.LmMarkerRelationPosition; import com.gistone.mapper.LmMarkerRelationPositionMapper; import com.gistone.service.ILmMarkerRelationPositionService; import org.springframework.stereotype.Service; /** * <p> * 服务实现类 * </p> * * @author xjc * @since 2019-03-20 */ @Service public class LmMarkerRelationPositionServiceImpl extends ServiceImpl<LmMarkerRelationPositionMapper, LmMarkerRelationPosition> implements ILmMarkerRelationPositionService { }
33b718c31592ed3e3e6dab57d1c97b983824cde0
9d2a25381c5a44dd4bb537b847a1f7c066efbca5
/src/test/java/org/parksy/java/examples/logging/LoggingTest.java
b702f3d07212e0c381dae7622cead7980c0fbb69
[]
no_license
djparks/JavaSamples
45fbfd8dc29caff7377c8fe4f1f382cedbf1222c
76569a5f4e5aa3f81d3796f33c0d693088119b50
refs/heads/master
2022-07-26T13:00:21.265258
2022-07-20T19:47:34
2022-07-20T19:47:34
4,502,524
0
0
null
2022-07-20T19:47:35
2012-05-31T01:18:41
Java
UTF-8
Java
false
false
606
java
package org.parksy.java.examples.logging; import org.junit.Rule; import org.junit.Test; import org.junit.rules.MethodRule; import org.junit.rules.TestWatchman; import org.junit.runners.model.FrameworkMethod; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; public class LoggingTest { @Rule public MethodRule watchman = new TestWatchman() { public void starting(FrameworkMethod method) { // logger.info("{} being run...", method.getName()); } }; // final Logger logger = LoggerFactory.getLogger(LoggingTest.class); @Test public void testA() { } @Test public void testB() { } }
aa707b54b392f9de3dff33b63870d10f15803c5f
446402bebd611e63e3ac6ccc725fd5e1d363fff8
/BinarySearchTree.java
6df1558a12c086b1c35ad0728d779763586cd947
[]
no_license
iturimbetov/COMP202_HW6_final
9a046d000120145d870cbb40bdde8329491309cf
708ed41c43538286c1fec3b5485aca7ad6eec783
refs/heads/main
2023-02-04T00:50:02.316420
2020-12-28T11:40:58
2020-12-28T11:40:58
324,845,321
0
0
null
null
null
null
UTF-8
Java
false
false
525
java
public class BinarySearchTree implements BSTInterface { public TreeNode root; public BinarySearchTree() { root = null; } @Override public void add(Student data) { // TODO: add your code here } @Override public TreeNode delete(Student data) { // TODO: add your code here return null; } @Override public TreeNode search(Student data) { // you don't have to implement it return null; } @Override public boolean contains(Student data) { // you don't have to implement it return false; } }
6b1884817598cbe0b9272225977af760d3754035
93c5b9273270f79ac3fd49e5ff0cc104d78ed50a
/starter/src/main/java/com/salmondx/cxf/client/core/utils/NamingUtilities.java
3a3687ee5c16f258ad60badfdcb383886ce1b4a5
[ "MIT" ]
permissive
jiraguha/spring-soap-client-starter
92818d4faef4a657b133a5f8a8ff336297296b15
f42b3cb86a879bbb435fbcad1eca5d34559334f6
refs/heads/master
2021-05-14T19:37:40.993083
2017-11-10T09:14:40
2017-11-10T09:16:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
284
java
package com.salmondx.cxf.client.core.utils; import org.apache.commons.lang3.StringUtils; /** * Created by Salmondx on 08/09/16. */ public class NamingUtilities { public static String removeSetPrefix(String name) { return StringUtils.removeStart(name, "set"); } }
4fef3f090588effd2c0ada4dd534d7e3c25a0d02
f35f4008d60bf04e6e3236a60514693cae296d42
/app/src/main/java/com/google/android/gms/fitness/request/z.java
82f1997113d081c6e13441f11448ec04c24e2874
[]
no_license
alsmwsk/golfmon
ef0c8e8c7ecaa13371deed40f7e20468b823b0e9
740132d47185bfe9ec9d6774efbde5404ea8cf6d
refs/heads/master
2020-03-22T11:16:01.438894
2018-07-06T09:47:10
2018-07-06T09:47:10
139,959,669
0
0
null
null
null
null
UTF-8
Java
false
false
1,665
java
package com.google.android.gms.fitness.request; import android.os.Parcel; import android.os.Parcelable.Creator; import com.google.android.gms.common.internal.safeparcel.a; import com.google.android.gms.common.internal.safeparcel.a.a; import com.google.android.gms.common.internal.safeparcel.b; public class z implements Parcelable.Creator<y> { static void a(y paramy, Parcel paramParcel, int paramInt) { int i = b.H(paramParcel); b.a(paramParcel, 1, paramy.getName(), false); b.c(paramParcel, 1000, paramy.getVersionCode()); b.a(paramParcel, 2, paramy.getIdentifier(), false); b.H(paramParcel, i); } public y bW(Parcel paramParcel) { String str1 = null; int i = a.G(paramParcel); int j = 0; String str2 = null; while (paramParcel.dataPosition() < i) { int k = a.F(paramParcel); switch (a.aH(k)) { default: a.b(paramParcel, k); break; case 1: str2 = a.o(paramParcel, k); break; case 1000: j = a.g(paramParcel, k); break; case 2: str1 = a.o(paramParcel, k); } } if (paramParcel.dataPosition() != i) { throw new a.a("Overread allowed size end=" + i, paramParcel); } return new y(j, str2, str1); } public y[] dr(int paramInt) { return new y[paramInt]; } } /* Location: C:\Users\TGKIM\Downloads\작업폴더\리버싱\androidReversetools\jd-gui-0.3.6.windows\com.appg.golfmon-1-dex2jar.jar * Qualified Name: com.google.android.gms.fitness.request.z * JD-Core Version: 0.7.0.1 */
79ff019a70da67f625ec029e11f9ca6ae0f719f3
a3eacf1d95a204850e6a2913a4d2e01786bb4c35
/src/main/java/com/github/vaerys/pogos/Events.java
95e921f9f0835e88eb1a504aceebfc5e998b416a
[]
no_license
AndrielChaoti/DiscordSailv2
53e3a78492555958d0f6244b1dbaabbdbd352008
4a73090611909c86767a055675f6deb5a60d41f0
refs/heads/master
2021-01-19T20:44:11.139088
2018-03-18T04:50:13
2018-03-18T04:50:13
101,136,774
0
0
null
2017-08-23T04:12:49
2017-08-23T04:12:49
null
UTF-8
Java
false
false
439
java
package com.github.vaerys.pogos; import com.github.vaerys.objects.TimedEvent; import com.github.vaerys.templates.GlobalFile; import java.util.ArrayList; import java.util.List; public class Events extends GlobalFile { public static final String FILE_PATH = "Events.json"; List<TimedEvent> events = new ArrayList<>(); private double fileVersion = 1.0; public List<TimedEvent> getEvents() { return events; } }
3c62bdf791a3cee03f4373a4ebe2a0c78b88cd56
6829f722e1e776649feaa08dee1899fbee8b54a0
/a6-nishita1207/src/a6/Crab.java
95a5241749e265dd4ba8b69c39ca4e4e652f99f5
[]
no_license
nishita1207/COMP401
5c6818fe4a6556dff7bc3003c9c8a4236747c959
8fa69877f7f5749fba10255f4bd6740f85f42401
refs/heads/master
2020-08-03T12:56:56.688251
2019-09-30T02:28:15
2019-09-30T02:28:15
211,752,738
0
0
null
null
null
null
UTF-8
Java
false
false
144
java
package a6; public class Crab extends IngredientDetail{ public Crab(){ super("crab", 37, 0.72, false, false, true); } }
861740639ba6107d68545f285a9cc48332cbae34
b496d18b87d2617bd287f5f13ef030219f84d0a7
/src/main/java/net/thecir/filemanagers/NewFileManager.java
388fc7340b283e7ddc6ff92b4f74c66bc724dac4
[]
no_license
KonstantinTsanov/LiteReportManager
c5198f1df800696fae0c2d0240fc1d0736c1982e
ae33031411b5fe10743977f6f743b1edfd151a47
refs/heads/master
2021-01-01T04:08:23.284228
2017-08-09T05:30:57
2017-08-09T05:30:57
97,129,181
0
0
null
null
null
null
UTF-8
Java
false
false
5,378
java
/* * The MIT License * * Copyright 2017 Konstantin Tsanov <[email protected]>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package net.thecir.filemanagers; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ResourceBundle; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import java.util.logging.Level; import javax.swing.SwingUtilities; import lombok.extern.java.Log; import net.thecir.callbacks.FileCallback; import net.thecir.exceptions.NewFileCreationException; import net.thecir.exceptions.OutputFileIOException; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * Creates a new xlsx file and formats it. * * @author Konstantin Tsanov <[email protected]> */ @Log public class NewFileManager { private volatile FileCallback fileCallback; private static NewFileManager instance; private static ResourceBundle rb; private NewFileManager() { } public static NewFileManager getInstance() { if (instance == null) { instance = new NewFileManager(); } rb = ResourceBundle.getBundle("CoreLanguageBundles/ErrorMessages"); return instance; } public void setFileCallback(FileCallback fileCallback) { this.fileCallback = fileCallback; } public boolean createNewWorkbook() throws OutputFileIOException, NewFileCreationException { XSSFWorkbook wb; try { wb = new XSSFWorkbook(ClassLoader.getSystemResourceAsStream("excel/default.xlsx")); NewFileFormatter formatter = new NewFileFormatter(wb); formatter.formatWorkbook(); FutureTask<File> getFileTask = new FutureTask<>(new Callable<File>() { @Override public File call() { return fileCallback.getFile(); } }); try { SwingUtilities.invokeAndWait(getFileTask); } catch (InterruptedException ex) { log.log(Level.SEVERE, "A thread waiting for the user to select new file to be created has been interrupted.", ex); throw new RuntimeException(rb.getString("FailedToCreateNewFile")); } catch (InvocationTargetException ex) { log.log(Level.SEVERE, "Invocation of the runnable to obtain the new file name/path has failed.", ex); throw new RuntimeException(rb.getString("FailedToCreateNewFile")); } File file = null; try { file = getFileTask.get(); } catch (InterruptedException ex) { log.log(Level.SEVERE, "The thread waiting for the user to select new file to be created has been interrupted.", ex); throw new RuntimeException(rb.getString("FailedToCreateNewFile")); } catch (ExecutionException ex) { log.log(Level.SEVERE, "Failed to obtain the new file name.", ex); throw new RuntimeException(rb.getString("FailedToCreateNewFile")); } if (file == null) { return false; } if (file.exists() && !file.renameTo(file)) { log.log(Level.SEVERE, "The selected output file is in use by another process/program."); throw new OutputFileIOException(rb.getString("OutputFileInUseException")); } try (FileOutputStream fileOut = new FileOutputStream(file)) { wb.write(fileOut); fileCallback.setAsOutputAndDisplay(); return true; } catch (IOException ex) { log.log(Level.SEVERE, "Failed to save output file!", ex); throw new OutputFileIOException("A problem occured while saving file!"); } } catch (OutputFileIOException ex) { throw ex; } catch (IOException ex) { log.log(Level.SEVERE, "A problem occured while getting the default workbook...", ex); throw new NewFileCreationException("Cannot create new file!"); } } }
e3d4ce292143758130d1c985fea0d1ca2b556ed0
17107e38fb7527b220b1b51ed1dd81e3429c051e
/library/src/main/java/cn/trinea/android/common/util/JSONUtils.java
8d7a1269af7d6196ffc964b735b9d5639505f6b7
[]
no_license
dusensong/common-library
ea32004bbe57cc21fdc1fd13d3ff47c849d3a3d0
236da3878c60a12fd75789c04b72ff36aa0f75b0
refs/heads/master
2020-12-26T01:48:51.202453
2015-11-18T03:34:14
2015-11-18T03:34:14
36,588,270
0
1
null
null
null
null
UTF-8
Java
false
false
26,655
java
package cn.trinea.android.common.util; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import wehax.util.StringUtils; /** * Json Utils * * @author <a href="http://www.trinea.cn" target="_blank">Trinea</a> 2012-5-12 */ public class JSONUtils { public static boolean isPrintException = true; private JSONUtils() { throw new AssertionError(); } /** * get Long from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if key is null or empty, return defaultValue</li> * <li>if {@link JSONObject#getLong(String)} exception, return defaultValue</li> * <li>return {@link JSONObject#getLong(String)}</li> * </ul> */ public static Long getLong(JSONObject jsonObject, String key, Long defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { return jsonObject.getLong(key); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get Long from jsonData * * @param jsonData * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONUtils#getLong(JSONObject, String, JSONObject)}</li> * </ul> */ public static Long getLong(String jsonData, String key, Long defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getLong(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * @param jsonObject * @param key * @param defaultValue * @return * @see JSONUtils#getLong(JSONObject, String, Long) */ public static long getLong(JSONObject jsonObject, String key, long defaultValue) { return getLong(jsonObject, key, (Long)defaultValue); } /** * @param jsonData * @param key * @param defaultValue * @return * @see JSONUtils#getLong(String, String, Long) */ public static long getLong(String jsonData, String key, long defaultValue) { return getLong(jsonData, key, (Long)defaultValue); } /** * get Int from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if key is null or empty, return defaultValue</li> * <li>if {@link JSONObject#getInt(String)} exception, return defaultValue</li> * <li>return {@link JSONObject#getInt(String)}</li> * </ul> */ public static Integer getInt(JSONObject jsonObject, String key, Integer defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { return jsonObject.getInt(key); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get Int from jsonData * * @param jsonData * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONUtils#getInt(JSONObject, String, JSONObject)}</li> * </ul> */ public static Integer getInt(String jsonData, String key, Integer defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getInt(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * @param jsonObject * @param key * @param defaultValue * @return * @see JSONUtils#getInt(JSONObject, String, Integer) */ public static int getInt(JSONObject jsonObject, String key, int defaultValue) { return getInt(jsonObject, key, (Integer)defaultValue); } /** * @param jsonObject * @param key * @param defaultValue * @return * @see JSONUtils#getInt(String, String, Integer) */ public static int getInt(String jsonData, String key, int defaultValue) { return getInt(jsonData, key, (Integer)defaultValue); } /** * get Double from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if key is null or empty, return defaultValue</li> * <li>if {@link JSONObject#getDouble(String)} exception, return defaultValue</li> * <li>return {@link JSONObject#getDouble(String)}</li> * </ul> */ public static Double getDouble(JSONObject jsonObject, String key, Double defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { return jsonObject.getDouble(key); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get Double from jsonData * * @param jsonData * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONUtils#getDouble(JSONObject, String, JSONObject)}</li> * </ul> */ public static Double getDouble(String jsonData, String key, Double defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getDouble(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * @param jsonObject * @param key * @param defaultValue * @return * @see JSONUtils#getDouble(JSONObject, String, Double) */ public static double getDouble(JSONObject jsonObject, String key, double defaultValue) { return getDouble(jsonObject, key, (Double)defaultValue); } /** * @param jsonObject * @param key * @param defaultValue * @return * @see JSONUtils#getDouble(String, String, Double) */ public static double getDouble(String jsonData, String key, double defaultValue) { return getDouble(jsonData, key, (Double)defaultValue); } /** * get String from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if key is null or empty, return defaultValue</li> * <li>if {@link JSONObject#getString(String)} exception, return defaultValue</li> * <li>return {@link JSONObject#getString(String)}</li> * </ul> */ public static String getString(JSONObject jsonObject, String key, String defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { return jsonObject.getString(key); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get String from jsonData * * @param jsonData * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONUtils#getString(JSONObject, String, JSONObject)}</li> * </ul> */ public static String getString(String jsonData, String key, String defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getString(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get String from jsonObject * * @param jsonObject * @param defaultValue * @param keyArray * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if keyArray is null or empty, return defaultValue</li> * <li>get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. if anyone is * null, return directly</li> * </ul> */ public static String getStringCascade(JSONObject jsonObject, String defaultValue, String... keyArray) { if (jsonObject == null || ArrayUtils.isEmpty(keyArray)) { return defaultValue; } String data = jsonObject.toString(); for (String key : keyArray) { data = getStringCascade(data, key, defaultValue); if (data == null) { return defaultValue; } } return data; } /** * get String from jsonData * * @param jsonData * @param defaultValue * @param keyArray * @return <ul> * <li>if jsonData is null, return defaultValue</li> * <li>if keyArray is null or empty, return defaultValue</li> * <li>get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. if anyone is * null, return directly</li> * </ul> */ public static String getStringCascade(String jsonData, String defaultValue, String... keyArray) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } String data = jsonData; for (String key : keyArray) { data = getString(data, key, defaultValue); if (data == null) { return defaultValue; } } return data; } /** * get String array from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if key is null or empty, return defaultValue</li> * <li>if {@link JSONObject#getJSONArray(String)} exception, return defaultValue</li> * <li>if {@link JSONArray#getString(int)} exception, return defaultValue</li> * <li>return string array</li> * </ul> */ public static String[] getStringArray(JSONObject jsonObject, String key, String[] defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { JSONArray statusArray = jsonObject.getJSONArray(key); if (statusArray != null) { String[] value = new String[statusArray.length()]; for (int i = 0; i < statusArray.length(); i++) { value[i] = statusArray.getString(i); } return value; } } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } return defaultValue; } /** * get String array from jsonData * * @param jsonData * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONUtils#getStringArray(JSONObject, String, JSONObject)}</li> * </ul> */ public static String[] getStringArray(String jsonData, String key, String[] defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getStringArray(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get String list from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if key is null or empty, return defaultValue</li> * <li>if {@link JSONObject#getJSONArray(String)} exception, return defaultValue</li> * <li>if {@link JSONArray#getString(int)} exception, return defaultValue</li> * <li>return string array</li> * </ul> */ public static List<String> getStringList(JSONObject jsonObject, String key, List<String> defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { JSONArray statusArray = jsonObject.getJSONArray(key); if (statusArray != null) { List<String> list = new ArrayList<String>(); for (int i = 0; i < statusArray.length(); i++) { list.add(statusArray.getString(i)); } return list; } } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } return defaultValue; } /** * get String list from jsonData * * @param jsonData * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONUtils#getStringList(JSONObject, String, List)}</li> * </ul> */ public static List<String> getStringList(String jsonData, String key, List<String> defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getStringList(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get JSONObject from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if key is null or empty, return defaultValue</li> * <li>if {@link JSONObject#getJSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONObject#getJSONObject(String)}</li> * </ul> */ public static JSONObject getJSONObject(JSONObject jsonObject, String key, JSONObject defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { return jsonObject.getJSONObject(key); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get JSONObject from jsonData * * @param jsonData * @param key * @param defaultValue * @return <ul> * <li>if jsonData is null, return defaultValue</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONUtils#getJSONObject(JSONObject, String, JSONObject)}</li> * </ul> */ public static JSONObject getJSONObject(String jsonData, String key, JSONObject defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getJSONObject(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get JSONObject from jsonObject * * @param jsonObject * @param defaultValue * @param keyArray * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if keyArray is null or empty, return defaultValue</li> * <li>get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. if anyone is * null, return directly</li> * </ul> */ public static JSONObject getJSONObjectCascade(JSONObject jsonObject, JSONObject defaultValue, String... keyArray) { if (jsonObject == null || ArrayUtils.isEmpty(keyArray)) { return defaultValue; } JSONObject js = jsonObject; for (String key : keyArray) { js = getJSONObject(js, key, defaultValue); if (js == null) { return defaultValue; } } return js; } /** * get JSONObject from jsonData * * @param jsonData * @param defaultValue * @param keyArray * @return <ul> * <li>if jsonData is null, return defaultValue</li> * <li>if keyArray is null or empty, return defaultValue</li> * <li>get {@link #getJSONObject(JSONObject, String, JSONObject)} by recursion, return it. if anyone is * null, return directly</li> * </ul> */ public static JSONObject getJSONObjectCascade(String jsonData, JSONObject defaultValue, String... keyArray) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getJSONObjectCascade(jsonObject, defaultValue, keyArray); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get JSONArray from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if key is null or empty, return defaultValue</li> * <li>if {@link JSONObject#getJSONArray(String)} exception, return defaultValue</li> * <li>return {@link JSONObject#getJSONArray(String)}</li> * </ul> */ public static JSONArray getJSONArray(JSONObject jsonObject, String key, JSONArray defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { return jsonObject.getJSONArray(key); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get JSONArray from jsonData * * @param jsonData * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONUtils#getJSONArray(JSONObject, String, JSONObject)}</li> * </ul> */ public static JSONArray getJSONArray(String jsonData, String key, JSONArray defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getJSONArray(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get Boolean from jsonObject * * @param jsonObject * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if key is null or empty, return defaultValue</li> * <li>return {@link JSONObject#getBoolean(String)}</li> * </ul> */ public static boolean getBoolean(JSONObject jsonObject, String key, Boolean defaultValue) { if (jsonObject == null || StringUtils.isEmpty(key)) { return defaultValue; } try { return jsonObject.getBoolean(key); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get Boolean from jsonData * * @param jsonData * @param key * @param defaultValue * @return <ul> * <li>if jsonObject is null, return defaultValue</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return defaultValue</li> * <li>return {@link JSONUtils#getBoolean(JSONObject, String, Boolean)}</li> * </ul> */ public static boolean getBoolean(String jsonData, String key, Boolean defaultValue) { if (StringUtils.isEmpty(jsonData)) { return defaultValue; } try { JSONObject jsonObject = new JSONObject(jsonData); return getBoolean(jsonObject, key, defaultValue); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return defaultValue; } } /** * get map from jsonObject. * * @param jsonObject key-value pairs json * @param key * @return <ul> * <li>if jsonObject is null, return null</li> * <li>return {@link JSONUtils#parseKeyAndValueToMap(String)}</li> * </ul> */ public static Map<String, String> getMap(JSONObject jsonObject, String key) { return JSONUtils.parseKeyAndValueToMap(JSONUtils.getString(jsonObject, key, null)); } /** * get map from jsonData. * * @param jsonData key-value pairs string * @param key * @return <ul> * <li>if jsonData is null, return null</li> * <li>if jsonData length is 0, return empty map</li> * <li>if jsonData {@link JSONObject#JSONObject(String)} exception, return null</li> * <li>return {@link JSONUtils#getMap(JSONObject, String)}</li> * </ul> */ public static Map<String, String> getMap(String jsonData, String key) { if (jsonData == null) { return null; } if (jsonData.length() == 0) { return new HashMap<String, String>(); } try { JSONObject jsonObject = new JSONObject(jsonData); return getMap(jsonObject, key); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return null; } } /** * parse key-value pairs to map. ignore empty key, if getValue exception, put empty value * * @param sourceObj key-value pairs json * @return <ul> * <li>if sourceObj is null, return null</li> * <li>else parse entry by {@link MapUtils#putMapNotEmptyKey(Map, String, String)} one by one</li> * </ul> */ @SuppressWarnings("rawtypes") public static Map<String, String> parseKeyAndValueToMap(JSONObject sourceObj) { if (sourceObj == null) { return null; } Map<String, String> keyAndValueMap = new HashMap<String, String>(); for (Iterator iter = sourceObj.keys(); iter.hasNext();) { String key = (String)iter.next(); MapUtils.putMapNotEmptyKey(keyAndValueMap, key, getString(sourceObj, key, "")); } return keyAndValueMap; } /** * parse key-value pairs to map. ignore empty key, if getValue exception, put empty value * * @param source key-value pairs json * @return <ul> * <li>if source is null or source's length is 0, return empty map</li> * <li>if source {@link JSONObject#JSONObject(String)} exception, return null</li> * <li>return {@link JSONUtils#parseKeyAndValueToMap(JSONObject)}</li> * </ul> */ public static Map<String, String> parseKeyAndValueToMap(String source) { if (StringUtils.isEmpty(source)) { return null; } try { JSONObject jsonObject = new JSONObject(source); return parseKeyAndValueToMap(jsonObject); } catch (JSONException e) { if (isPrintException) { e.printStackTrace(); } return null; } } }
7bbe92880a3603c8520d3d37a19a1c6dbe6998a1
c294b2f6e57904381f272c03652c0fea276b7f17
/Problem_3886.java
32a36da2314bab6035333be0766614fe29bdac78
[]
no_license
bbs-white/UVa_JavaPrograming
0c69843f395314c6cf6ad1b4793da56fc8866f81
414c395546dfcca836b7bfb002f6a975a0140986
refs/heads/master
2021-08-19T12:16:35.248124
2017-11-26T06:33:46
2017-11-26T06:33:46
111,862,235
0
0
null
null
null
null
UTF-8
Java
false
false
1,041
java
//Problem_3886 Bars import java.util.*; class Main{ static boolean s = false; public static void main(String[] args){ Scanner scan = new Scanner(System.in); // Caseを入力 int T = scan.nextInt(); for(int t = 0; t < T; t++){ int N = scan.nextInt(); int P = scan.nextInt(); int[] x = new int[P]; for(int i = 0; i < P; i++) x[i] = scan.nextInt(); bubble_sort(x); s = false; dfs(x,0,0,N); if(s) System.out.println("YES"); else System.out.println("NO"); } } public static void swap(int[] A, int i, int j){ int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } public static void bubble_sort(int[] A){ int n = A.length; for(int i = 0; i < n; i++){ for(int j = n-1; j > i; j--){ if(A[j-1] > A[j]) swap(A,j,j-1); } } } public static void dfs(int[] A, int ci, int cl, int N){ if(cl == N){ s = true; }else if(!s){ for(int i = ci; i < A.length; i++){ if(cl + A[i] <= N){ dfs(A, i+1, cl+A[i], N); } } } } }
498396835d319faf943813cd668f4e73cf9c71e7
fa55027e10c36977b4a50946d663e15f8fe0faf7
/src/org/wshuai/leetcode/AmbiguousCoordinates.java
f332da30aff8c65a77b98ad989dcfa37cb0c6f88
[]
no_license
relentlesscoder/Leetcode
773a207c15ea72f6027eade8565377f11a856672
6b3ecd82d01739f6adb1caf86a770fcff0d6a54b
refs/heads/master
2021-07-05T13:35:37.312910
2020-06-21T12:48:54
2020-06-21T12:48:54
40,448,524
0
0
null
null
null
null
UTF-8
Java
false
false
1,407
java
package org.wshuai.leetcode; import java.util.ArrayList; import java.util.List; /** * Created by Wei on 11/11/2019. * #0816 https://leetcode.com/problems/ambiguous-coordinates/ */ public class AmbiguousCoordinates { // time O(n^3), space O(n^2) public List<String> ambiguousCoordinates(String S) { S = S.substring(1, S.length() - 1); List<String> res = new ArrayList<>(); for(int i = 1; i < S.length(); i++){ String s1 = S.substring(0, i), s2 = S.substring(i); List<String> l1 = parse(s1), l2 = parse(s2); if(l1.size() > 0 && l2.size() > 0){ for(String v1 : l1){ for(String v2 : l2){ res.add("(" + v1 + ", " + v2 + ")"); } } } } return res; } private List<String> parse(String s){ int n = s.length(); List<String> result = new ArrayList<>(); // "0xxxx0" invalid unless a single "0" if (s.charAt(0) == '0' && s.charAt(n - 1) == '0') { if (n == 1) { result.add("0"); } return result; } // "0xxxxx" the only valid result is "0.xxxxx" if (s.charAt(0) == '0') { result.add("0." + s.substring(1)); return result; } // "xxxxx0" the only valid result is itself if (s.charAt(n - 1) == '0') { result.add(s); return result; } // add itself result.add(s); // "xxxx" -> "x.xxx", "xx.xx", "xxx.x" for (int i = 1; i < n; i++) { result.add(s.substring(0, i) + '.' + s.substring(i)); } return result; } }
83df2e415ea022fb51841e2296404f2a84e24529
21e73f952ecf395afde0d9e570c83cc963d8fda9
/JavaNumberPrograms/Recursion2.java
c424015f1513c96f4f79a326beb1ec184b83c192
[]
no_license
DivyaAR04/Java-Programs
ceaff994263cd860439409b10ddf36dc1a240631
672b5c5f95418be79ed395784c49f3151a4004c9
refs/heads/master
2022-05-29T16:47:21.277766
2020-04-30T12:48:04
2020-04-30T12:48:04
259,879,269
0
0
null
null
null
null
UTF-8
Java
false
false
273
java
package javaPractice; public class Recursion2 { public static void test(int a) { if(a<=10) { System.out.println(a); a++; test(a); } } public static void main(String[] args) { // TODO Auto-generated method stub test(1); } }
ce3d2d2444792e9682ba86f5d7bbc2a7e014ad1c
914de9bb4831eb9803330b267870ff0dcd838456
/TalkingTagsClient/src/com/google/android/apps/talkingtags/model/Tag.java
bf1d2abcb1ca23347a7cc527d1199ba968fd430e
[]
no_license
audisuv/talking-tags-android-client
bbceb6a1afa94ca9a67b94b5cbd34a4274684521
2575ffc847dbb22b6d936ebadecd3c5cdb2fe7cf
refs/heads/master
2016-08-12T02:58:08.349142
2015-05-30T12:34:02
2015-05-30T12:34:02
36,557,266
0
0
null
null
null
null
UTF-8
Java
false
false
743
java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.talkingtags.model; import java.io.Serializable; /** * Represents a tag-instance. * @author [email protected] (Adam Connors) */ public class Tag implements Serializable { private static final long serialVersionUID = 1L; public final String tagId; public final String tagShortDescription; public final String title; public final String body; public Tag(String tagId, String shortDesc, String title, String body) { this.tagId = tagId; this.tagShortDescription = shortDesc; this.title = title; this.body = body; } @Override public String toString() { return "Tag: " + tagId + ": " + title + "/" + body; } }
[ "adamconnors@2f18c655-9d46-4c27-46c3-8d257dfb4d8a" ]
adamconnors@2f18c655-9d46-4c27-46c3-8d257dfb4d8a
674161e26c7010ca234f15ebe8583f29752bc2ea
589dcd422402477ce80e9c349bd483c2d36b80cd
/trunk/adhoc-solr/src/main/java/org/apache/lucene/util/cache/Cache.java
5261a53178b878fefaeb76c47cc879d561842e7f
[ "Apache-2.0", "LicenseRef-scancode-unicode-mappings", "BSD-3-Clause", "CDDL-1.0", "Python-2.0", "MIT", "ICU", "CPL-1.0" ]
permissive
baojiawei1230/mdrill
e3d92f4f1f85b34f0839f8463e7e5353145a9c78
edacdb4dc43ead6f14d83554c1f402aa1ffdec6a
refs/heads/master
2021-06-10T17:42:11.076927
2021-03-15T16:43:06
2021-03-15T16:43:06
95,193,877
0
0
Apache-2.0
2021-03-15T16:43:06
2017-06-23T07:15:00
Java
UTF-8
Java
false
false
3,323
java
package org.apache.lucene.util.cache; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.Closeable; /** * Base class for cache implementations. */ public abstract class Cache<K,V> implements Closeable { /** * Simple Cache wrapper that synchronizes all * calls that access the cache. */ static class SynchronizedCache<K,V> extends Cache<K,V> { private Object mutex; private Cache<K,V> cache; SynchronizedCache(Cache<K,V> cache) { this.cache = cache; this.mutex = this; } SynchronizedCache(Cache<K,V> cache, Object mutex) { this.cache = cache; this.mutex = mutex; } @Override public void put(K key, V value) { synchronized(mutex) {cache.put(key, value);} } @Override public V get(Object key) { synchronized(mutex) {return cache.get(key);} } @Override public boolean containsKey(Object key) { synchronized(mutex) {return cache.containsKey(key);} } @Override public void close() { synchronized(mutex) {cache.close();} } @Override Cache<K,V> getSynchronizedCache() { return this; } @Override public V remove(Object key) { synchronized(mutex) {return cache.remove(key);} } @Override public int size() { synchronized(mutex) {return cache.size();} } } /** * Returns a thread-safe cache backed by the specified cache. * In order to guarantee thread-safety, all access to the backed cache must * be accomplished through the returned cache. */ public static <K,V> Cache<K,V> synchronizedCache(Cache<K,V> cache) { return cache.getSynchronizedCache(); } /** * Called by {@link #synchronizedCache(Cache)}. This method * returns a {@link SynchronizedCache} instance that wraps * this instance by default and can be overridden to return * e. g. subclasses of {@link SynchronizedCache} or this * in case this cache is already synchronized. */ Cache<K,V> getSynchronizedCache() { return new SynchronizedCache<K,V>(this); } /** * Puts a (key, value)-pair into the cache. */ public abstract void put(K key, V value); public abstract int size(); /** * Returns the value for the given key. */ public abstract V get(Object key); public abstract V remove(Object key); /** * Returns whether the given key is in this cache. */ public abstract boolean containsKey(Object key); /** * Closes the cache. */ public abstract void close(); }
cc52ce49a4bbe409a22267a1c6e40ca498d34866
1afdc3381e7947620f0cd24cf9c097f144f79843
/Refactoring/src/exercise/refactoring/ComputerMove.java
0f5d6393eff534bb7379f5dc7c411eae02ca16b4
[]
no_license
compwron/refactoringExercise
c2532eab57914a64c33350105bf8e1f7252c9b7f
10cd6066e76c2fce02ab49f5ff8da88ae732cdae
refs/heads/master
2020-12-24T08:30:43.890630
2016-08-19T03:14:29
2016-08-19T03:14:29
11,492,944
0
1
null
null
null
null
UTF-8
Java
false
false
52,248
java
package exercise.refactoring; public class ComputerMove { private static final int lastPositionOnSecondToLastLine = 89; private final MoveSequence moveNumber; private final GamePosition nextComputerMove; private final GameBoard gameBoard; final MarksByAxis marksByAxis = new MarksByAxis(); public ComputerMove(MoveSequence moveNumber, RawPlayerMove rawPlayerMove, GameBoard gameBoard) { this.gameBoard = gameBoard; this.moveNumber = moveNumber; this.nextComputerMove = makeComputerMove(rawPlayerMove); } private GamePosition makeComputerMove(RawPlayerMove rawPlayerMove) { GamePosition position = new GamePosition(); if (moveNumber.isFirstMove()) { return rawPlayerMove.firstComputerMove(); } position = closeGapInSeries(gameBoard); if (moveNumber.isMove(2) && position.isNotNone()) { return position; } if (moveNumber.isOver(3)) { position = blockSeriesOfFourOrMoreInCheckMode(GameBoardMark.ZERO_MARK_FOR_COMPUTER); if (position.isNotNone()) { return position; } position = blockSeriesOfFourOrMoreInCheckMode(GameBoardMark.X_MARK_FOR_PLAYER); if (position.isNotNone()) { return position; } } position = responseTo3Or4InaRowOpportunityOnMainBoardInCheckMode(GameBoardMark.ZERO_MARK_FOR_COMPUTER); if ((moveNumber.isOver(2) && position.isNotNone())) { return position; } position.setPosition(tryToFindPositionGivingSeriesOf4OnTwoOrMoreAxes(GameBoardMark.ZERO_MARK_FOR_COMPUTER)); if ((moveNumber.isOver(5) && position.isNotNone())) { return position; } setFlagsForLaterProcessing(GameBoardMark.X_MARK_FOR_PLAYER); position.setPosition(tryToMake3WithGap_FromVert4IntersectingWithHoriz4(GameBoardMark.ZERO_MARK_FOR_COMPUTER)); if ((moveNumber.isOver(4) && position.isNotNone())) { return position; } position = responseTo3Or4InaRowOpportunityOnMainBoardInCheckMode(GameBoardMark.X_MARK_FOR_PLAYER); if ((moveNumber.isOver(2) && position.isNotNone())) { return position; } position.setPosition(tryToFindPositionGivingSeriesOf4OnTwoOrMoreAxes(GameBoardMark.X_MARK_FOR_PLAYER)); if ((moveNumber.isOver(5) && position.isNotNone())) { return position; } setFlagsForLaterProcessing(GameBoardMark.ZERO_MARK_FOR_COMPUTER); position.setPosition(tryToMake3WithGap_FromVert4IntersectingWithHoriz4(GameBoardMark.X_MARK_FOR_PLAYER)); if ((moveNumber.isOver(4) && position.isNotNone())) { return position; } gameBoard.setBoardTwoToDuplicateOfMainBoard(); position = checkSeries(GameBoardMark.ZERO_MARK_FOR_COMPUTER, 0); if ((moveNumber.isOver(3) && position.isNotNone())) { return position; } if (moveNumber.isOver(3)) { position = checkSeries(GameBoardMark.X_MARK_FOR_PLAYER, 0); if (position.isNotNone()) { return position; } } position.setPosition(check2o3c(GameBoardMark.ZERO_MARK_FOR_COMPUTER)); if ((moveNumber.isOver(2) && position.isNotNone())) { return position; } position.setPosition(check2o3c(GameBoardMark.X_MARK_FOR_PLAYER)); if ((moveNumber.isOver(20) && position.isNotNone())) { return position; } if (moveNumber.isOver(3)) { position.setPosition(checkCross(GameBoardMark.X_MARK_FOR_PLAYER)); if (position.isNotNone()) { return position; } } if (moveNumber.isOver(3)) { position.setPosition(checkCross(GameBoardMark.ZERO_MARK_FOR_COMPUTER)); if (position.isNotNone()) { return position; } } if (moveNumber.isOver(2)) { position.setPosition(checkBox(GameBoardMark.X_MARK_FOR_PLAYER)); if (position.isNotNone()) { return position; } } if (moveNumber.isOver(2)) { position = closeGapInSeries(gameBoard); if (position.isNotNone()) { return position; } } position = createTwoAxesOrCreateOneAndBlockAnother(); if (position.isNotNone()) { return position; } position = responseTo3Or4InaRowOpportunityOnMainBoardInCleanMode(GameBoardMark.ZERO_MARK_FOR_COMPUTER); if (position.isNotNone()) { return position; } position = responseTo3Or4InaRowOpportunityOnMainBoardInCleanMode(GameBoardMark.X_MARK_FOR_PLAYER); if (position.isNotNone()) { return position; } position.setPosition(findSpot(gameBoard)); return position; } private GamePosition createTwoAxesOrCreateOneAndBlockAnother() { seto4cc(GameBoardMark.X_MARK_FOR_PLAYER); for (int position = GameBoard.oneMoreThanSquaresPerSide; position < lastPositionOnSecondToLastLine; position++) if (positionIsOccupiedOnStagingBoardAndDesirable(gameBoard, new StagingBoard(), position)) { return new GamePosition(position); } return GamePosition.nonePosition(); } private boolean positionIsOccupiedOnStagingBoardAndDesirable(GameBoard gameBoard, StagingBoard stagingBoard, int position) { return stagingBoard.isOccupiedAtPosition(position) && gameBoard.positionIsDesirableForCreateTwoAxesOrCreateOneAndBlockAnother(position); } private GamePosition closeGapInSeries(GameBoard gameBoard) { for (int upToSeven = 1; upToSeven < 7; upToSeven++) { for (int upToNine = 1; upToNine < GameBoard.oneLessThanCountInRow; upToNine++) { int position = upToSeven + GameBoard.SQUARES_PER_SIDE * upToNine; int otherPosition = upToNine + upToSeven * GameBoard.SQUARES_PER_SIDE; if (gameBoard.hasOccupiedUnoccupiedOccupiedPatternStartingAt(position)) { return new GamePosition(position + 1); } if (gameBoard.hasOccupiedUnoccupiedOccupiedDiagonalPatternStartingAt(otherPosition)) { return new GamePosition(otherPosition + GameBoard.SQUARES_PER_SIDE); } } } return GamePosition.nonePosition(); } private GamePosition blockSeriesOfFourOrMoreInCheckMode(GameBoardMark playerMark) { int zero = 0; int upToSquaresPerSide, upToFive, upToSix; GamePosition position = new GamePosition(); GamePosition position2 = new GamePosition(); for (upToSix = 0; upToSix < 6; upToSix++) { for (upToSquaresPerSide = 0; upToSquaresPerSide < GameBoard.SQUARES_PER_SIDE; upToSquaresPerSide++) { gameBoard.resetAllMarksAlongAxesForFirstHalfOfBoard(marksByAxis); position = checkFor5AlongHorizAxis(playerMark, zero, upToSquaresPerSide, upToSix, position); if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 4), new MarksByAxisPositionPair(1, 1))) { return position; } position = checkFor5AlongVertAxis(playerMark, zero, upToSquaresPerSide, upToSix, position); if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(2, 4), new MarksByAxisPositionPair(3, 1))) { return position; } } for (upToSquaresPerSide = 0; upToSquaresPerSide < 6; upToSquaresPerSide++) { gameBoard.resetAllMarksAlongAxesForFirstHalfOfBoard(marksByAxis); for (upToFive = 0; upToFive < 5; upToFive++) { position = checkFor5AlongDiagDownRightAxis(playerMark, zero, upToSquaresPerSide, upToFive, upToSix, position); position2 = checkFor5AlongDiagUpRightAxis(playerMark, zero, upToSquaresPerSide, upToFive, upToSix, position2); } if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 4), new MarksByAxisPositionPair(1, 1))) { return position; } if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(2, 4), new MarksByAxisPositionPair(3, 1))) { return position2; } } } return GamePosition.nonePosition(); } private GamePosition responseTo3Or4InaRowOpportunityOnMainBoardInCheckMode(GameBoardMark playerMark) { int j, k, l; GamePosition place = new GamePosition(); int tempRowForChecks[] = new int[GameBoard.SQUARES_PER_SIDE]; for (k = 0; k < 4; k++) { tempRowForChecks[k] = 0; } for (l = 0; l < 5; l++) { for (j = 0; j < GameBoard.SQUARES_PER_SIDE; j++) { clearMarksByAxisArray(); if (gameBoard.hasEmptyValueOnMainBoardAt(j * GameBoard.SQUARES_PER_SIDE + l) && gameBoard.hasEmptyValueOnMainBoardAt(j * GameBoard.SQUARES_PER_SIDE + l + 5)) { place = checkForHoriz4InRow(playerMark, 0, j, l); if (anyHoriz4MatchToMark(Mode.CHECK, place)) return place; } if (gameBoard.hasEmptyValueOnMainBoardAt(l * GameBoard.SQUARES_PER_SIDE + j) && gameBoard.hasEmptyValueOnMainBoardAt(l * GameBoard.SQUARES_PER_SIDE + j + 50)) { place = checkForVert4InRow(playerMark, 0, j, l); if (anyVert4MatchToMark(Mode.CHECK, place)) return place; } } for (j = 0; j < 5; j++) { clearMarksByAxisArray(); if (gameBoard.hasEmptyValueOnMainBoardAt(l * GameBoard.SQUARES_PER_SIDE + j) && gameBoard.hasEmptyValueOnMainBoardAt(l * GameBoard.SQUARES_PER_SIDE + j + 55)) { place = checkForDiagDown4InRow(playerMark, 0, j, l); if (anyDiagDown4MatchToMark(Mode.CHECK, place)) return place; } if (gameBoard.hasEmptyValueOnMainBoardAt(l * GameBoard.SQUARES_PER_SIDE + j + 50) && gameBoard.hasEmptyValueOnMainBoardAt(l * GameBoard.SQUARES_PER_SIDE + j + 5)) { place = checkForDiagUp4InRow(playerMark, 0, j, l); if (anyDiagUp4MatchToMark(Mode.CHECK, place)) return place; } } } if (Mode.CHECK.equals(Mode.COUNT)) { return new GamePosition(tempRowForChecks[0] + tempRowForChecks[1] + tempRowForChecks[2] + tempRowForChecks[3]); } return GamePosition.nonePosition(); } private int tryToFindPositionGivingSeriesOf4OnTwoOrMoreAxes(GameBoardMark playerMark) { copyBoardToCheck(0); for (int k = 0; k < GameBoard.TOTAL_SQUARES_PER_BOARD; k++) { if (gameBoard.hasEmptyValueAt(1, k)) { gameBoard.setValueAt(1, k, playerMark); if (countNumberOfAxesAlongWhichSeriesOfFourOccur(playerMark, 1, Mode.CLEAN.rawMode) > 1) return k; gameBoard.setPositionToEmpty(1, k); } } return (GameBoard.oneMoreThanLastPositionOnBoard); } private int tryToMake3WithGap_FromVert4IntersectingWithHoriz4(GameBoardMark playerMark) { int k; int gameBoardLevelToCheck = GameBoard.indexOfMainBoard; for (k = 0; k < GameBoard.TOTAL_SQUARES_PER_BOARD; k++) gameBoard.setValueAt(1, k, gameBoard.getValueAt(gameBoardLevelToCheck, k)); for (k = 0; k < GameBoard.TOTAL_SQUARES_PER_BOARD; k++) { if (gameBoard.hasEmptyValueAt(1, k)) { gameBoard.setValueAt(1, k, playerMark); if (responseTo3Or4InaRowOpportunity(playerMark, 1, Mode.CHECK).isNotNone() && countNumberOfAxesAlongWhichSeriesOfFourOccur(playerMark, 1, Mode.SAFE.rawMode) > 0) { return k; } gameBoard.setPositionToEmpty(1, k); } } return (GameBoard.oneMoreThanLastPositionOnBoard); } private int check2o3c(GameBoardMark playerMark) { int k; for (k = 0; k < GameBoard.TOTAL_SQUARES_PER_BOARD; k++) { if (!gameBoard.hasEmptyValueOnMainBoardAt(k)) continue; gameBoard.setValueAt(GameBoard.indexOfMainBoard, k, playerMark); if (responseTo3Or4InaRowOpportunity(playerMark, GameBoard.indexOfMainBoard, Mode.COUNT).isOverOne()) { return k; } gameBoard.setValueAt(GameBoard.indexOfMainBoard, k, GameBoardMark.EMPTY); } return GameBoard.oneMoreThanLastPositionOnBoard; } private int checkCross(GameBoardMark playerMark) { int k, l, x; for (k = 1; k < 7; k++) { for (l = 1; l < 7; l++) { x = k + 10 * l; if (gameBoard.mainBoard()[x] == playerMark.index && gameBoard.mainBoard()[x + 2] == playerMark.index && gameBoard.mainBoard()[x + 20] == playerMark.index && gameBoard.mainBoard()[x + 22] == playerMark.index && gameBoard.mainBoard()[x + 11] == 0) return (x + 11); } } return GameBoard.oneMoreThanLastPositionOnBoard; } private int checkBox(GameBoardMark playerMark) { for (int k = 1; k < 8; k++) { for (int l = 1; l < 8; l++) { int cnt = 0; int pos = -1; for (int a = 0; a < 2; a++) { for (int b = 0; b < 2; b++) { int x = k + a + 10 * (l + b); int c = gameBoard.mainBoard()[x]; if (c == playerMark.index) cnt++; else if (c == 0) pos = x; } } if (cnt == 3 && pos != -1) return pos; } } return GameBoard.oneMoreThanLastPositionOnBoard; } private GamePosition responseTo3Or4InaRowOpportunityOnMainBoardInCleanMode(GameBoardMark playerMark) { int alsoUpToFive, upToFour, upToFive; GamePosition place = new GamePosition(); int tempRowForChecks[] = new int[GameBoard.SQUARES_PER_SIDE]; for (upToFour = 0; upToFour < 4; upToFour++) { tempRowForChecks[upToFour] = 0; } for (upToFive = 0; upToFive < 5; upToFive++) { for (alsoUpToFive = 0; alsoUpToFive < GameBoard.SQUARES_PER_SIDE; alsoUpToFive++) { clearMarksByAxisArray(); if (gameBoard.hasEmptyValueOnMainBoardAt(alsoUpToFive * GameBoard.SQUARES_PER_SIDE + upToFive) && gameBoard.hasEmptyValueOnMainBoardAt(alsoUpToFive * GameBoard.SQUARES_PER_SIDE + upToFive + 5)) { place = checkForHoriz4InRow(playerMark, 0, alsoUpToFive, upToFive); if (anyHoriz4MatchToMark(Mode.CLEAN, place)) return place; } if (gameBoard.hasEmptyValueOnMainBoardAt(upToFive * GameBoard.SQUARES_PER_SIDE + alsoUpToFive) && gameBoard.hasEmptyValueOnMainBoardAt(upToFive * GameBoard.SQUARES_PER_SIDE + alsoUpToFive + 50)) { place = checkForVert4InRow(playerMark, 0, alsoUpToFive, upToFive); if (anyVert4MatchToMark(Mode.CLEAN, place)) return place; } } for (alsoUpToFive = 0; alsoUpToFive < 5; alsoUpToFive++) { clearMarksByAxisArray(); if (gameBoard.hasEmptyValueOnMainBoardAt(upToFive * GameBoard.SQUARES_PER_SIDE + alsoUpToFive) && gameBoard.hasEmptyValueOnMainBoardAt(upToFive * GameBoard.SQUARES_PER_SIDE + alsoUpToFive + 55)) { place = checkForDiagDown4InRow(playerMark, 0, alsoUpToFive, upToFive); if (anyDiagDown4MatchToMark(Mode.CLEAN, place)) return place; } if (gameBoard.hasEmptyValueOnMainBoardAt(upToFive * GameBoard.SQUARES_PER_SIDE + alsoUpToFive + 50) && gameBoard.hasEmptyValueOnMainBoardAt(upToFive * GameBoard.SQUARES_PER_SIDE + alsoUpToFive + 5)) { place = checkForDiagUp4InRow(playerMark, 0, alsoUpToFive, upToFive); if (anyDiagUp4MatchToMark(Mode.CLEAN, place)) return place; } } } return GamePosition.nonePosition(); } private int findSpot(GameBoard gameBoard) { int position; int i; i = GameBoardMark.EMPTY.index; do { position = (int) (Math.random() * GameBoard.TOTAL_SQUARES_PER_BOARD); if (gameBoard.mainBoard()[position] != GameBoardMark.EMPTY.index) continue; if (spotFinderCondition(gameBoard, position)) { i = GameBoardMark.OCCUPIED.index; } } while (i == GameBoardMark.EMPTY.index); return position; } private boolean spotFinderCondition(GameBoard gameBoard, int position) { return (position > 0 && gameBoard.mainBoard()[position - 1] != GameBoardMark.EMPTY.index) || (position > GameBoard.SQUARES_PER_SIDE && (gameBoard.mainBoard()[position - 11] != GameBoardMark.EMPTY.index || gameBoard.mainBoard()[position - GameBoard.SQUARES_PER_SIDE] != GameBoardMark.EMPTY.index || gameBoard.mainBoard()[position - GameBoard.oneLessThanCountInRow] != GameBoardMark.EMPTY.index)) || (position < 99 && gameBoard.mainBoard()[position + 1] != GameBoardMark.EMPTY.index) || (position < 88 && (gameBoard.mainBoard()[position + GameBoard.oneLessThanCountInRow] != GameBoardMark.EMPTY.index || gameBoard.mainBoard()[position + GameBoard.SQUARES_PER_SIDE] != GameBoardMark.EMPTY.index || gameBoard.mainBoard()[position + 11] != GameBoardMark.EMPTY.index)); } public GamePosition getNextComputerMove() { return nextComputerMove; } public GamePosition checkForWinOpportunity(GameBoardMark playerMark, int boardNumber) { GamePosition winner = blockSeriesOfFourOrMore(switchPlayers(playerMark), boardNumber, Mode.CHECK); if (winner.isNotNone()) { return winner; } GamePosition winnerCheck2 = responseTo3Or4InaRowOpportunity(switchPlayers(playerMark), boardNumber, Mode.CHECK); if (winnerCheck2.isNotNone()) { return winnerCheck2; } return GamePosition.nonePosition(); } private boolean isNotNone(int response) { return response != GameBoard.oneMoreThanLastPositionOnBoard; } public GamePosition checkSeries(GameBoardMark playerMark, int depth) { int[] auxilliaryBoard = new int[GameBoard.TOTAL_SQUARES_PER_BOARD]; GamePosition winningPosition; if (depth == GameBoard.MAX_DEPTH_FOR_TEMP_BOARD) return GamePosition.nonePosition(); setc4c(playerMark); for (int k = 0; k < GameBoard.TOTAL_SQUARES_PER_BOARD; k++) { if (StagingBoard.isEmptyAtPosition(k) || auxilliaryBoard[k] != GameBoardMark.EMPTY.index) continue; copyStagingBoardIntoOddGroupOfBoardsAtDepth(depth); auxilliaryBoard[k] = playerMark.index; winningPosition = checkForWinOpportunity(switchPlayers(playerMark), 2); if (winningPosition.isNone()) return GamePosition.nonePosition(); auxilliaryBoard[winningPosition.getRaw()] = switchPlayers(playerMark).index; if (blockSeriesOfFourOrMore(playerMark, 2, Mode.CHECK).isNotNone()) { return new GamePosition(k); } if (blockSeriesOfFourOrMore(switchPlayers(playerMark), 2, Mode.CHECK).isNotNone()) { auxilliaryBoard[k] = GameBoardMark.EMPTY.index; auxilliaryBoard[winningPosition.getRaw()] = GameBoardMark.EMPTY.index; copyIntoStagingBoardFromOddBoardGroupAtDepth(depth); continue; } if (checkSeries(playerMark, depth + 1) != GamePosition.nonePosition()) { return new GamePosition(k); } auxilliaryBoard[k] = GameBoardMark.EMPTY.index; auxilliaryBoard[winningPosition.getRaw()] = GameBoardMark.EMPTY.index; copyIntoStagingBoardFromOddBoardGroupAtDepth(depth); } return GamePosition.nonePosition(); } public GameBoardMark switchPlayers(GameBoardMark playerMark) { return GameBoardMark.valueOf(3 - playerMark.index); } public int countNumberOfAxesAlongWhichSeriesOfFourOccur(GameBoardMark playerMark, int x, int type) { int j, k, l; int zbir = 0; GameBoardMark flag, flag2; flag = GameBoardMark.EMPTY; for (j = 0; j < 10; j++) { for (l = 0; l < 6; l++) { marksByAxis.setPositionsToZero(0, 1, 2); for (k = 0; k < 5; k++) { marksByAxis.incrementValueAtPositionAndReturnValue(gameBoard.getValueAt(x, j * 10 + l + k).index); } if (getDOublt(playerMark)) { if (type == Mode.SAFE.rawMode) { flag2 = GameBoardMark.EMPTY; for (k = 0; k < 5; k++) { if (gameBoard.hasEmptyValueAt(x, j * 10 + l + k) && TemporaryChecksTable.tempTableForChecks[j * 10 + l + k] == GameBoardMark.OCCUPIED.index) { flag2 = GameBoardMark.OCCUPIED; } } if (flag2 == GameBoardMark.EMPTY) { zbir++; flag = GameBoardMark.OCCUPIED; break; } } else { zbir++; flag = GameBoardMark.OCCUPIED; break; } } } if (flag == GameBoardMark.OCCUPIED) break; } flag = GameBoardMark.EMPTY; for (j = 0; j < 10; j++) { for (l = 0; l < 6; l++) { marksByAxis.setPositionsToZero(0, 1, 2); for (k = 0; k < 5; k++) marksByAxis.incrementValueAtPosition(gameBoard.getValueAt(x, l * 10 + j + k * 10)); if (getDOublt(playerMark)) { if (type == Mode.SAFE.rawMode) { flag2 = GameBoardMark.EMPTY; for (k = 0; k < 5; k++) if (gameBoard.hasEmptyValueAt(x, l * 10 + j + k * 10) && TemporaryChecksTable.tempTableForChecks[l * 10 + j + k * 10] == GameBoardMark.OCCUPIED.index) flag2 = GameBoardMark.OCCUPIED; if (flag2 == GameBoardMark.EMPTY) { zbir++; flag = GameBoardMark.OCCUPIED; break; } } else { zbir++; flag = GameBoardMark.OCCUPIED; break; } } } if (flag == GameBoardMark.OCCUPIED) break; } flag = GameBoardMark.EMPTY; for (l = 0; l < 6; l++) { for (j = 0; j < 6; j++) { for (k = 0; k < 3; k++) /* za diag */ marksByAxis.setPositionsToZero(k); for (k = 0; k < 5; k++) /* diag\ */ marksByAxis.incrementValueAtPosition(gameBoard.getValueAt(x, l * 10 + j + k * 11)); if (getDOublt(playerMark)) { if (type == Mode.SAFE.rawMode) { flag2 = GameBoardMark.EMPTY; for (k = 0; k < 5; k++) { if (gameBoard.hasEmptyValueAt(x, l * 10 + j + k * 11) && TemporaryChecksTable.tempTableForChecks[l * 10 + j + k * 11] == GameBoardMark.OCCUPIED.index) { flag2 = GameBoardMark.OCCUPIED; } } if (flag2 == GameBoardMark.EMPTY) { zbir++; flag = GameBoardMark.OCCUPIED; break; } } else { zbir++; flag = GameBoardMark.OCCUPIED; break; } } } if (flag == GameBoardMark.OCCUPIED) break; } flag = GameBoardMark.EMPTY; for (l = 0; l < 6; l++) { for (j = 0; j < 6; j++) { for (k = 0; k < 3; k++) { marksByAxis.setPositionsToZero(k); } for (k = 0; k < 5; k++) { marksByAxis.incrementValueAtPosition(gameBoard.getValueAt(x, l * 10 + j - k * GameBoard.oneLessThanCountInRow + 40)); } if (getDOublt(playerMark)) { if (type == Mode.SAFE.rawMode) { flag2 = GameBoardMark.EMPTY; for (k = 0; k < 5; k++) { if (gameBoard.hasEmptyValueAt(x, l * 10 + j - k * GameBoard.oneLessThanCountInRow + 40) && TemporaryChecksTable.tempTableForChecks[l * 10 + j - k * GameBoard.oneLessThanCountInRow + 40] == GameBoardMark.OCCUPIED.index) { flag2 = GameBoardMark.OCCUPIED; } } if (flag2 == GameBoardMark.EMPTY) { zbir++; flag = GameBoardMark.OCCUPIED; break; } } else { zbir++; flag = GameBoardMark.OCCUPIED; break; } } } if (flag == GameBoardMark.OCCUPIED) break; } return zbir; } private boolean getDOublt(GameBoardMark playerMark) { return marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(playerMark, 4), new MarksByAxisPositionPair(GameBoardMark.EMPTY, 1)); } public void setc4c(GameBoardMark playerMark) { int j, k, l; int position, x = 2; // TODO make this Position object for (j = 0; j < GameBoard.TOTAL_SQUARES_PER_BOARD; j++) { StagingBoard.setValueAtPositionToEmpty(j); } int tempRowForChecks[] = new int[GameBoard.SQUARES_PER_SIDE]; for (j = 0; j < GameBoard.SQUARES_PER_SIDE; j++) { for (k = 0; k < 6; k++) { marksByAxis.setPositionsToZero(0, 1); for (l = 0; l < 5; l++) { position = gameBoard.getValueAt(x, j * GameBoard.SQUARES_PER_SIDE + k + l).index; if (position == playerMark.index) marksByAxis.incrementValueAtPosition(GameBoardMark.ZERO_MARK_FOR_COMPUTER); if (position == GameBoardMark.EMPTY.index) { tempRowForChecks[marksByAxis.getValueAtPosition(1)] = j * GameBoard.SQUARES_PER_SIDE + k + l; marksByAxis.incrementValueAtPositionAndReturnValue(1); } } if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 3), new MarksByAxisPositionPair(1, 2))) for (l = 0; l < 2; l++) StagingBoard.setValueAtPositionToOccupied(tempRowForChecks[l]); } } for (j = 0; j < GameBoard.SQUARES_PER_SIDE; j++) { for (k = 0; k < 6; k++) { marksByAxis.setPositionsToZero(0, 1); for (l = 0; l < 5; l++) { position = gameBoard.getValueAt(x, k * GameBoard.SQUARES_PER_SIDE + j + l * GameBoard.SQUARES_PER_SIDE).index; if (position == playerMark.index) marksByAxis.incrementValueAtPositionAndReturnValue(0); if (position == GameBoardMark.EMPTY.index) { tempRowForChecks[marksByAxis.getValueAtPosition(1)] = k * GameBoard.SQUARES_PER_SIDE + j + l * GameBoard.SQUARES_PER_SIDE; marksByAxis.incrementValueAtPositionAndReturnValue(1); } } if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 3), new MarksByAxisPositionPair(1, 2))) for (l = 0; l < 2; l++) StagingBoard.setValueAtPositionToOccupied(tempRowForChecks[l]); } } for (j = 0; j < 6; j++) { for (k = 0; k < 6; k++) { marksByAxis.setPositionsToZero(0, 1); for (l = 0; l < 5; l++) { position = gameBoard.getValueAt(x, j * GameBoard.SQUARES_PER_SIDE + k + l * 11).index; if (position == playerMark.index) marksByAxis.incrementValueAtPositionAndReturnValue(0); if (position == GameBoardMark.EMPTY.index) { tempRowForChecks[marksByAxis.getValueAtPosition(1)] = j * GameBoard.SQUARES_PER_SIDE + k + l * 11; marksByAxis.incrementValueAtPositionAndReturnValue(1); } } if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 3), new MarksByAxisPositionPair(1, 2))) for (l = 0; l < 2; l++) StagingBoard.setValueAtPositionToOccupied(tempRowForChecks[l]); } } for (j = 0; j < 6; j++) { for (k = 0; k < 6; k++) { marksByAxis.setPositionsToZero(0, 1); for (l = 0; l < 5; l++) { position = gameBoard.getValueAt(x, j * GameBoard.SQUARES_PER_SIDE + k - l * GameBoard.oneLessThanCountInRow + 40).index; if (position == playerMark.index) marksByAxis.incrementValueAtPositionAndReturnValue(0); if (position == GameBoardMark.EMPTY.index) { setValueInTempRowForChecksToCalculatedValue(j, k, l, tempRowForChecks); marksByAxis.incrementValueAtPositionAndReturnValue(1); } } if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 3), new MarksByAxisPositionPair(1, 2))) for (l = 0; l < 2; l++){ StagingBoard.setValueAtPositionToOccupied(tempRowForChecks[l]); } } } } private void setValueInTempRowForChecksToCalculatedValue(int j, int k, int l, int[] tempRowForChecks) { tempRowForChecks[marksByAxis.getValueAtPosition(1)] = j * GameBoard.SQUARES_PER_SIDE + k - l * GameBoard.oneLessThanCountInRow + 40; } public void seto4cc(GameBoardMark playerMark) { int j, k, l; int position; for (j = 0; j < GameBoard.TOTAL_SQUARES_PER_BOARD; j++) { StagingBoard.setValueAtPositionToEmpty(j); } int tempRowForChecks[] = new int[GameBoard.SQUARES_PER_SIDE]; for (j = 0; j < GameBoard.SQUARES_PER_SIDE; j++) { for (k = 0; k < 5; k++) { position = j * GameBoard.SQUARES_PER_SIDE + k; if (gameBoard.hasEmptyValueAtPositionOnBoardTwoAndPositionWithDiff(position, 5)) { marksByAxis.setPositionsToZero(0, 1); for (l = 1; l < 5; l++) { position = gameBoard.getValueAt(GameBoard.indexOfBoardTwo, j * GameBoard.SQUARES_PER_SIDE + k + l).index; if (position == playerMark.index) marksByAxis.incrementValueAtPositionAndReturnValue(0); if (position == GameBoardMark.EMPTY.index) { tempRowForChecks[marksByAxis.getValueAtPosition(1)] = j * GameBoard.SQUARES_PER_SIDE + k + l; marksByAxis.incrementValueAtPositionAndReturnValue(1); } } if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 2), new MarksByAxisPositionPair(1, 2))) for (l = 0; l < 2; l++) StagingBoard.setValueAtPositionToOccupied(tempRowForChecks[l]); } } } for (j = 0; j < GameBoard.SQUARES_PER_SIDE; j++) { for (k = 0; k < 5; k++) { position = k * GameBoard.SQUARES_PER_SIDE + j; if (gameBoard.hasEmptyValueAtPositionOnBoardTwoAndPositionWithDiff(position, 50)) { marksByAxis.setPositionsToZero(0, 1); for (l = 1; l < 5; l++) { position = gameBoard.getValueAt(GameBoard.indexOfBoardTwo, k * GameBoard.SQUARES_PER_SIDE + j + l * GameBoard.SQUARES_PER_SIDE).index; if (position == playerMark.index) marksByAxis.incrementValueAtPositionAndReturnValue(0); if (position == GameBoardMark.EMPTY.index) { tempRowForChecks[marksByAxis.getValueAtPosition(1)] = k * GameBoard.SQUARES_PER_SIDE + j + l * GameBoard.SQUARES_PER_SIDE; marksByAxis.incrementValueAtPositionAndReturnValue(1); } } if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 2), new MarksByAxisPositionPair(1, 2))) for (l = 0; l < 2; l++) StagingBoard.setValueAtPositionToOccupied(tempRowForChecks[l]); } } } newMethod(playerMark, tempRowForChecks, 1, 0, 50, 11); newMethod(playerMark, tempRowForChecks, -1, 50, 0, GameBoard.oneLessThanCountInRow); } private void newMethod(GameBoardMark playerMark, int[] tempRowForChecks, int sign, int foo, int bar, int baz) { for (int b1 = 0; b1 < 5; b1++) { for (int b2 = 0; b2 < 5; b2++) { int positionB = b1 * GameBoard.SQUARES_PER_SIDE + b2; if (gameBoard.hasEmptyValueAt(GameBoard.indexOfBoardTwo, positionB + foo) && gameBoard.hasEmptyValueAt(GameBoard.indexOfBoardTwo, positionB + bar + 5)) { marksByAxis.setPositionsToZero(0, 1); for (int b3 = 1; b3 < 5; b3++) { positionB = gameBoard.getValueAt(GameBoard.indexOfBoardTwo, b1 * GameBoard.SQUARES_PER_SIDE + b2 + sign * b3 * baz + foo).index; if (positionB == playerMark.index) marksByAxis.incrementValueAtPositionAndReturnValue(0); if (positionB == GameBoardMark.EMPTY.index) { tempRowForChecks[marksByAxis.getValueAtPosition(1)] = b1 * GameBoard.SQUARES_PER_SIDE + b2 + sign * b3 * baz + foo; marksByAxis.incrementValueAtPositionAndReturnValue(1); } } if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 2), new MarksByAxisPositionPair(1, 2))) for (int b4 = 0; b4 < 2; b4++) StagingBoard.setValueAtPositionToOccupied(tempRowForChecks[b4]); } } } } public GamePosition blockSeriesOfFourOrMore(GameBoardMark playerMark, int x, Mode type) { int j, k, l; GamePosition position = new GamePosition(); GamePosition position2 = new GamePosition(); int tempRowForChecks[] = new int[GameBoard.SQUARES_PER_SIDE]; for (l = 0; l < 6; l++) { for (j = 0; j < GameBoard.SQUARES_PER_SIDE; j++) { gameBoard.resetAllMarksAlongAxesForFirstHalfOfBoard(marksByAxis); position = checkFor5AlongHorizAxis(playerMark, x, j, l, position); if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 3), new MarksByAxisPositionPair(1, 2))) { if (type.equals(Mode.SETFLAGS)) { TemporaryChecksTable.tempTableForChecks[tempRowForChecks[0]] = GameBoardMark.OCCUPIED.index; TemporaryChecksTable.tempTableForChecks[tempRowForChecks[1]] = GameBoardMark.OCCUPIED.index; } if (type.equals(Mode.CLEAN)) return new GamePosition(tempRowForChecks[0]); } if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 4), new MarksByAxisPositionPair(1, 1)) && type.equals(Mode.CHECK)) return position; position = checkFor5AlongVertAxis(playerMark, x, j, l, position); if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(2, 3), new MarksByAxisPositionPair(3, 2))) { if (type.equals(Mode.SETFLAGS)) { TemporaryChecksTable.tempTableForChecks[tempRowForChecks[0]] = GameBoardMark.OCCUPIED.index; TemporaryChecksTable.tempTableForChecks[tempRowForChecks[1]] = GameBoardMark.OCCUPIED.index; } if (type.equals(Mode.CLEAN)) return new GamePosition(tempRowForChecks[0]); } if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(2, 4), new MarksByAxisPositionPair(3, 1)) && type.equals(Mode.CHECK)) return position; } for (j = 0; j < 6; j++) { gameBoard.resetAllMarksAlongAxesForFirstHalfOfBoard(marksByAxis); for (k = 0; k < 5; k++) { position = checkFor5AlongDiagDownRightAxis(playerMark, x, j, k, l, position); position2 = checkFor5AlongDiagUpRightAxis(playerMark, x, j, k, l, position2); } if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 3), new MarksByAxisPositionPair(1, 2))) { if (type.equals(Mode.SETFLAGS)) { TemporaryChecksTable.tempTableForChecks[tempRowForChecks[0]] = GameBoardMark.OCCUPIED.index; TemporaryChecksTable.tempTableForChecks[tempRowForChecks[1]] = GameBoardMark.OCCUPIED.index; } if (type.equals(Mode.CLEAN)) return new GamePosition(tempRowForChecks[0]); } if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 4), new MarksByAxisPositionPair(1, 1)) && type.equals(Mode.CHECK)) return position; if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(2, 3), new MarksByAxisPositionPair(3, 2))) { if (type.equals(Mode.SETFLAGS)) { TemporaryChecksTable.tempTableForChecks[tempRowForChecks[0]] = GameBoardMark.OCCUPIED.index; TemporaryChecksTable.tempTableForChecks[tempRowForChecks[1]] = GameBoardMark.OCCUPIED.index; } if (type.equals(Mode.CLEAN)) return new GamePosition(tempRowForChecks[0]); } if (marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(2, 4), new MarksByAxisPositionPair(3, 1)) && type.equals(Mode.CHECK)) return position2; } } return GamePosition.nonePosition(); } public GamePosition checkFor5AlongDiagUpRightAxis(GameBoardMark playerMark, int x, int j, int k, int l, GamePosition position2) { if (gameBoard.valueAtPositionMatches(x, l * GameBoard.SQUARES_PER_SIDE + j - k * GameBoard.oneLessThanCountInRow + 40, playerMark)) marksByAxis.incrementValueAtPositionAndReturnValue(2); int tempRowForChecks[] = new int[GameBoard.SQUARES_PER_SIDE]; if (gameBoard.hasEmptyValueAt(x, l * GameBoard.SQUARES_PER_SIDE + j - k * GameBoard.oneLessThanCountInRow + 40)) { position2 = new GamePosition(l * GameBoard.SQUARES_PER_SIDE + j - k * GameBoard.oneLessThanCountInRow + 40); tempRowForChecks[marksByAxis.getValueAtPosition(3)] = position2.getRaw(); marksByAxis.incrementValueAtPosition(3); } return position2; } public GamePosition checkFor5AlongDiagDownRightAxis(GameBoardMark playerMark, int x, int j, int k, int l, GamePosition position) { if (gameBoard.valueAtPositionMatches(x, l * GameBoard.SQUARES_PER_SIDE + j + k * 11, playerMark)) marksByAxis.incrementValueAtPositionAndReturnValue(0); int tempRowForChecks[] = new int[GameBoard.SQUARES_PER_SIDE]; if (gameBoard.hasEmptyValueAt(x, l * GameBoard.SQUARES_PER_SIDE + j + k * 11)) { position = new GamePosition(l * GameBoard.SQUARES_PER_SIDE + j + k * 11); tempRowForChecks[marksByAxis.getValueAtPosition(1)] = position.getRaw(); marksByAxis.incrementValueAtPositionAndReturnValue(1); } return position; } public GamePosition checkFor5AlongVertAxis(GameBoardMark playerMark, int x, int j, int l, GamePosition position) { int k; int tempRowForChecks[] = new int[GameBoard.SQUARES_PER_SIDE]; for (k = 0; k < 5; k++) { if (gameBoard.valueAtPositionMatches(x, l * GameBoard.SQUARES_PER_SIDE + j + k * GameBoard.SQUARES_PER_SIDE, playerMark)) marksByAxis.incrementValueAtPositionAndReturnValue(2); else if (gameBoard.hasEmptyValueAt(x, l * GameBoard.SQUARES_PER_SIDE + j + k * GameBoard.SQUARES_PER_SIDE)) { position = new GamePosition(GameBoard.SQUARES_PER_SIDE * l + j + k * GameBoard.SQUARES_PER_SIDE); tempRowForChecks[marksByAxis.getValueAtPosition(3)] = position.getRaw(); marksByAxis.incrementValueAtPosition(3); } else break; } return position; } public GamePosition checkFor5AlongHorizAxis(GameBoardMark playerMark, int x, int j, int l, GamePosition position) { int k; int tempRowForChecks[] = new int[GameBoard.SQUARES_PER_SIDE]; for (k = 0; k < 5; k++) { if (gameBoard.valueAtPositionMatches(x, j * GameBoard.SQUARES_PER_SIDE + l + k, playerMark)) marksByAxis.incrementValueAtPositionAndReturnValue(0); else if (gameBoard.hasEmptyValueAt(x, j * GameBoard.SQUARES_PER_SIDE + l + k)) { position = new GamePosition(GameBoard.SQUARES_PER_SIDE * j + l + k); tempRowForChecks[marksByAxis.getValueAtPosition(1)] = position.getRaw(); marksByAxis.incrementValueAtPositionAndReturnValue(1); } else break; } return position; } public GamePosition responseTo3Or4InaRowOpportunity(GameBoardMark playerMark, int boardLevel, Mode type) { int j, k, l; GamePosition place = new GamePosition(); int tempRowForChecks[] = new int[GameBoard.SQUARES_PER_SIDE]; for (k = 0; k < 4; k++) { tempRowForChecks[k] = 0; } for (l = 0; l < 5; l++) { for (j = 0; j < GameBoard.SQUARES_PER_SIDE; j++) { clearMarksByAxisArray(); if (gameBoard.hasEmptyValueAt(boardLevel, j * GameBoard.SQUARES_PER_SIDE + l) && gameBoard.hasEmptyValueAt(boardLevel, j * GameBoard.SQUARES_PER_SIDE + l + 5)) { place = checkForHoriz4InRow(playerMark, boardLevel, j, l); if (anyHoriz4MatchToMark(type, place)) return place; } if (gameBoard.hasEmptyValueAt(boardLevel, l * GameBoard.SQUARES_PER_SIDE + j) && gameBoard.hasEmptyValueAt(boardLevel, l * GameBoard.SQUARES_PER_SIDE + j + 50)) { place = checkForVert4InRow(playerMark, boardLevel, j, l); if (anyVert4MatchToMark(type, place)) return place; } } for (j = 0; j < 5; j++) { clearMarksByAxisArray(); if (gameBoard.hasEmptyValueAt(boardLevel, l * GameBoard.SQUARES_PER_SIDE + j) && gameBoard.hasEmptyValueAt(boardLevel, l * GameBoard.SQUARES_PER_SIDE + j + 55)) { place = checkForDiagDown4InRow(playerMark, boardLevel, j, l); if (anyDiagDown4MatchToMark(type, place)) return place; } if (gameBoard.hasEmptyValueAt(boardLevel, l * GameBoard.SQUARES_PER_SIDE + j + 50) && gameBoard.hasEmptyValueAt(boardLevel, l * GameBoard.SQUARES_PER_SIDE + j + 5)) { place = checkForDiagUp4InRow(playerMark, boardLevel, j, l); if (anyDiagUp4MatchToMark(type, place)) return place; } } } if (type.equals(Mode.COUNT)) { return new GamePosition(tempRowForChecks[0] + tempRowForChecks[1] + tempRowForChecks[2] + tempRowForChecks[3]); } return GamePosition.nonePosition(); } public GamePosition checkForHoriz4InRow(GameBoardMark playerMark, int boardLevel, int j, int l) { /* horiz */ int place = GameBoard.oneMoreThanLastPositionOnBoard; int k; for (k = 1; k < 5; k++) { if (gameBoard.valueAtPositionMatches(boardLevel, j * GameBoard.SQUARES_PER_SIDE + l + k, playerMark)) marksByAxis.incrementValueAtPositionAndReturnValue(0); else if (gameBoard.hasEmptyValueAt(boardLevel, j * GameBoard.SQUARES_PER_SIDE + l + k)) { place = GameBoard.SQUARES_PER_SIDE * j + l + k; marksByAxis.incrementValueAtPositionAndReturnValue(1); } else break; } return new GamePosition(place); } public GamePosition checkForVert4InRow(GameBoardMark playerMark, int boardLevel, int j, int l) { int place = GameBoard.oneMoreThanLastPositionOnBoard; int k; for (k = 1; k < 5; k++) { if (gameBoard.valueAtPositionMatches(boardLevel, l * GameBoard.SQUARES_PER_SIDE + j + k * GameBoard.SQUARES_PER_SIDE, playerMark)) marksByAxis.incrementValueAtPositionAndReturnValue(2); else if (gameBoard.hasEmptyValueAt(boardLevel, l * GameBoard.SQUARES_PER_SIDE + j + k * GameBoard.SQUARES_PER_SIDE)) { place = GameBoard.SQUARES_PER_SIDE * l + j + k * GameBoard.SQUARES_PER_SIDE; marksByAxis.incrementValueAtPosition(3); } else break; } return new GamePosition(place); } public GamePosition checkForDiagDown4InRow(GameBoardMark playerMark, int boardLevel, int j, int l) { GamePosition place = GamePosition.nonePosition(); int k; for (k = 1; k < 5; k++) { if (gameBoard.valueAtPositionMatches(boardLevel, l * GameBoard.SQUARES_PER_SIDE + j + k * 11, playerMark)) marksByAxis.incrementValueAtPositionAndReturnValue(0); if (gameBoard.hasEmptyValueAt(boardLevel, l * GameBoard.SQUARES_PER_SIDE + j + k * 11)) { place = new GamePosition(l * GameBoard.SQUARES_PER_SIDE + j + k * 11); marksByAxis.incrementValueAtPositionAndReturnValue(1); } } return place; } public GamePosition checkForDiagUp4InRow(GameBoardMark playerMark, int boardLevel, int j, int l) { GamePosition place = GamePosition.nonePosition(); int k; for (k = 1; k < 5; k++) { if (gameBoard.valueAtPositionMatches(boardLevel, l * GameBoard.SQUARES_PER_SIDE + j - k * GameBoard.oneLessThanCountInRow + 50, playerMark)) marksByAxis.incrementValueAtPosition(2); if (gameBoard.valueAtPositionMatches(boardLevel, l * GameBoard.SQUARES_PER_SIDE + j - k * GameBoard.oneLessThanCountInRow + 50, GameBoardMark.EMPTY)) { place = new GamePosition(l * GameBoard.SQUARES_PER_SIDE + j - k * GameBoard.oneLessThanCountInRow + 50); marksByAxis.incrementValueAtPosition(3); } } return place; } public boolean anyDiagUp4MatchToMark(Mode type, GamePosition place) { boolean match = false; int tempRowForChecks[] = new int[GameBoard.SQUARES_PER_SIDE]; if (!type.equals(Mode.CLEAN) && marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(2, 3), new MarksByAxisPositionPair(3, 1))) { tempRowForChecks[3] = 1; if (type.equals(Mode.CHECK)) { match = true; } if (type.equals(Mode.SETFLAGS)) TemporaryChecksTable.tempTableForChecks[place.getRaw()] = GameBoardMark.OCCUPIED.index; } if (type.equals(Mode.CLEAN) && marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(2, 2), new MarksByAxisPositionPair(3, 2))) { match = true; } return match; } public boolean anyDiagDown4MatchToMark(Mode type, GamePosition place) { boolean match = false; int tempRowForChecks[] = new int[GameBoard.SQUARES_PER_SIDE]; if (!type.equals(Mode.CLEAN) && marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 3), new MarksByAxisPositionPair(1, 1))) { tempRowForChecks[2] = 1; if (type.equals(Mode.CHECK)) { match = true; } if (type.equals(Mode.SETFLAGS)) TemporaryChecksTable.tempTableForChecks[place.getRaw()] = GameBoardMark.OCCUPIED.index; } if (type.equals(Mode.CLEAN) && marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 2), new MarksByAxisPositionPair(1, 2))) { match = true; } return match; } public boolean anyVert4MatchToMark(Mode type, GamePosition place) { boolean match = false; int tempRowForChecks[] = new int[GameBoard.SQUARES_PER_SIDE]; if (!type.equals(Mode.CLEAN) && marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(2, 3), new MarksByAxisPositionPair(3, 1))) { tempRowForChecks[1] = 1; if (type.equals(Mode.CHECK)) { match = true; } if (type.equals(Mode.SETFLAGS)) TemporaryChecksTable.tempTableForChecks[place.getRaw()] = GameBoardMark.OCCUPIED.index; } if (type.equals(Mode.CLEAN) && marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(2, 2), new MarksByAxisPositionPair(3, 2))) { match = true; } return match; } public boolean anyHoriz4MatchToMark(Mode type, GamePosition gamePosition) { int tempRowForChecks[] = new int[GameBoard.SQUARES_PER_SIDE]; if (!type.equals(Mode.CLEAN) && marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 3), new MarksByAxisPositionPair(1, 1))) { tempRowForChecks[0] = 1; if (type.equals(Mode.CHECK)) { return true; } if (type.equals(Mode.SETFLAGS)) TemporaryChecksTable.tempTableForChecks[gamePosition.getRaw()] = GameBoardMark.OCCUPIED.index; } if (type.equals(Mode.CLEAN) && marksByAxis.valueAtPositionPairsMatch(new MarksByAxisPositionPair(0, 2), new MarksByAxisPositionPair(1, 2))) { return true; } return false; } public void setFlagsForLaterProcessing(GameBoardMark playerMark) { int k; for (k = 0; k < GameBoard.TOTAL_SQUARES_PER_BOARD; k++) TemporaryChecksTable.tempTableForChecks[k] = GameBoardMark.EMPTY.index; blockSeriesOfFourOrMore(playerMark, 0, Mode.SETFLAGS); responseTo3Or4InaRowOpportunity(playerMark, 0, Mode.SETFLAGS); } public void copyIntoStagingBoardFromOddBoardGroupAtDepth(int depth) { for (int k = 0; k < GameBoard.TOTAL_SQUARES_PER_BOARD; k++) StagingBoard.setValueAt(k, TemporaryBoardHolder.getValueAt(depth, k)); } public void copyStagingBoardIntoOddGroupOfBoardsAtDepth(int depth) { for (int k = 0; k < GameBoard.TOTAL_SQUARES_PER_BOARD; k++) { TemporaryBoardHolder.setValueAt(depth, k, StagingBoard.getValueAt(k)); } } void copyBoardToCheck(int indexForBoardToCheck) { for (int j = 0; j < GameBoard.TOTAL_SQUARES_PER_BOARD; j++) { gameBoard.setValueAt(1, j, gameBoard.getValueAt(indexForBoardToCheck, j)); } } void clearMarksByAxisArray() { for (int k = 0; k < 4; k++) { marksByAxis.setPositionsToZero(k); } } }
966cbff08b506d287a0c8070de9217e7278aaff6
4116230b16e2b74ca0efe9992e5db81b8f451bc0
/.svn/pristine/96/966cbff08b506d287a0c8070de9217e7278aaff6.svn-base
60d7b8f4f463ca26735a931d9587fd927908508a
[]
no_license
folksuperior/123
2e4d2fe79b870feca41d30993d14e59b3222a209
0844ba3373ec17bff8b7a9df1fb95724061fb2a7
refs/heads/master
2021-01-20T08:19:46.315561
2017-03-04T15:17:59
2017-03-04T15:17:59
83,903,761
0
0
null
null
null
null
UTF-8
Java
false
false
1,591
/** * */ package cn.yin.jx.domain; import java.util.HashSet; import java.util.Set; /** * @Description: * @author: 尹成功 * @version: 1.0 * @Company: http://java.itcast.cn * @date: 2017年2月18日 */ public class User extends BaseEntity{ //用户编号 private String id; //部门编号 //用户与部门,是多对一的关系 private Dept dept; //用户姓名 private String userName; //密码 private String password; //状态 0 禁用 1 启用 private Integer state; //用户扩展信息 private UserInfo userInfo; private Set<Role> roles = new HashSet(); public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } public String getId() { return id; } public void setId(String id) { this.id = id; } public Dept getDept() { return dept; } public void setDept(Dept dept) { this.dept = dept; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public UserInfo getUserInfo() { return userInfo; } public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; } }
[ "Administrator@Peter" ]
Administrator@Peter
d541dc021c640ab948e0a61bef89522954505816
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/commonsguy--cw-omnibus/517cd987692133bae30ed58fb60a43998ccd4f2f/before/StringConcatActivity.java
ecba08bce6ec7c10e564537e02cf6f3a0ef913f2
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
1,245
java
/*** Copyright (c) 2011 CommonsWare, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. From _Tuning Android Applications_ https://commonsware.com/AndTuning */ package com.commonsware.android.traceview; import android.view.View; import android.widget.TextView; public class StringConcatActivity extends BaseActivity { StringConcatTask createTask(TextView msg, View v) { return(new StringConcatTask(msg, v)); } class StringConcatTask extends BaseTask { StringConcatTask(TextView msg, View v) { super(msg, v); } protected String doTest() { String result="This is a string"; result+=" -- that varies --"; result+=" and also has "; result+=String.valueOf(4); result+=" hyphens in it"; return(result); } } }
5aa2a54deb9eb037347853166af1409a18db85a7
91028fd1353f81bbf80dec58927414c2e438afd9
/spring_rest/src/main/java/com/ustglobal/spring_rest/dto/EmployeeBean.java
5e6691265bf828f75eaf289aa49f0917128aaac1
[]
no_license
C-karthik/USTGlobal-16SEP19-c-karthik
02ab00221c6eb901a1ee1a3ac734ae5950b2a506
98e48b274ae3cb9964b70d2b3ab6a9e6d5e80c96
refs/heads/master
2023-01-09T18:10:22.875429
2019-12-21T16:48:27
2019-12-21T16:48:27
215,541,133
0
0
null
2023-01-07T17:47:15
2019-10-16T12:19:51
JavaScript
UTF-8
Java
false
false
1,247
java
package com.ustglobal.spring_rest.dto; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonFormat; @Entity @Table(name = "employeerestapi") public class EmployeeBean { @Id @Column @GeneratedValue private int id; @Column private String name; @Column private String email; @Column private String password; @Column @JsonFormat(pattern = "yyyy-MM-dd") private Date doj; @Column private String gender; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getDoj() { return doj; } public void setDoj(Date doj) { this.doj = doj; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } }
54150af7eef102b8f20377a2ddb37cca5dd92498
46aa2e79d1acb5266a49dacde6f91b763af21284
/Pelicula/PeliculaBase.java
401c12b42396e1fb0dec1e9f4fb777aaf7fa2ce3
[]
no_license
GustavoEstay/EggCollections
dcec2f37ba4eb9916870376cb0b52f9ca8d725d6
e50b5cee74059fe8969ef3bc96f540bd20eed458
refs/heads/main
2023-09-03T21:00:10.512191
2021-11-20T23:27:56
2021-11-20T23:27:56
430,228,756
0
0
null
null
null
null
UTF-8
Java
false
false
2,100
java
/* * 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 Pelicula; import PeliculaService.PeliculaService; import java.util.Scanner; /** * * @author Gustavo */ public class PeliculaBase { /** * @param args the command line arguments */ public static void main(String[] args) { //// En el main deberemos tener un bucle que crea un objeto Pelicula pidiéndole al //usuario todos sus datos y guardándolos en el objeto Pelicula. //Después, esa Pelicula se guarda una lista de Peliculas y se le pregunta al usuario //si quiere crear otra Pelicula o no. PeliculaService ps = new PeliculaService(); int opcion; Scanner leer; leer = new Scanner(System.in).useDelimiter("\n"); System.out.println("Bienvenidx"); System.out.println("Qué desea hacer?"); System.out.println(" 1) Cargar películas en el sistema"); System.out.println(" 2) Salir"); opcion = leer.nextInt(); do { switch (opcion) { case 1: ps.crearPelicula(); System.out.println("Está seguro de querer dejar de cargar Películas?"); System.out.println(" 1)No"); System.out.println(" 2)Si"); opcion=leer.nextInt(); break; case 2: System.out.println("Muchas Gracias"); break; default: System.out.println("Opción no válida"); } } while (opcion == 1); ps.mostrarPeliculas(); System.out.println(""); ps.largometrajes(); System.out.println(""); ps.peliculasDeMayorAMenor(); System.out.println(""); ps.peliculasDeMenorAMayor(); System.out.println(""); ps.peliculasPorTitulo(); System.out.println(""); ps.peliculasPorDirector(); } }
228cbe8138d3fb5d34633101a9c1430575ec5d94
1836c081e466a6034f4b59866d22c0d18e204c3d
/SQLite/app/src/main/java/com/example/sqlite/DataHelper.java
dc63f01435c38b2f3061537069a0d5b5c55d4cd2
[ "MIT" ]
permissive
shdx8/E31190672_Elyas_Agus_Suhadak_A
042a3b6eb7c984d3b8f94b676fe9b04d1ebe8d22
71a93a029d885fbdeb43f1e1fe22d0b4e0dcea70
refs/heads/main
2023-06-15T23:55:21.853440
2021-07-11T16:48:38
2021-07-11T16:48:38
345,973,505
0
0
null
null
null
null
UTF-8
Java
false
false
1,106
java
package com.example.sqlite; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DataHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "biodatadiri.db"; private static final int DATABASE_VERSION = 1; public DataHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub String sql = "create table biodata(no integer primary key, nama text null, tgl text null, jk text null, alamat text null);"; Log.d("Data", "onCreate: " + sql); db.execSQL(sql); sql = "INSERT INTO biodata (no, nama, tgl, jk, alamat) VALUES ('1', 'test', '2021-04-23', 'Laki-Laki','Probolinggo');"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { // TODO Auto-generated method stub } }
fbd84b006ed8fe16d8e41d3f7b6fbffcc6638996
404475cfd3471e197b4a6637398a0ffcdc0c2904
/app/src/main/java/com/yiaosi/aps/adapter/WorkbenchItemAdapter.java
19289d903f85d67ca78279f0c625db2694069114
[]
no_license
Lion2003/APSDemo
826d0752323ec0e9c55b69f49c061d3c936d29f7
b8c2f32140d48836d90dcc17eba4b185c35ac236
refs/heads/master
2021-01-01T20:31:19.390078
2017-12-27T16:13:19
2017-12-27T16:13:19
98,874,696
0
0
null
null
null
null
UTF-8
Java
false
false
8,641
java
package com.yiaosi.aps.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.yiaosi.aps.R; import com.yiaosi.aps.entity.WorkbenchItem; import java.util.List; /** * Created by Administrator on 2017-06-05. */ public class WorkbenchItemAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int TITLE = 0; private static final int ITEM1 = 1; private static final int ITEM2 = 2; private static final int ITEM3 = 3; private Context context; private List<WorkbenchItem> list; private LayoutInflater mLayoutInflater; private OnMyClickListener onMyClickListener; public WorkbenchItemAdapter(Context context, List<WorkbenchItem> list) { this.context = context; this.list = list; this.mLayoutInflater = LayoutInflater.from(context); } public interface OnMyClickListener { void onClick(View view, int position, String pic, String isShow); } public void setOnMyClickListener(OnMyClickListener onMyClickListener) { this.onMyClickListener = onMyClickListener; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if(viewType == TITLE) { return new HeaderViewHolder(mLayoutInflater.inflate(R.layout.em_workbench_header, parent, false)); } else if(viewType == ITEM1) { return new Item1ViewHolder(mLayoutInflater.inflate(R.layout.em_workbench_itemtype1, parent, false)); } else if(viewType == ITEM2) { return new Item2ViewHolder(mLayoutInflater.inflate(R.layout.em_workbench_itemtype2, parent, false)); } else if(viewType == ITEM3) { return new Item3ViewHolder(mLayoutInflater.inflate(R.layout.em_workbench_itemtype3, parent, false)); } return null; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { if(holder instanceof HeaderViewHolder) { ((HeaderViewHolder)holder).item0.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onMyClickListener.onClick(v, 0, "", "-1"); } }); ((HeaderViewHolder)holder).item1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onMyClickListener.onClick(v, 1, "", "-1"); } }); ((HeaderViewHolder)holder).item2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onMyClickListener.onClick(v, 2, "", "-1"); } }); ((HeaderViewHolder)holder).item3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onMyClickListener.onClick(v, 3, "", "-1"); } }); } else if( holder instanceof Item1ViewHolder) { if(position == 1) { ((Item1ViewHolder)holder).title.setText("今日紧急未处理单"); } else if(position == getItemCount() - 2) { ((Item1ViewHolder)holder).title.setText("今日任务事项"); } } else if(holder instanceof Item2ViewHolder) { // ((RemindNoticeAdapter.ItemViewHolder)holder).relativeLayout.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // onMyClickListener.onClick(v); // } // }); ((Item2ViewHolder)holder).linearLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onMyClickListener.onClick(v, 4, list.get(position - 2).getPic(), list.get(position - 2).getIsFinish()); } }); ((Item2ViewHolder)holder).customerName.setText("客户名称:" + list.get(position - 2).getCustomerName()); if(list.get(position - 2).getIsFinish().equals("1")) { ((Item2ViewHolder)holder).jindu.setText("已处理"); ((Item2ViewHolder)holder).jindu.setTextColor(context.getResources().getColor(R.color.color_808080)); } else { ((Item2ViewHolder)holder).jindu.setText("未处理"); ((Item2ViewHolder)holder).jindu.setTextColor(context.getResources().getColor(R.color.color_e24a4a)); } Glide.with(context).load(list.get(position - 2).getPic()).into(((Item2ViewHolder)holder).img); ((Item2ViewHolder)holder).ewi_productOrderNum.setText(list.get(position - 2).getProductOrderNum()); ((Item2ViewHolder)holder).ewi_clientDate.setText(list.get(position - 2).getCustomerDate()); ((Item2ViewHolder)holder).ewi_styleNum.setText(list.get(position - 2).getStyleNum()); ((Item2ViewHolder)holder).ewi_color.setText(list.get(position - 2).getColor()); ((Item2ViewHolder)holder).ewi_number.setText("数量 " + list.get(position - 2).getNum()); } else if(holder instanceof Item3ViewHolder) { } } @Override public int getItemViewType(int position) { if(position == 0) { return TITLE; } else if(position == 1 || position == getItemCount() - 2) { return ITEM1; } else if(position == getItemCount() - 1) { return ITEM3; } else { return ITEM2; } } @Override public int getItemCount() { return list.size() + 4; } public class HeaderViewHolder extends RecyclerView.ViewHolder { private LinearLayout item0, item1, item2, item3; public HeaderViewHolder(View itemView) { super(itemView); item0 = (LinearLayout) itemView.findViewById(R.id.ewh_item0); item1 = (LinearLayout) itemView.findViewById(R.id.ewh_item1); item2 = (LinearLayout) itemView.findViewById(R.id.ewh_item2); item3 = (LinearLayout) itemView.findViewById(R.id.ewh_item3); } } public class Item1ViewHolder extends RecyclerView.ViewHolder { private TextView title; public Item1ViewHolder(View itemView) { super(itemView); title = (TextView) itemView.findViewById(R.id.ewi_title); } } public class Item2ViewHolder extends RecyclerView.ViewHolder { private LinearLayout linearLayout; private TextView customerName; private ImageView img; private TextView ewi_productOrderNum; private TextView ewi_clientDate; private TextView ewi_styleNum; private TextView ewi_color; private TextView ewi_number; private TextView jindu; public Item2ViewHolder(View itemView) { super(itemView); linearLayout = (LinearLayout) itemView.findViewById(R.id.ewi_LinearLayout); customerName = (TextView) itemView.findViewById(R.id.ewi_tvClientName); img = (ImageView) itemView.findViewById(R.id.ewi_pic); jindu = (TextView) itemView.findViewById(R.id.jindu); ewi_productOrderNum = (TextView) itemView.findViewById(R.id.ewi_productOrderNum); ewi_clientDate = (TextView) itemView.findViewById(R.id.ewi_clientDate); ewi_styleNum = (TextView) itemView.findViewById(R.id.ewi_styleNum); ewi_color = (TextView) itemView.findViewById(R.id.ewi_color); ewi_number = (TextView) itemView.findViewById(R.id.ewi_number); } } public class Item3ViewHolder extends RecyclerView.ViewHolder { private TextView tv1; private TextView tv2; private TextView tv3; private TextView tv4; private TextView tv5; public Item3ViewHolder(View itemView) { super(itemView); tv1 = (TextView) itemView.findViewById(R.id.ewi_1); tv2 = (TextView) itemView.findViewById(R.id.ewi_2); tv3 = (TextView) itemView.findViewById(R.id.ewi_3); tv4 = (TextView) itemView.findViewById(R.id.ewi_4); tv5 = (TextView) itemView.findViewById(R.id.ewi_5); } } }
4d3343955ffbef9ac80e53de13d8476edebf8f8d
c278b35c634af62b8f28b33b8c81dcb6581ab918
/DataStruct/src/Test/datastruct/linked/LinkedQueueTest.java
31e955efc916c4a9fe13e7a5062ec33cb4e308a8
[ "Apache-2.0" ]
permissive
PineDx/Java_Datastruct
65bcfc61bffe8c3fe636c4e4518e5451b9f1ca09
c06abb21437edb4ce8a50987538da6bb21f2c95a
refs/heads/master
2023-03-07T03:28:48.025226
2021-02-23T15:39:37
2021-02-23T15:39:37
310,223,258
0
0
Apache-2.0
2021-02-23T15:39:38
2020-11-05T07:38:14
Java
UTF-8
Java
false
false
960
java
package Test.datastruct.linked; import algorithm.datastruct.Queue.linkedQueue.LinkedQueue; /** * <功能简述> * <功能详细描述> * * @Author: Songlin * @create: 2020/11/14-19:27 */ public class LinkedQueueTest { public static void main(String[] args) { LinkedQueue linkedQueue = new LinkedQueue(); linkedQueue.enqueue(1); linkedQueue.enqueue(2); linkedQueue.enqueue(3); System.out.println("size:"+linkedQueue.getSize()); System.out.println("QueueFront:"+linkedQueue.dequeue()+"\tout"); linkedQueue.enqueue(4); System.out.println("QueueFront:"+linkedQueue.dequeue()+"\tout"); System.out.println("QueueFront:"+linkedQueue.getFront()+"\t scan"); System.out.println("QueueFront:"+linkedQueue.dequeue()+"\tout"); System.out.println("QueueFront:"+linkedQueue.dequeue()+"\tout"); System.out.println("QueueFront:"+linkedQueue.dequeue()+"\tout"); } }
[ "xurenzealiyun.com" ]
xurenzealiyun.com
c5b5f6bf2cd49df58ecf241ab462320924a36c45
326567ec5d960a0cc2b8ede0a34aaaf0c0ea94fe
/src/main/java/com/recommend/web/controller/ApplicationController.java
d917fc255d1bc19f2ef7f4f99701928b82541023
[]
no_license
Mozgh/RecommendTool
0a2b3f11b0820c6adb6f664d5a1ea0e3e6613c9e
e4a94a3302819faa064e6f4c9abc8c0dd2f2b166
refs/heads/master
2020-03-10T12:21:24.831733
2018-06-05T07:48:26
2018-06-05T07:48:26
129,376,265
0
0
null
null
null
null
UTF-8
Java
false
false
1,014
java
package com.recommend.web.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** * Created by feir4 on 2018/5/12. */ public class ApplicationController { @Autowired protected HttpServletRequest request; @Autowired protected HttpServletResponse response; protected ModelAndView buildMAV(String page) { return buildMAV(page, "index"); } public ModelAndView buildMAV(String page, String layout) { ModelAndView mav = new ModelAndView(layout); mav.addObject("view", page); Map<String, String> requestContext = new HashMap<>(); requestContext.put("contextPath", request.getContextPath()); mav.addObject("rc", requestContext); mav.addObject("contextPath", request.getContextPath()); return mav; } }
ba8bffa612c0574491e88bf3262acd38f6c34311
6facc6cc414ddaafa5f7bfe00d71a743b9dfe928
/ece558project3_release/app/src/androidTest/java/com/example/hiral/myapplication/ApplicationTest.java
cb78e05d3d6f395f2009c5d0b180360472e3fe48
[]
no_license
hrishikesh988/CoffeeMaker
1bfee6be258e79912dae7df8a6964f9d70d17bad
645bc52d758bd702663785f0262862134ab75b5b
refs/heads/master
2021-06-08T17:43:01.766413
2016-12-02T06:06:29
2016-12-02T06:06:29
74,104,219
0
0
null
null
null
null
UTF-8
Java
false
false
374
java
package com.example.hiral.myapplication; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
0aa8e8c2d8254a9c43c7cf19b9376399b07c4edf
2c039978fb2e427b0bab0453923a0b66a98d840c
/src/main/java/framework/annotation/Aspect.java
aabc7ba2111c7c4eff79e5cf1d2ce2f9e5f809d5
[]
no_license
haizi1996/MVC-framework
8a5411621e38c82cf80c059b67e7a9b13face56f
c630eac2c5fc08b8a4f844ea76fe5a856e11e795
refs/heads/master
2021-01-01T17:09:13.422634
2018-12-15T12:43:42
2018-12-15T12:43:42
98,013,802
0
0
null
null
null
null
UTF-8
Java
false
false
480
java
package framework.annotation; import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Aspect { Class<? extends Annotation>[] targetClass(); //目标类 /** *代理类的第几层,数值越小离目标类越近 */ int order() default 1; }
9265842d0d110c1ea4e5f2c9736810c9b495c6da
2c7084b4000738fa1e6b09df9a950ce8fc323e00
/projetoSuap/src/main/java/br/edu/ifrn/jeferson/dto/MeusDados.java
6d4696ca4ad47c972ba11ffadf7b380797b82bfc
[]
no_license
JefersonQueiroga/ClientApiSuap
895578778146b6fcf33ae9622fd3513aee8faf22
dae77ec757c4fcbebd57ea38e23928208c40d13d
refs/heads/master
2020-07-31T05:08:52.584511
2019-09-24T02:30:30
2019-09-24T02:30:30
210,494,315
0
0
null
null
null
null
UTF-8
Java
false
false
2,467
java
package br.edu.ifrn.jeferson.dto; import java.util.ArrayList; public class MeusDados { private float id; private String matricula; private String nome_usual; private String cpf; private String rg; ArrayList < Object > filiacao = new ArrayList < Object > (); private String data_nascimento; private String naturalidade; private String tipo_sanguineo; private String email; private String url_foto_75x100; private String url_foto_150x200; private String tipo_vinculo; Vinculo VinculoObject; // Getter Methods public float getId() { return id; } public String getMatricula() { return matricula; } public String getNome_usual() { return nome_usual; } public String getCpf() { return cpf; } public String getRg() { return rg; } public String getData_nascimento() { return data_nascimento; } public String getNaturalidade() { return naturalidade; } public String getTipo_sanguineo() { return tipo_sanguineo; } public String getEmail() { return email; } public String getUrl_foto_75x100() { return url_foto_75x100; } public String getUrl_foto_150x200() { return url_foto_150x200; } public String getTipo_vinculo() { return tipo_vinculo; } public Vinculo getVinculo() { return VinculoObject; } // Setter Methods public void setId(float id) { this.id = id; } public void setMatricula(String matricula) { this.matricula = matricula; } public void setNome_usual(String nome_usual) { this.nome_usual = nome_usual; } public void setCpf(String cpf) { this.cpf = cpf; } public void setRg(String rg) { this.rg = rg; } public void setData_nascimento(String data_nascimento) { this.data_nascimento = data_nascimento; } public void setNaturalidade(String naturalidade) { this.naturalidade = naturalidade; } public void setTipo_sanguineo(String tipo_sanguineo) { this.tipo_sanguineo = tipo_sanguineo; } public void setEmail(String email) { this.email = email; } public void setUrl_foto_75x100(String url_foto_75x100) { this.url_foto_75x100 = url_foto_75x100; } public void setUrl_foto_150x200(String url_foto_150x200) { this.url_foto_150x200 = url_foto_150x200; } public void setTipo_vinculo(String tipo_vinculo) { this.tipo_vinculo = tipo_vinculo; } public void setVinculo(Vinculo vinculoObject) { this.VinculoObject = vinculoObject; } }
8665a752df3319b16173187916ef397e2f7efc29
0a0c75308170240bef48336fe794df9947e8b088
/src/main/java/ua/kpi/dzidzoiev/is/service/FileEncryptService.java
95415ed114556f93ea31fc250f22d209e2492b93
[]
no_license
schaffe/CryptographyLabs
c5a38671af8570569f0f4267506fc69381dc2a6b
dbbb366ae4b5f65a6165aa5185acb52b5478d4c8
refs/heads/master
2021-01-10T04:08:01.499269
2015-12-22T08:04:42
2015-12-22T08:04:42
47,140,494
0
0
null
null
null
null
UTF-8
Java
false
false
5,103
java
package ua.kpi.dzidzoiev.is.service; import org.apache.commons.io.FilenameUtils; import ua.kpi.dzidzoiev.is.MainApp; import ua.kpi.dzidzoiev.is.service.symmetric.CipherDescription; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import java.io.*; import java.net.URISyntaxException; import java.net.URL; import java.nio.ByteBuffer; /** * Created by dzidzoiev on 12/13/15. */ public class FileEncryptService { public static final int FILE_BUFFER_SIZE = 2048; public static final int KEY_SIZE = 56; public static final int KEY_SIZE_OFFSET = 0; public String encrypt(String source, String destDir, CipherDescription cipherDescription, String key) { StatefulSymmetricEncoder encoder = new StatefulSymmetricEncoder(); String newName = createEncryptedFile(destDir, source); try ( InputStream sourceStream = new BufferedInputStream(new FileInputStream(source), FILE_BUFFER_SIZE * 2); // OutputStream outputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(newName), FILE_BUFFER_SIZE * 2), Holder.UTF_8)) OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(newName), FILE_BUFFER_SIZE * 2)) { byte[] iv = ByteBuffer.allocate(KEY_SIZE).put(encoder.encryptInit(key, cipherDescription)).array(); // byte[] bytes = ByteBuffer.allocate(KEY_SIZE_OFFSET).putInt(cipherDescription.getBlockSize()).array(); // outputStream.write(bytes); outputStream.write(iv); CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, encoder.getCipher()); byte[] buffer = new byte[FILE_BUFFER_SIZE]; int count; int offset = 0; while ((count = sourceStream.read(buffer)) > 0) { cipherOutputStream.write(buffer, offset, count ); } cipherOutputStream.flush(); cipherOutputStream.close(); return newName; } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException(e); } } public String decrypt(String source, String destDir, CipherDescription cipherDescription, String key) { StatefulSymmetricEncoder decoder = new StatefulSymmetricEncoder(); String newName = createDecryptedFile(destDir, source); try ( InputStream sourceStream = new BufferedInputStream(new FileInputStream(source), FILE_BUFFER_SIZE * 2); // InputStream sourceStream = new ZipInputStream(new BufferedInputStream(new FileInputStream(source), FILE_BUFFER_SIZE * 2), Holder.UTF_8); OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(newName), FILE_BUFFER_SIZE * 2)) { // byte[] key_size = new byte[KEY_SIZE_OFFSET]; byte[] key_bytes_full = new byte[KEY_SIZE]; // sourceStream.read(key_size); sourceStream.read(key_bytes_full); // int keySize = ByteBuffer.wrap(key_size).getInt(); int keySize = cipherDescription.getBlockSize(); byte[] keyBytes = new byte[keySize]; System.arraycopy(key_bytes_full, 0, keyBytes, 0, keySize); decoder.decryptInit(keyBytes, key, cipherDescription); CipherInputStream cipherInputStream = new CipherInputStream(sourceStream, decoder.getCipher()); byte[] buffer = new byte[FILE_BUFFER_SIZE]; int count; int offset = 0; while ((count = cipherInputStream.read(buffer)) > 0) { outputStream.write(buffer, offset, count ); } cipherInputStream.close(); outputStream.flush(); return newName; } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException(e); } } private String createEncryptedFile(String directory, String oldFile) { String newName = "encrypted_" + FilenameUtils.getName(oldFile); return new File(directory, newName).getAbsolutePath(); } private String createDecryptedFile(String directory, String oldFile) { String newName = "decrypted_" + FilenameUtils.getName(oldFile); return new File(directory, newName).getAbsolutePath(); } public static void main(String[] args) throws IOException, URISyntaxException { FileEncryptService fileEncryptService = new FileEncryptService(); URL fileUrl = MainApp.class.getClassLoader().getResource("file/test.txt"); URL folderUrl = MainApp.class.getClassLoader().getResource("file"); // URL fileUrl = MainApp.class.getClassLoader().getResource("file/test_big.txt"); System.out.println(fileUrl); String encrFile = fileEncryptService.encrypt(fileUrl.getFile(), folderUrl.getFile(), new CipherDescription("AES", "CBC", "PKCS5Padding"), "key"); fileEncryptService.decrypt(encrFile, folderUrl.getFile(), new CipherDescription("AES", "CBC", "PKCS5Padding"), "key"); } }
130ecda48d8afeda0e3fefe20cde0fd4203a1fa1
3f3d02cff5b43408b0cdac252b380aad0780e801
/basemodule/src/main/java/com/moregood/base/BaseTabActivity.java
9ba551b9be755849ec923bbe4e8b235ac1ad88dc
[]
no_license
xifengye/Modularization
2fc0912465468315a895ec922be1064d9222a98a
499aa22153880e7c5dd5fe3a4807d4fff289e672
refs/heads/master
2020-03-24T09:50:07.686848
2019-06-28T01:27:47
2019-06-28T01:27:47
142,638,970
0
0
null
null
null
null
UTF-8
Java
false
false
1,651
java
package com.moregood.base; import android.support.v4.app.FragmentTabHost; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TabHost; import android.widget.TextView; import com.moregood.basemodule.R; import com.moregood.bean.Tab; import java.util.ArrayList; import java.util.List; /** * Created by yexifeng on 2018/4/22. */ public abstract class BaseTabActivity extends BaseActivity { private FragmentTabHost mTabHost; private List<Tab> list = new ArrayList<>(); protected void initTab(Tab... tabs) { for(Tab tab:tabs) { list.add(tab); } mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost); mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent); for (Tab tab : list) { TabHost.TabSpec tabSpec = mTabHost.newTabSpec(tab.getTag()); tabSpec.setIndicator(buildView(tab)); mTabHost.addTab(tabSpec, tab.getmFragment(), null); } mTabHost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE); if(list!=null && list.size()>0){ mTabHost.setCurrentTabByTag(list.get(0).getTag()); } } private View buildView(Tab tab) { View view = LayoutInflater.from(this).inflate(R.layout.tab_indicator, null); ImageView tabImg = (ImageView) view.findViewById(R.id.tab_img); TextView text = (TextView) view.findViewById(R.id.tab_text); tabImg.setImageResource(tab.getIcon()); text.setText(tab.getText()); return view; } }
76a1b74454a3934a6110f434622258c8d6daa278
ed3cb95dcc590e98d09117ea0b4768df18e8f99e
/project_1_3/src/g/a/h/Calc_1_3_6078.java
8fb0dc1690a7ad5eece42bd3bee25e74f8f44435
[]
no_license
chalstrick/bigRepo1
ac7fd5785d475b3c38f1328e370ba9a85a751cff
dad1852eef66fcec200df10083959c674fdcc55d
refs/heads/master
2016-08-11T17:59:16.079541
2015-12-18T14:26:49
2015-12-18T14:26:49
48,244,030
0
0
null
null
null
null
UTF-8
Java
false
false
131
java
package g.a.h; public class Calc_1_3_6078 { /** @return the sum of a and b */ public int add(int a, int b) { return a+b; } }
3429512deb70e5913367f300ea1e9e03bdf3dead
0f240fd8a8bf446f06e2bb76d9a10921a82f1258
/TicTacToe/app/src/main/java/com/comp1601/tictactoe/TicTacToeButton.java
8789a188f609df4467ef7e65e55dda81a281e82e
[]
no_license
phampe68/TicTacToe
c6a811b5695eaba0492cea50b0ef5985d1e93774
72f26be8e5c88bbd74e658971f06c12d2d729de9
refs/heads/master
2021-03-06T05:54:36.478510
2020-03-10T01:54:17
2020-03-10T01:54:17
246,184,024
0
0
null
null
null
null
UTF-8
Java
false
false
3,327
java
package com.comp1601.tictactoe; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.View; import androidx.appcompat.widget.AppCompatButton; import java.util.Random; /** * IMPORTANT: * this class uses integer values 0 and 1 for representation of "X" and "O" * this is to better handle arrays */ public class TicTacToeButton extends AppCompatButton implements View.OnClickListener { private int buttonNum; //what number button in the 3x3 square of buttons private MainActivity activity; /** * @param context: the context that the button is associated with (all from Main Activity in this app) * @param attrs: defines the button's attributes */ public TicTacToeButton(Context context, AttributeSet attrs ) { super(context, attrs); this.setOnClickListener(this); //every button from this class will share this class's onClickListener //initialize button number (the button number is the last character of its resource id //ex: if resName: square1 resName: square2 //then buttonNum: 1 buttonNum: 2 String resName = getResources().getResourceEntryName(this.getId()); //get the last character, convert it to a string, and then store it as an integer char lastChar = resName.charAt(resName.length() -1); String lastString = String.valueOf(lastChar); this.buttonNum = Integer.parseInt(lastString); //set button background to default this.setBackgroundResource(R.drawable.tic_tac_toe_button_default); //store the MainActivity context (so we can access its state and behaviour from the onClickListener) activity = (MainActivity) context; } /** * Changes the text based on which player's turn it is, makes the corresponding change in the TicTacToeGame model * @param v: the view (in this case a button) */ @Override public void onClick(View v) { //log which button was pressed Log.i("BUTTON", String.valueOf(this.buttonNum)); //do nothing if the button was already pressed (we know the button was pressed if its text was changed to either X or O) if(this.getText() == "X" || this.getText()== "O") return; //get the game from main activity TicTacToeGame currGame = activity.getGame(); //change text if(currGame.getSymbol() == 0) this.setText("X"); else this.setText("O"); //make move and show board currGame.makeMove(this.buttonNum); currGame.printBoard(); //change background this.setBackgroundResource(R.drawable.tic_tac_toe_button_clicked); //when someone wins, make a new game String winningLine = currGame.getWinningLine()[0]; if(!winningLine.equals("GAME IN PROGRESS")){ activity.newGame(); } } /** * resets the button's background and text, re-enables button */ public void resetButton(){ this.setBackgroundResource(R.drawable.tic_tac_toe_button_default); this.setText(""); this.setEnabled(true); } public void highlightButton(){ this.setBackgroundResource(R.drawable.tic_tac_toe_button_win); } }
66c232a66bb7b87150aa1bed9dab972be58cc8ac
68465e463a662b9ccd12525c02326aa359e912b6
/huboot-business-server/src/main/java/com/huboot/business/base_model/login/sso/client/exception/SsoException.java
b333e05d13969682c10309bc0ee89158ca236e67
[]
no_license
qiangli524/myproject
d868e94daca660275eaac456e2117075cd901d41
56a605367606f7d7259e49a74454d8cbcdef45ce
refs/heads/master
2020-07-02T03:45:13.010861
2019-03-25T02:04:43
2019-03-25T02:04:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,254
java
package com.huboot.business.base_model.login.sso.client.exception; public class SsoException extends RuntimeException{ private static final long serialVersionUID = -1827198664611457387L; private String code = "403"; private String msg; public SsoException() { super(); } public SsoException(String message, Throwable cause,boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public SsoException(String errorCode, String message, Throwable cause,boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); this.code = errorCode; } public SsoException(String message, Throwable cause) { super(message, cause); } public SsoException(String message) { super(message); } public SsoException(String errorCode, String message) { super(message); this.code = errorCode; } public SsoException(Throwable cause) { super(cause); } public String getErrorCode() { return code; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
15df480fc8d162da99df501966e7702a666bdab4
aab2a45faab24ee09c59ec9c3d6f484ce7db4242
/WangYiYun/app/src/main/java/com/example/wangyiyun/Search.java
b835c2d07d66a19793b647c9085e8de7bc2611a1
[]
no_license
suagger/FristProject
a470f246c4921f51a36be87ca95385f681d28b72
bb071328858f4d7f49fbc3493be576fa5cc20616
refs/heads/master
2020-08-28T21:02:57.775388
2019-10-27T07:44:28
2019-10-27T07:44:28
217,820,106
0
0
null
null
null
null
UTF-8
Java
false
false
5,192
java
package com.example.wangyiyun; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.Activity; import android.graphics.Color; import android.graphics.Typeface; import android.os.Build; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.example.wangyiyun.adapter.SearchSongs; import com.example.wangyiyun.adapter.SongsAdapter; import com.example.wangyiyun.util.HttpUrl; import org.jetbrains.annotations.NotNull; import org.json.JSONArray; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.List; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class Search extends AppCompatActivity implements View.OnClickListener { private List<SearchSongs> songsList = new ArrayList<>(); private EditText text; private Button back; private RecyclerView recyclerView1; private Button enter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_serach); main.activityList.add(this); if(Build.VERSION.SDK_INT >= 21) { View decroView = getWindow().getDecorView(); decroView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |View.SYSTEM_UI_FLAG_LAYOUT_STABLE);//布局显示在状态栏上面 getWindow().setStatusBarColor(Color.TRANSPARENT);//设置颜色为透明色 } recyclerView1 = findViewById(R.id.view_recycler); text= findViewById(R.id.search_sing); enter = findViewById(R.id.enter); enter.setOnClickListener(this); back = findViewById(R.id.back); back.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.back: finish(); break; case R.id.enter: String name = text.getText().toString().trim(); InitSongs(name); break; default: break; } } private void InitSongs(String name){ try { String path = "https://c.y.qq.com/soso/fcgi-bin/client_search_cp?p=1&n=50&w=" + name + "&format=json"; HttpUrl.sendHttpResult(path, new Callback() { @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { e.printStackTrace(); } @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { String data = response.body().string(); parseJSONWithJSONObject(data); } }); }catch (Exception e){ e.printStackTrace(); } } private void parseJSONWithJSONObject(String jsonData){ try{ songsList.clear(); JSONObject objectAll = new JSONObject(jsonData); String data = objectAll.optString("data",null); if(!TextUtils.isEmpty(data)){ JSONObject object = new JSONObject(data); String song = object.optString("song",null); JSONObject objectSong = new JSONObject(song); String list = objectSong.optString("list",null); JSONArray array = new JSONArray(list); for(int i = 0; i < array.length(); i ++){ JSONObject trueObject = array.getJSONObject(i); String singer = trueObject.optString("singer",null); String alumnId = trueObject.optString("albummid",null); JSONArray jsonArray = new JSONArray(singer); String singerName = null; for(int j = 0; j < jsonArray.length(); j ++){ JSONObject oobject = jsonArray.getJSONObject(j); singerName = oobject.optString("name",null); } String songName = trueObject.optString("songname","null"); String songmid = trueObject.optString("songmid",null); SearchSongs songs = new SearchSongs(singerName,songName,songmid,alumnId); songsList.add(songs); } } runOnUiThread(new Runnable() { @Override public void run() { LinearLayoutManager layoutManager = new LinearLayoutManager(Search.this); recyclerView1.setLayoutManager(layoutManager); SongsAdapter adapter = new SongsAdapter(songsList); recyclerView1.setAdapter(adapter); } }); }catch (Exception e){ e.printStackTrace(); } } }
0b6928ab9288d90e70ecbc3e4f8cd67d4bd6bf7d
027e713d403e139f2a4015590bbcbe556ac19728
/src/br/org/cesar/jedje/javame/JEdjeCanvasObject.java
d73a282efa7caf9e81833390119eb7c44eb3e1fe
[]
no_license
dpsm/jedje
c64d80be9dded9c22e5d7b752c5b107ba7e03a6a
aa747589650435e5b4812dabbbef8b6fa3383ac6
refs/heads/master
2018-12-29T19:33:25.934144
2009-02-02T14:21:09
2009-02-02T14:21:09
97,355
1
1
null
null
null
null
UTF-8
Java
false
false
2,125
java
/** * Copyright (c) 2008 David Marques. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * David Marques - Adding EPL headers. */ package br.org.cesar.jedje.javame; import br.org.cesar.jedje.compiler.grammar.JEdjePart; public class JEdjeCanvasObject { // Constants ----------------------------------------------------- // Attributes ---------------------------------------------------- private JEdjePart part; private int x; private int y; private int width; private int height; // Static -------------------------------------------------------- // Constructors -------------------------------------------------- public JEdjeCanvasObject(JEdjePart _part) { this.part = _part; } // Public -------------------------------------------------------- /** * @return the part */ public JEdjePart getPart() { return part; } /** * @return the x */ public int getX() { return x; } /** * @param x the x to set */ public void setX(int x) { this.x = x; } /** * @return the y */ public int getY() { return y; } /** * @param y the y to set */ public void setY(int y) { this.y = y; } /** * @return the width */ public int getWidth() { return width; } /** * @param width the width to set */ public void setWidth(int width) { this.width = width; } /** * @return the height */ public int getHeight() { return height; } /** * @param height the height to set */ public void setHeight(int height) { this.height = height; } // X implementation ---------------------------------------------- // Y overrides --------------------------------------------------- // Package protected --------------------------------------------- // Protected ----------------------------------------------------- // Private ------------------------------------------------------- }
329919f2e6fb49eb21783d4b50838b51b0dfb9ca
c87fd6d93631a1a98e77fede930eb59702002a82
/engine/src/test/java/org/teiid/query/optimizer/TestDependentJoins.java
208c237d3d218d0a87a8cb23dca5aa1ea6f7da77
[ "Apache-2.0" ]
permissive
Freakey17/teiid
6a216d844b5f79993d6aca7b82225270fd3e3175
76d29a5580f018fa42c842c1ccb2f5ee6b4b9cdb
refs/heads/master
2020-04-30T10:57:40.183351
2019-03-20T18:03:04
2019-03-20T18:03:04
176,790,018
0
0
NOASSERTION
2019-03-20T18:02:24
2019-03-20T18:02:24
null
UTF-8
Java
false
false
58,760
java
/* * Copyright Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags and * the COPYRIGHT.txt file distributed with this work. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teiid.query.optimizer; import static org.junit.Assert.*; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.junit.Test; import org.teiid.core.TeiidComponentException; import org.teiid.core.TeiidProcessingException; import org.teiid.metadata.Column; import org.teiid.query.metadata.CompositeMetadataStore; import org.teiid.query.metadata.QueryMetadataInterface; import org.teiid.query.metadata.SystemMetadata; import org.teiid.query.metadata.TransformationMetadata; import org.teiid.query.optimizer.TestOptimizer.ComparisonMode; import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities; import org.teiid.query.optimizer.capabilities.CapabilitiesFinder; import org.teiid.query.optimizer.capabilities.DefaultCapabilitiesFinder; import org.teiid.query.optimizer.capabilities.FakeCapabilitiesFinder; import org.teiid.query.optimizer.capabilities.SourceCapabilities.Capability; import org.teiid.query.optimizer.relational.rules.RuleChooseDependent; import org.teiid.query.processor.ProcessorPlan; import org.teiid.query.processor.relational.AccessNode; import org.teiid.query.processor.relational.DependentAccessNode; import org.teiid.query.processor.relational.JoinNode; import org.teiid.query.processor.relational.RelationalNode; import org.teiid.query.processor.relational.RelationalPlan; import org.teiid.query.sql.lang.Command; import org.teiid.query.sql.lang.JoinType; import org.teiid.query.sql.symbol.GroupSymbol; import org.teiid.query.sql.visitor.GroupCollectorVisitor; import org.teiid.query.unittest.RealMetadataFactory; @SuppressWarnings("nls") public class TestDependentJoins { static void checkDependentGroups(ProcessorPlan plan, String[] groups) { if(! (plan instanceof RelationalPlan)) { return; } // Collect all the group names (uppercase) for all the dependent groups in the plan Set<String> depGroups = new HashSet<String>(); getDependentGroups(((RelationalPlan)plan).getRootNode(), depGroups, true); // Check that all the expected groups exist in depGroups Set<String> expectedGroups = new HashSet<String>(); for(int i=0; i<groups.length; i++) { expectedGroups.add(groups[i].toUpperCase()); } assertEquals("Expected groups were not made dependent", expectedGroups, depGroups); //$NON-NLS-1$ } static void getDependentGroups(RelationalNode node, Set<String> depGroups, boolean depdenent) { if(node instanceof AccessNode) { if (node instanceof DependentAccessNode) { if (!depdenent) { return; } } else if (depdenent) { return; } AccessNode accessNode = (AccessNode)node; Command depCommand = accessNode.getCommand(); Collection<GroupSymbol> groupSymbols = GroupCollectorVisitor.getGroups(depCommand, true); for (GroupSymbol groupSymbol : groupSymbols) { depGroups.add(groupSymbol.getNonCorrelationName().toUpperCase()); } } // Recurse through children RelationalNode[] children = node.getChildren(); for(int i=0; i<children.length; i++) { if(children[i] != null) { getDependentGroups(node.getChildren()[i], depGroups, depdenent); } } } private void checkNotDependentGroups(ProcessorPlan plan, String[] groups) { if(! (plan instanceof RelationalPlan)) { return; } // Collect all the group names (uppercase) for all the dependent groups in the plan Set<String> notDepGroups = new HashSet<String>(); getDependentGroups(((RelationalPlan)plan).getRootNode(), notDepGroups, false); // Check that all the expected groups exist in depGroups Set<String> expectedGroups = new HashSet<String>(); for(int i=0; i<groups.length; i++) { expectedGroups.add(groups[i].toUpperCase()); } assertEquals("Expected groups were made dependent", expectedGroups, notDepGroups); //$NON-NLS-1$ } @Test public void testOptionMakeDep1() throws Exception { FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder(); BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities(); caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false); capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$ ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm2.g1 where pm1.g1.e1 = pm2.g1.e1 option makedep pm2.g1", RealMetadataFactory.example1Cached(), null, capFinder, //$NON-NLS-1$ new String[] { "SELECT g_0.e1 FROM pm2.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ checkDependentGroups(plan, new String[] {"pm2.g1"}); //$NON-NLS-1$ checkNotDependentGroups(plan, new String[] {"pm1.g1"}); //$NON-NLS-1$ TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); } @Test public void testOptionMakeDep2() throws Exception { FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder(); BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities(); caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false); capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$ ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1, pm2.g1.e1 from pm1.g1 MAKEDEP INNER JOIN pm2.g1 MAKENOTDEP ON pm1.g1.e1 = pm2.g1.e1", RealMetadataFactory.example1Cached(), null, capFinder, //$NON-NLS-1$ new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm2.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ checkDependentGroups(plan, new String[] {"pm1.g1"}); //$NON-NLS-1$ checkNotDependentGroups(plan, new String[] {"pm2.g1"}); //$NON-NLS-1$ TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); } @Test public void testDepJoinHintForceLeft() throws Exception { ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g1", TestOptimizer.example1(), //$NON-NLS-1$ new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g2 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); checkDependentGroups(plan, new String[] {"pm1.g1"}); //$NON-NLS-1$ } @Test public void testDepJoinHintForceRight() throws Exception { ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g2", TestOptimizer.example1(), //$NON-NLS-1$ new String[] { "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); checkDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$ } @Test public void testGlobalHint() throws Exception { ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep @g4.g2", TestOptimizer.example1(), //$NON-NLS-1$ new String[] { "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); checkDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$ } @Test public void testGlobalHint1() throws Exception { ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 as x option makedep @x.g2", TestOptimizer.example1(), //$NON-NLS-1$ new String[] { "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); checkDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$ } @Test public void testGlobalHintSetQuery() throws Exception { ProcessorPlan plan = TestOptimizer.helpPlan("(Select e1 from pm1.g1 Intersect select abc.e1 from (select pm1.g2.e1 from pm1.g2, pm1.g3 where pm1.g2.e2 = pm1.g3.e2) abc) option makedep @abc.g2", TestOptimizer.example1(), //$NON-NLS-1$ new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0", "SELECT g_0.e2, g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e2 IN (<dependent values>)", "SELECT g_0.e2 FROM pm1.g3 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ TestOptimizer.checkNodeTypes(plan, new int[] { 2, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 2, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); checkDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$ } @Test public void testDepJoinMultiGroupBaseline() throws Exception { ProcessorPlan plan = TestOptimizer.helpPlan("select vm1.g4.*, pm1.g3.e1 FROM vm1.g4, pm1.g3 where pm1.g3.e1=vm1.g4.e1", TestOptimizer.example1(), //$NON-NLS-1$ new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", //$NON-NLS-1$ "SELECT pm1.g2.e1 FROM pm1.g2", //$NON-NLS-1$ "SELECT pm1.g3.e1 FROM pm1.g3" }, TestOptimizer.getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING ); //$NON-NLS-1$ TestOptimizer.checkNodeTypes(plan, new int[] { 3, // Access 0, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 2, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); checkDependentGroups(plan, new String[0]); } @Test public void testDepJoinMultiGroupForceOther() throws Exception { ProcessorPlan plan = TestOptimizer.helpPlan("select vm1.g4.*, pm1.g3.e1 FROM vm1.g4, pm1.g3 where pm1.g3.e1=vm1.g4.e1 option makedep pm1.g2", TestOptimizer.example1(), //$NON-NLS-1$ new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0", "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ TestOptimizer.checkNodeTypes(plan, new int[] { 2, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 2, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); checkDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$ } @Test public void testDepJoinHintForceLeft_NotDep() throws Exception { ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g1 makenotdep pm1.g2", TestOptimizer.example1(), //$NON-NLS-1$ new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g2 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); checkDependentGroups(plan, new String[] {"pm1.g1"}); //$NON-NLS-1$ checkNotDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$ } @Test public void testDepJoinHintForceRight_NotDep() throws Exception { ProcessorPlan plan = TestOptimizer.helpPlan("select * FROM vm1.g4 option makedep pm1.g2 makenotdep pm1.g1", TestOptimizer.example1(), //$NON-NLS-1$ new String[] { "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); checkDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$ checkNotDependentGroups(plan, new String[] {"pm1.g1"}); //$NON-NLS-1$ } @Test public void testDepJoinMultiGroupForceOther_NotDep() throws Exception { ProcessorPlan plan = TestOptimizer.helpPlan("select vm1.g4.*, pm1.g3.e1 FROM vm1.g4, pm1.g3 where pm1.g3.e1=vm1.g4.e1 option makedep pm1.g2 makenotdep pm1.g1, pm1.g3", TestOptimizer.example1(), //$NON-NLS-1$ new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0", "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ TestOptimizer.checkNodeTypes(plan, new int[] { 2, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 2, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); checkDependentGroups(plan, new String[] {"pm1.g2"}); //$NON-NLS-1$ checkNotDependentGroups(plan, new String[] {"pm1.g1", "pm1.g3"}); //$NON-NLS-1$ //$NON-NLS-2$ } /** * Test that access node with unsatisfied access pattern is made dependent */ @Test public void testMakeDependentAccessPattern1() throws Exception { ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm1.g1.e1 = pm4.g1.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$ new String[] { "SELECT g_0.e1 FROM pm4.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ checkDependentGroups(plan, new String[] {"pm4.g1"}); //$NON-NLS-1$ } /** * Test that access node with unsatisfied access pattern is made dependent * (Same query written slightly different way) */ @Test public void testMakeDependentAccessPattern1a() throws Exception { ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm4.g1, pm1.g1 where pm4.g1.e1 = pm1.g1.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$ new String[] { "SELECT g_0.e1 FROM pm4.g1 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ checkDependentGroups(plan, new String[] {"pm4.g1"}); //$NON-NLS-1$ } /** * Test that access node with unsatisfied access pattern is made dependent */ @Test public void testMakeDependentAccessPattern2() throws Exception { ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm4.g1.e2 = 1 and pm1.g1.e1 = pm4.g1.e1", RealMetadataFactory.example1Cached(), //$NON-NLS-1$ new String[] { "SELECT g_0.e1 FROM pm4.g1 AS g_0 WHERE (g_0.e2 = 1) AND (g_0.e1 IN (<dependent values>))", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ checkDependentGroups(plan, new String[] {"pm4.g1"}); //$NON-NLS-1$ } /** * Test that second access pattern of access node is chosen to make * dependent with */ @Test public void testMakeDependentAccessPattern3() throws Exception { ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g2 where pm1.g1.e1 = pm4.g2.e5", RealMetadataFactory.example1Cached(), //$NON-NLS-1$ new String[] { "SELECT g_0.e5 FROM pm4.g2 AS g_0 WHERE g_0.e5 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ checkDependentGroups(plan, new String[] {"pm4.g2"}); //$NON-NLS-1$ } /** * This case actually tests the dead-tie case - either access node could * be made dependent, but merge join is used since no access pattern * needs to be fulfilled and there is no cost info available for either source */ @Test public void testPushSelectAndMakeDependentAccessPattern1() throws Exception { ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm4.g1.e1 = 'abc' and pm1.g1.e1 = 'abc' and pm1.g1.e2 = pm4.g1.e2", RealMetadataFactory.example1Cached(), //$NON-NLS-1$ new String[] { "SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'", "SELECT pm4.g1.e2 FROM pm4.g1 WHERE pm4.g1.e1 = 'abc'" }, TestOptimizer.getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ checkDependentGroups(plan, new String[0]); TestOptimizer.checkNodeTypes(plan, new int[] { 2, // Access 0, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); } /** * This case actually tests the dead-tie case - either access node could * be made dependent, but merge join is used since no access pattern * needs to be fulfilled and there is no cost info available for either source * (Same query written slightly different) */ @Test public void testPushSelectAndMakeDependentAccessPattern1a() throws Exception { ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm4.g1, pm1.g1 where pm4.g1.e2 = pm1.g1.e2 and pm4.g1.e1 = 'abc' and pm1.g1.e1 = 'abc'", RealMetadataFactory.example1Cached(), //$NON-NLS-1$ new String[] { "SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1 WHERE pm1.g1.e1 = 'abc'", "SELECT pm4.g1.e2 FROM pm4.g1 WHERE pm4.g1.e1 = 'abc'" }, TestOptimizer.getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ checkDependentGroups(plan, new String[0]); TestOptimizer.checkNodeTypes(plan, new int[] { 2, // Access 0, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); } /** * Tests that it is enforced if an access node can't be made dependent * because of it's (already-satisfied) access pattern - merge join is used */ @Test public void testPushSelectAndMakeDependentAccessPattern2() throws Exception { ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm4.g1 where pm4.g1.e1 = 'abc' and pm1.g1.e2 = pm4.g1.e2", RealMetadataFactory.example1Cached(), //$NON-NLS-1$ new String[] { "SELECT pm1.g1.e2, pm1.g1.e1 FROM pm1.g1", "SELECT pm4.g1.e2 FROM pm4.g1 WHERE pm4.g1.e1 = 'abc'" }, TestOptimizer.getGenericFinder(false), ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ checkDependentGroups(plan, new String[0] ); TestOptimizer.checkNodeTypes(plan, new int[] { 2, // Access 0, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); } /** Should use dependent join since one access node is "strong" */ @Test public void testUseMergeJoin1() throws Exception { // Create query String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder(); BasicSourceCapabilities caps = new BasicSourceCapabilities(); caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true); caps.setCapabilitySupport(Capability.CRITERIA_QUANTIFIED_SOME, true); caps.setCapabilitySupport(Capability.CRITERIA_IN, true); caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true); caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(10)); capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$ QueryMetadataInterface metadata = RealMetadataFactory.example1(); RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, null, capFinder, new String[] { "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); } /** Should not use a dependent join since neither access node is "strong" */ @Test public void testUseMergeJoin2() throws Exception { // Create query String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2 WHERE pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder(); BasicSourceCapabilities caps = new BasicSourceCapabilities(); caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true); caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true); capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$ QueryMetadataInterface metadata = RealMetadataFactory.example1(); RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1, metadata); RealMetadataFactory.setCardinality("pm1.g2", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1, metadata); ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, null, capFinder, new String[] { "SELECT pm1.g1.e1 FROM pm1.g1", "SELECT pm1.g2.e1 FROM pm1.g2" }, TestOptimizer.ComparisonMode.CORRECTED_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ TestOptimizer.checkNodeTypes(plan, new int[] { 2, // Access 0, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); } /** should have one dependent joins */ @Test public void testMultiMergeJoin3() throws Exception { // Create query String sql = "SELECT pm1.g2.e1 FROM pm1.g3, pm1.g2, pm1.g1 WHERE pm1.g2.e1 = pm1.g3.e1 AND pm1.g1.e1 = pm1.g2.e1";//$NON-NLS-1$ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder(); BasicSourceCapabilities caps = new BasicSourceCapabilities(); caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true); caps.setCapabilitySupport(Capability.CRITERIA_IN, true); caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true); caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true); caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000)); capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$ QueryMetadataInterface metadata = RealMetadataFactory.example1(); RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1, metadata); RealMetadataFactory.setCardinality("pm1.g2", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); RealMetadataFactory.setCardinality("pm1.g3", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, null, capFinder, new String[] { "SELECT g_0.e1 FROM pm1.g3 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g2 AS g_0", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ TestOptimizer.checkNodeTypes(plan, new int[] { 2, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 2, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); } @Test public void testMultiMergeJoin2() throws Exception { String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2, pm1.g3 WHERE pm1.g1.e1 = pm1.g2.e1 AND pm1.g2.e1 = pm1.g3.e1";//$NON-NLS-1$ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder(); BasicSourceCapabilities caps = new BasicSourceCapabilities(); caps.setCapabilitySupport(Capability.CRITERIA_IN, true); caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true); caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true); caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true); caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000)); capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$ QueryMetadataInterface metadata = RealMetadataFactory.example1(); RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); RealMetadataFactory.setCardinality("pm1.g2", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); RealMetadataFactory.setCardinality("pm1.g3", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, null, capFinder, new String[] { "SELECT g_0.e1 FROM pm1.g1 AS g_0", "SELECT g_0.e1 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>)", "SELECT g_0.e1 FROM pm1.g3 AS g_0 WHERE g_0.e1 IN (<dependent values>)" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 2, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 2, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); } /** * Defect 13448 * should be one merge join and two dependent join * Unlike the above tests, here the model pm1 supports ORDER BY. */ @Test public void testMultiMergeJoin5_defect13448() throws Exception { // Create query String sql = "SELECT pm1.g1.e1 FROM pm1.g1, pm1.g2, pm1.g3 WHERE pm1.g1.e1 = pm1.g2.e1 AND pm1.g1.e1 = pm1.g3.e1";//$NON-NLS-1$ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder(); BasicSourceCapabilities caps = new BasicSourceCapabilities(); caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true); caps.setCapabilitySupport(Capability.CRITERIA_IN, true); caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true); caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true); caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true); caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true); caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000)); capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$ QueryMetadataInterface metadata = RealMetadataFactory.example1(); RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); RealMetadataFactory.setCardinality("pm1.g2", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); RealMetadataFactory.setCardinality("pm1.g3", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, null, capFinder, new String[] { "SELECT g_0.e1 AS c_0 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>) ORDER BY c_0", "SELECT g_0.e1 AS c_0 FROM pm1.g3 AS g_0 WHERE g_0.e1 IN (<dependent values>) ORDER BY c_0", "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 2, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 2, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); } @Test public void testMergeJoinVirtualGroups() throws Exception { String sql = "SELECT vm1.g1.e1 FROM vm1.g1, vm1.g2a WHERE vm1.g1.e1 = vm1.g2a.e1";//$NON-NLS-1$ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder(); BasicSourceCapabilities caps = new BasicSourceCapabilities(); caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true); caps.setCapabilitySupport(Capability.CRITERIA_IN, true); caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true); caps.setCapabilitySupport(Capability.QUERY_ORDERBY, true); caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_COUNT, true); caps.setCapabilitySupport(Capability.QUERY_SELECT_EXPRESSION, true); caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000)); capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$ QueryMetadataInterface metadata = RealMetadataFactory.example1(); RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); RealMetadataFactory.setCardinality("pm1.g2", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, null, capFinder, new String[] { "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0", "SELECT g_0.e1 AS c_0 FROM pm1.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>) ORDER BY c_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); } @Test public void testRLMCase2077() throws Exception { FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder(); BasicSourceCapabilities caps = new BasicSourceCapabilities(); caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true); caps.setCapabilitySupport(Capability.CRITERIA_IN, true); caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true); caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true); caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true); caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000)); caps.setFunctionSupport("||", true); //$NON-NLS-1$ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$ QueryMetadataInterface metadata = RealMetadataFactory.exampleBQT(); RealMetadataFactory.setCardinality("bqt1.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); //$NON-NLS-1$ RealMetadataFactory.setCardinality("bqt2.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); //$NON-NLS-1$ ProcessorPlan plan = TestOptimizer.helpPlan( "SELECT table1comp.IntKey, table1comp.key1, BQT1.SmallA.StringKey FROM (SELECT t1.*, (STRINGKEY || STRINGNUM) AS key1 FROM BQT2.SmallA AS t1) AS table1comp, BQT1.SmallA WHERE table1comp.key1 = BQT1.SmallA.StringKey", //$NON-NLS-1$ metadata, null, capFinder, new String[] {"SELECT g_0.StringKey, g_0.StringNum, g_0.IntKey FROM BQT2.SmallA AS g_0", "SELECT g_0.StringKey FROM BQT1.SmallA AS g_0 WHERE g_0.StringKey IN (<dependent values>)"}, //$NON-NLS-1$ //$NON-NLS-2$ TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 2, // Project 0, // Select 0, // Sort 0 // UnionAll }); } @Test public void testRLMCase2077_2() throws Exception { FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder(); BasicSourceCapabilities caps = new BasicSourceCapabilities(); caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true); caps.setCapabilitySupport(Capability.CRITERIA_IN, true); caps.setCapabilitySupport(Capability.QUERY_SEARCHED_CASE, true); caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_INNER, true); caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true); caps.setCapabilitySupport(Capability.ARRAY_TYPE, true); caps.setSourceProperty(Capability.MAX_IN_CRITERIA_SIZE, new Integer(1000)); caps.setFunctionSupport("||", true); //$NON-NLS-1$ capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$ TransformationMetadata metadata = RealMetadataFactory.exampleBQT(); RealMetadataFactory.setCardinality("bqt1.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); //$NON-NLS-1$ RealMetadataFactory.setCardinality("bqt2.smalla", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY - 1, metadata); //$NON-NLS-1$ ProcessorPlan plan = TestOptimizer.helpPlan( "SELECT table1comp.IntKey, table1comp.key1, BQT1.SmallA.StringKey FROM (SELECT t1.*, (STRINGKEY || STRINGNUM) AS key1 FROM BQT2.SmallA AS t1) AS table1comp, BQT1.SmallA WHERE table1comp.key1 = BQT1.SmallA.StringKey AND table1comp.key1 = BQT1.SmallA.StringNum", //$NON-NLS-1$ metadata, null, capFinder, new String[] {"SELECT g_0.StringKey, g_0.StringNum, g_0.IntKey FROM BQT2.SmallA AS g_0", "SELECT g_0.StringKey, g_0.StringNum FROM BQT1.SmallA AS g_0 WHERE (g_0.StringNum = g_0.StringKey) AND (g_0.StringKey IN (<dependent values>))"}, //$NON-NLS-1$ //$NON-NLS-2$ TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 2, // Project 0, // Select 0, // Sort 0 // UnionAll }); } @Test public void testCostingCleanup() throws Exception { FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder(); BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities(); caps.setCapabilitySupport(Capability.QUERY_FROM_JOIN_SELFJOIN, true); caps.setCapabilitySupport(Capability.QUERY_AGGREGATES, true); caps.setCapabilitySupport(Capability.QUERY_AGGREGATES_MAX, true); caps.setCapabilitySupport(Capability.QUERY_GROUP_BY, true); capFinder.addCapabilities("BQT1", caps); //$NON-NLS-1$ capFinder.addCapabilities("BQT2", caps); //$NON-NLS-1$ TransformationMetadata metadata = RealMetadataFactory.exampleBQT(); RealMetadataFactory.setCardinality("bqt1.smalla", 1000, metadata); //$NON-NLS-1$ RealMetadataFactory.setCardinality("bqt2.smalla", 10000, metadata); //$NON-NLS-1$ Column fmo = metadata.getElementID("bqt1.smalla.intnum"); fmo.setDistinctValues(1000); Column floatnum = metadata.getElementID("bqt1.smalla.floatnum"); floatnum.setDistinctValues(800); ProcessorPlan plan = TestOptimizer.helpPlan( "SELECT max(a.stringkey) from bqt1.smalla a, bqt2.smalla a2, bqt1.smalla a1 where a.intnum = a2.intnum and a1.stringnum = a2.stringnum and a.floatnum = a1.floatnum", //$NON-NLS-1$ metadata, null, capFinder, new String[] {"SELECT g_0.StringNum, g_0.IntNum FROM BQT2.SmallA AS g_0 WHERE (g_0.StringNum IN (<dependent values>)) AND (g_0.IntNum IN (<dependent values>))", "SELECT DISTINCT g_1.StringNum AS c_0, g_0.IntNum AS c_1, g_0.StringKey AS c_2 FROM BQT1.SmallA AS g_0, BQT1.SmallA AS g_1 WHERE g_0.FloatNum = g_1.FloatNum ORDER BY c_0, c_1"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 1, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); } @Test public void testSystemDependent() throws TeiidComponentException, TeiidProcessingException { // Create query String sql = "SELECT pm1.g1.e1 FROM pm1.g1, sys.columns makedep where pm1.g1.e1 = sys.columns.name"; //$NON-NLS-1$ CompositeMetadataStore cms = new CompositeMetadataStore(Arrays.asList(RealMetadataFactory.example1Store(), SystemMetadata.getInstance().getSystemStore())); TransformationMetadata tm = new TransformationMetadata(null, cms, null, null, null); BasicSourceCapabilities bsc = new BasicSourceCapabilities(); bsc.setCapabilitySupport(Capability.CRITERIA_IN, true); ProcessorPlan plan = TestOptimizer.helpPlan( sql, //$NON-NLS-1$ tm, null, new DefaultCapabilitiesFinder(bsc), new String[] {"SELECT pm1.g1.e1 FROM pm1.g1", "SELECT SYS.Columns.Name FROM SYS.Columns WHERE SYS.Columns.Name IN (<dependent values>)"}, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING ); TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 2, // Project - we expect a project over the system query 0, // Select 0, // Sort 0 // UnionAll }); } @Test public void testPlanningOverJoin() throws Exception { // Create query String sql = "SELECT pm1.g1.e1 FROM pm1.g1, (select pm2.g2.e1, pm2.g3.e2 from pm2.g2 left outer join pm2.g3 on pm2.g2.e1 = pm2.g3.e1) as x where pm1.g1.e1 = x.e1";//$NON-NLS-1$ FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder(); BasicSourceCapabilities caps = new BasicSourceCapabilities(); caps.setCapabilitySupport(Capability.CRITERIA_COMPARE_EQ, true); caps.setCapabilitySupport(Capability.QUERY_FROM_GROUP_ALIAS, true); capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$ capFinder.addCapabilities("pm2", TestOptimizer.getTypicalCapabilities()); //$NON-NLS-1$ QueryMetadataInterface metadata = RealMetadataFactory.example1(); RealMetadataFactory.setCardinality("pm1.g1", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY, metadata); RealMetadataFactory.setCardinality("pm2.g2", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1000, metadata); RealMetadataFactory.setCardinality("pm2.g3", RuleChooseDependent.DEFAULT_INDEPENDENT_CARDINALITY + 1, metadata); ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, null, capFinder, new String[] { "SELECT g_0.e1 AS c_0 FROM pm2.g2 AS g_0 LEFT OUTER JOIN pm2.g3 AS g_1 ON g_0.e1 = g_1.e1 WHERE g_0.e1 IN (<dependent values>) ORDER BY c_0", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); } /** * Makes sure that hints are considered after rule push aggregates * @throws Exception */ @Test public void testMakedepWithAggregatePushdown() throws Exception { String sql = "select count(x.e2), pm2.g2.e1 from pm1.g1 x makedep, pm2.g2 where x.e4 = pm2.g2.e4 group by pm2.g2.e1";//$NON-NLS-1$ QueryMetadataInterface metadata = RealMetadataFactory.example1Cached(); ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, null, new DefaultCapabilitiesFinder(TestOptimizer.getTypicalCapabilities()), new String[] { "SELECT g_0.e4, g_0.e2 FROM pm1.g1 AS g_0 WHERE g_0.e4 IN (<dependent values>)", "SELECT g_0.e4 AS c_0, g_0.e1 AS c_1 FROM pm2.g2 AS g_0 ORDER BY c_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 2, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); } @Test public void testKeepTransitiveWithDependentJoin() throws Exception { FakeCapabilitiesFinder capFinder = new FakeCapabilitiesFinder(); BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities(); caps.setCapabilitySupport(Capability.QUERY_ORDERBY, false); capFinder.addCapabilities("pm1", caps); //$NON-NLS-1$ capFinder.addCapabilities("pm2", caps); //$NON-NLS-1$ ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g1.e1 from pm1.g1, pm2.g1, pm2.g2 where pm1.g1.e1 = pm2.g1.e1 and pm1.g1.e1 = pm2.g2.e1 and pm2.g1.e2 = pm2.g2.e2 option makedep pm2.g1", RealMetadataFactory.example1Cached(), null, capFinder, //$NON-NLS-1$ new String[] { "SELECT g_1.e1, g_0.e1 FROM pm2.g1 AS g_0, pm2.g2 AS g_1 WHERE (g_0.e2 = g_1.e2) AND (g_1.e1 = g_0.e1) AND (g_1.e1 IN (<dependent values>))", "SELECT g_0.e1 FROM pm1.g1 AS g_0" }, TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ TestOptimizer.checkNodeTypes(plan, new int[] { 1, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // NestedLoopJoinStrategy 1, // MergeJoinStrategy 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); } @Test public void testNestedLeftOuterJoin() throws TeiidComponentException, TeiidProcessingException { String sql = "select pm1.g1.e2, 'a', trim(pm1.g3.e1) from (pm1.g1 left outer join pm1.g2 on pm1.g1.e2 = pm1.g2.e2) left outer join pm1.g3 on pm1.g3.e3 = pm1.g2.e3 and pm1.g3.e4 = pm1.g1.e4"; //$NON-NLS-1$ QueryMetadataInterface metadata = RealMetadataFactory.example1(); RealMetadataFactory.setCardinality("pm1.g2", 6, metadata); //$NON-NLS-1$ RealMetadataFactory.setCardinality("pm1.g1", 0, metadata); //$NON-NLS-1$ RealMetadataFactory.setCardinality("pm1.g3", 0, metadata); //$NON-NLS-1$ CapabilitiesFinder finder = TestOptimizer.getGenericFinder(false); ProcessorPlan plan = TestOptimizer.helpPlan(sql, metadata, new String[] { "SELECT g_0.e3, g_0.e4, g_0.e1 FROM pm1.g3 AS g_0", "SELECT g_0.e2, g_0.e4 FROM pm1.g1 AS g_0", "SELECT g_0.e2, g_0.e3 FROM pm1.g2 AS g_0 WHERE g_0.e2 IN (<dependent values>)"}, finder, ComparisonMode.EXACT_COMMAND_STRING); TestOptimizer.checkNodeTypes(plan, new int[] { 2, // Access 1, // DependentAccess 0, // DependentSelect 0, // DependentProject 0, // DupRemove 0, // Grouping 0, // Join 2, // MergeJoin 0, // Null 0, // PlanExecution 1, // Project 0, // Select 0, // Sort 0 // UnionAll }); RelationalPlan rPlan = (RelationalPlan)plan; RelationalNode node = rPlan.getRootNode().getChildren()[0]; assertTrue(node instanceof JoinNode); node = node.getChildren()[0]; assertTrue(node instanceof JoinNode); assertEquals(JoinType.JOIN_LEFT_OUTER, ((JoinNode)node).getJoinType()); } @Test public void testMakeDependentOverUnionProjectingLiterals() throws Exception { ProcessorPlan plan = TestOptimizer.helpPlan("select pm1.g2.e1 from pm1.g2 inner join /*+ makedep */ " + "(select 1 as x, 'a' as y, e1 from pm1.g1 union all select 2, 'b', e1 from pm2.g1) v on y = pm1.g2.e1 and x = pm1.g2.e2", RealMetadataFactory.example1Cached(), //$NON-NLS-1$ new String[] { "SELECT 2 FROM pm2.g1 AS g_0", "SELECT g_0.e1, g_0.e2 FROM pm1.g2 AS g_0", "SELECT 1 FROM pm1.g1 AS g_0" }, TestOptimizer.getGenericFinder(false), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); //$NON-NLS-1$ //$NON-NLS-2$ checkDependentGroups(plan, new String[] {}); //$NON-NLS-1$ } @Test public void testMakeDependentWithLimit() throws Exception { BasicSourceCapabilities caps = TestOptimizer.getTypicalCapabilities(); ProcessorPlan plan = TestOptimizer.helpPlan( "select pm1.g1.e1, pm2.g2.e2 from pm1.g1 left outer join pm2.g2 on pm1.g1.e1 = pm2.g2.e1 order by pm1.g1.e1 limit 5", //$NON-NLS-1$ RealMetadataFactory.example1Cached(), new String[] { "SELECT g_0.e1 AS c_0, g_0.e2 AS c_1 FROM pm2.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>) ORDER BY c_0", "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0" }, //$NON-NLS-1$ new DefaultCapabilitiesFinder(caps), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); checkDependentGroups(plan, new String[] { "PM2.G2" }); //$NON-NLS-1$ caps.setCapabilitySupport(Capability.ROW_LIMIT, true); plan = TestOptimizer.helpPlan( "select pm1.g1.e1, pm2.g2.e2 from pm1.g1 left outer join pm2.g2 on pm1.g1.e1 = pm2.g2.e1 order by pm1.g1.e1 limit 5", //$NON-NLS-1$ RealMetadataFactory.example1Cached(), new String[] { "SELECT g_0.e1 AS c_0, g_0.e2 AS c_1 FROM pm2.g2 AS g_0 WHERE g_0.e1 IN (<dependent values>) ORDER BY c_0", "SELECT g_0.e1 AS c_0 FROM pm1.g1 AS g_0 ORDER BY c_0 LIMIT 5" }, //$NON-NLS-1$ new DefaultCapabilitiesFinder(caps), TestOptimizer.ComparisonMode.EXACT_COMMAND_STRING); checkDependentGroups(plan, new String[] { "PM2.G2" }); //$NON-NLS-1$ } }
c8ae33d37f724918680f86a92f033c6938167ff9
814169b683b88f1b7498f1edf530a8d1bec2971f
/mall-product/src/main/java/com/bootx/mall/product/controller/admin/plugin/PaypalPaymentController.java
8eb8c655c0315b5043bc6b40be994c6872211206
[]
no_license
springwindyike/mall-auth
fe7f216c7241d8fd9247344e40503f7bc79fe494
3995d258955ecc3efbccbb22ef4204d148ec3206
refs/heads/master
2022-10-20T15:12:19.329363
2020-07-05T13:04:29
2020-07-05T13:04:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,320
java
package com.bootx.mall.product.controller.admin.plugin; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import com.bootx.mall.product.common.Results; import com.bootx.mall.product.controller.admin.BaseController; import com.bootx.mall.product.entity.PluginConfig; import com.bootx.mall.product.plugin.PaymentPlugin; import com.bootx.mall.product.plugin.PaypalPaymentPlugin; import com.bootx.mall.product.service.PluginConfigService; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; /** * Controller - Paypal * * @author BOOTX Team * @version 6.1 */ @Controller("adminPluginPaypalPaymentController") @RequestMapping("/admin/plugin/paypal_payment") public class PaypalPaymentController extends BaseController { @Inject private PaypalPaymentPlugin paypalPaymentPlugin; @Inject private PluginConfigService pluginConfigService; /** * 安装 */ @PostMapping("/install") public ResponseEntity<?> install() { if (!paypalPaymentPlugin.getIsInstalled()) { PluginConfig pluginConfig = new PluginConfig(); pluginConfig.setPluginId(paypalPaymentPlugin.getId()); pluginConfig.setIsEnabled(false); pluginConfig.setAttributes(null); pluginConfigService.save(pluginConfig); } return Results.OK; } /** * 卸载 */ @PostMapping("/uninstall") public ResponseEntity<?> uninstall() { if (paypalPaymentPlugin.getIsInstalled()) { pluginConfigService.deleteByPluginId(paypalPaymentPlugin.getId()); } return Results.OK; } /** * 设置 */ @GetMapping("/setting") public String setting(ModelMap model) { PluginConfig pluginConfig = paypalPaymentPlugin.getPluginConfig(); model.addAttribute("currencies", PaypalPaymentPlugin.Currency.values()); model.addAttribute("feeTypes", PaymentPlugin.FeeType.values()); model.addAttribute("pluginConfig", pluginConfig); return "/admin/plugin/paypal_payment/setting"; } /** * 更新 */ @PostMapping("/update") public ResponseEntity<?> update(String displayName, String partner, PaypalPaymentPlugin.Currency currency, PaymentPlugin.FeeType feeType, BigDecimal fee, String logo, String description, @RequestParam(defaultValue = "false") Boolean isEnabled, Integer order) { PluginConfig pluginConfig = paypalPaymentPlugin.getPluginConfig(); Map<String, String> attributes = new HashMap<>(); attributes.put(PaymentPlugin.DISPLAY_NAME_ATTRIBUTE_NAME, displayName); attributes.put("partner", partner); attributes.put("currency", String.valueOf(currency)); attributes.put(PaymentPlugin.FEE_TYPE_ATTRIBUTE_NAME, String.valueOf(feeType)); attributes.put(PaymentPlugin.FEE_ATTRIBUTE_NAME, String.valueOf(fee)); attributes.put(PaymentPlugin.LOGO_ATTRIBUTE_NAME, logo); attributes.put(PaymentPlugin.DESCRIPTION_ATTRIBUTE_NAME, description); pluginConfig.setAttributes(attributes); pluginConfig.setIsEnabled(isEnabled); pluginConfig.setOrder(order); pluginConfigService.update(pluginConfig); return Results.OK; } }
[ "a12345678" ]
a12345678
519d7a3a2d6e548b2862f1c30a06a68ddad18e93
8a77b600c5676f6c5378347bc893c58b19b68fa7
/apes-system/src/main/java/top/luoqiz/system/modules/security/rest/SecurityUserController.java
6e2d094e41f866ab595c602e6501478e34eb8983
[]
no_license
luoqiz/apes-admin
40c3c5156650dca821ee1e649e8d31baa082460a
cd943cee9ead5d6c459a9eaec140bc57f26f55dd
refs/heads/master
2023-08-22T00:17:26.269284
2021-08-06T08:27:53
2021-08-06T08:27:53
393,310,281
0
0
null
null
null
null
UTF-8
Java
false
false
6,988
java
package top.luoqiz.system.modules.security.rest; import com.baomidou.mybatisplus.core.toolkit.IdWorker; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import top.luoqiz.common.web.annotation.AnonymousAccess; import top.luoqiz.common.web.extend.SysUserExtendService; import top.luoqiz.common.web.response.config.BusinessException; import top.luoqiz.common.web.response.vo.ResponseCode; import top.luoqiz.user.entity.SysUserEntity; import top.luoqiz.user.service.SysUserService; import top.luoqiz.user.vo.SysUserVo; import javax.validation.ConstraintViolation; import javax.validation.Validator; import java.time.LocalDateTime; import java.util.LinkedHashMap; import java.util.Set; /** * <p> * 系统用户 前端控制器 * </p> * * @author luoqiz * @since 2021-03-03 */ @Tag(name = "用户安全接口") @RestController @RequestMapping("/user") public class SecurityUserController { private SysUserService sysUserService; private SysUserExtendService sysUserExtendService; private PasswordEncoder passwordEncoder; private Validator validator; @Autowired public void setValidator(Validator validator) { this.validator = validator; } @Autowired public void setPasswordEncoder(PasswordEncoder passwordEncoder) { this.passwordEncoder = passwordEncoder; } @Autowired(required = false) public void setUserExtendService(SysUserExtendService sysUserExtendService) { this.sysUserExtendService = sysUserExtendService; } @Autowired public void setSysUserService(SysUserService sysUserService) { this.sysUserService = sysUserService; } /** * 获取用户信息 * * @param authentication 认证信息 * @return SysUserVo */ @Operation(summary = "获取用户信息") @GetMapping("/info") public SysUserVo info(Authentication authentication) { if (authentication == null || !authentication.isAuthenticated()) { return null; } SysUserEntity user = sysUserService.getByUsername(authentication.getName()); SysUserVo userVo = SysUserVo.fromEntity(user); if (sysUserExtendService != null) { try { userVo.setUserExtend(sysUserExtendService.getUserExtendInfo(user)); } catch (Exception e) { userVo.setUserExtend(null); e.printStackTrace(); } } return userVo; } @Operation(summary = "用户注册") @AnonymousAccess @PostMapping("/register") @Transactional(rollbackFor = Exception.class) public boolean register(@RequestBody LinkedHashMap<String, Object> param) throws JsonProcessingException { // 用户指定检测是否可以进行注册 sysUserExtendService.registerPreUserValidate(param); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); SysUserEntity user = objectMapper.readValue(objectMapper.writeValueAsString(param), SysUserEntity.class); // 验证用户是否已经存在 SysUserEntity dbUser = sysUserService.getByUsername(user.getPhone()); if (dbUser != null) { throw new BusinessException(ResponseCode.USER_IS_EXIST); } Long userId = IdWorker.getId(); param.put("userId", userId); user.setUserId(userId); user.setPassword(passwordEncoder.encode(param.getOrDefault("password", "123456").toString())); user.setIsAdmin(false); user.setUsername(user.getPhone()); user.setCreateTime(LocalDateTime.now()); checkUser(user); boolean flag = true; if (sysUserExtendService != null) { flag = sysUserExtendService.saveUserExtendInfo(param); } if (flag) { return sysUserService.save(user); } throw new BusinessException(ResponseCode.USER_ACCOUNT_EXPIRED); } @Operation(summary = "用户修改密码") @AnonymousAccess @PostMapping("/password/modify") @Transactional(rollbackFor = Exception.class) public boolean updatePassword(Authentication authentication, String newPassword) { if (authentication == null || !authentication.isAuthenticated()) { return false; } SysUserEntity user = sysUserService.getByUsername(authentication.getName()); SysUserEntity mUser = new SysUserEntity(); //此处检测密码规则 if (StringUtils.isBlank(newPassword)) { throw new BusinessException(ResponseCode.UPDATE_USER_PASSWORD_NON_COMPLIANT_RULE); } boolean flag = true; if (sysUserExtendService != null) { flag = sysUserExtendService.checkPassword(newPassword); } mUser.setUserId(user.getUserId()); mUser.setPassword(passwordEncoder.encode(newPassword)); mUser.setPwdResetTime(LocalDateTime.now()); if (flag) { return sysUserService.updateById(mUser); } throw new BusinessException(ResponseCode.UPDATE_USER_PASSWORD_NON_COMPLIANT_RULE); } @Operation(summary = "用户修改头像") @AnonymousAccess @PostMapping("/avatar") @Transactional(rollbackFor = Exception.class) public boolean updateAvatar(Authentication authentication, String avatarPath) { if (authentication == null || !authentication.isAuthenticated()) { return false; } SysUserEntity user = sysUserService.getByUsername(authentication.getName()); SysUserEntity mUser = new SysUserEntity(); if (StringUtils.isNotBlank(avatarPath)) { mUser.setUserId(user.getUserId()); mUser.setAvatarPath(avatarPath); return sysUserService.updateById(mUser); } return false; } /** * 检测注册用户信息填写是否完整 * * @param user 生成的用户实体类 */ private void checkUser(SysUserEntity user) { Set<ConstraintViolation<SysUserEntity>> constraintViolations = validator.validate(user); for (ConstraintViolation<SysUserEntity> cs : constraintViolations) { String msg = cs.getPropertyPath() + ":参数有误"; throw new BusinessException(ResponseCode.GLOBAL_PARAM_ERROR.getCode(), String.format("[%s] %s", msg, cs.getMessage())); } } }
f4d52bacf7d20b4cb365aec3bcce50420d1201ab
1c8f9d7258b282fc64e803a9d209d6f06b93ee34
/src/main/java/org/jeecgframework/web/system/service/impl/UserServiceImpl.java
bce5e42078faffa41ceb72c930bab967f6520570
[]
no_license
songchengxi/master
648624c9d6ec05a2860cdbc9ddb48c9ab6dcd58b
8c3b3d1a00d095491258c1c1f36ec8580a26a134
refs/heads/master
2021-09-06T04:55:56.634542
2018-02-02T14:11:46
2018-02-02T14:11:46
108,369,839
0
0
null
null
null
null
UTF-8
Java
false
false
3,918
java
package org.jeecgframework.web.system.service.impl; import java.util.List; import javax.servlet.http.HttpServletRequest; import com.scx.system.entity.CompanyRoleUser; import org.jeecgframework.web.system.pojo.base.TSLog; import org.jeecgframework.web.system.pojo.base.TSRoleUser; import org.jeecgframework.web.system.pojo.base.TSUser; import org.jeecgframework.web.system.service.UserService; import org.hibernate.Criteria; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.jeecgframework.core.common.service.impl.CommonServiceImpl; import org.jeecgframework.core.constant.Globals; import org.jeecgframework.core.util.BrowserUtils; import org.jeecgframework.core.util.ContextHolderUtils; import org.jeecgframework.core.util.DateUtils; import org.jeecgframework.core.util.ResourceUtil; import org.jeecgframework.core.util.oConvertUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * * @author 张代浩 * */ @Service("userService") @Transactional public class UserServiceImpl extends CommonServiceImpl implements UserService { public TSUser checkUserExits(TSUser user){ return this.commonDao.getUserByUserIdAndUserNameExits(user); } public String getUserRole(TSUser user){ return this.commonDao.getUserRole(user); } public void pwdInit(TSUser user,String newPwd) { this.commonDao.pwdInit(user,newPwd); } public int getUsersOfThisRole(String id) { Criteria criteria = getSession().createCriteria(TSRoleUser.class); criteria.add(Restrictions.eq("TSRole.id", id)); int allCounts = ((Long) criteria.setProjection( Projections.rowCount()).uniqueResult()).intValue(); return allCounts; } @Override public String trueDel(TSUser user) { String message; List<CompanyRoleUser> roleUser = this.commonDao.findByProperty(CompanyRoleUser.class, "TSUser.id", user.getId()); if (!user.getStatus().equals(Globals.User_ADMIN)) { if (roleUser.size() > 0) { // 删除用户时先删除用户和角色关系表 delRoleUser(user); this.commonDao.executeSql("delete from t_s_user_org where user_id=?", user.getId()); // 删除 用户-机构 数据 this.commonDao.delete(user); message = "用户:" + user.getUserName() + "删除成功"; this.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO); } else { this.commonDao.delete(user); message = "用户:" + user.getUserName() + "删除成功"; } } else { message = "超级管理员不可删除"; } return message; } private void delRoleUser(TSUser user) { // 同步删除用户角色关联表 List<CompanyRoleUser> roleUserList = this.commonDao.findByProperty(CompanyRoleUser.class, "TSUser.id", user.getId()); if (roleUserList.size() >= 1) { for (CompanyRoleUser roleUser : roleUserList) { this.commonDao.delete(roleUser); } } } /** * 添加日志 */ private void addLog(String logcontent, Short loglevel, Short operatetype) { HttpServletRequest request = ContextHolderUtils.getRequest(); String broswer = BrowserUtils.checkBrowse(request); TSLog log = new TSLog(); log.setLogcontent(logcontent); log.setLoglevel(loglevel); log.setOperatetype(operatetype); log.setNote(oConvertUtils.getIp()); log.setBroswer(broswer); log.setOperatetime(DateUtils.gettimestamp()); // log.setTSUser(ResourceUtil.getSessionUser()); /*start chenqian 201708031TASK #2317 【改造】系统日志表,增加两个字段,避免关联查询 [操作人账号] [操作人名字]*/ TSUser u = ResourceUtil.getSessionUser(); log.setUserid(u.getId()); log.setUsername(u.getUserName()); log.setRealname(u.getRealName()); /*update-end--Author chenqian 201708031TASK #2317 【改造】系统日志表,增加两个字段,避免关联查询 [操作人账号] [操作人名字]*/ commonDao.save(log); } }
10ea42510629a526d16ad43736741922d493eecd
526bb0f0e257e3ebdfea2054a9066716744a4950
/spring-web/src/main/java/vn/topica/itlab4/springweb/controller/ProductController.java
5d393f9c3ee2cfb1b875969babd8fce485b3b723
[]
no_license
khanhnguyenbn/spring-web
5e31ee880c25db20e94566801cfc6b89909656a4
f890a85c703e009dbdd5d2e40cf8fac9a39ea483
refs/heads/master
2022-12-25T17:20:28.297348
2019-10-15T03:16:41
2019-10-15T03:16:41
210,903,687
0
0
null
2022-12-16T08:23:01
2019-09-25T17:34:45
CSS
UTF-8
Java
false
false
2,072
java
package vn.topica.itlab4.springweb.controller; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; 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.servlet.ModelAndView; import vn.topica.itlab4.springweb.model.ProductModel; import vn.topica.itlab4.springweb.services.IProductService; @Controller public class ProductController { @Autowired private IProductService productService; @RequestMapping(value = "/web/product/home", method = RequestMethod.GET) public ModelAndView homePage() { ModelAndView modelAndView = new ModelAndView("/home/index"); List<ProductModel> products = productService.getAllProduct(); modelAndView.addObject("products", products); Set<String> typeProductSet = productService.getAllTypeOfProduct(); modelAndView.addObject("types", typeProductSet); System.out.println("this is product controller"); System.out.println("the change 2"); System.out.println("the change 3"); return modelAndView; } @RequestMapping(value = "/web/product/{id}") public ModelAndView getProductDetail(@PathVariable("id") Integer id) { ProductModel productModel = productService.findProductById(id); ModelAndView modelAndView = new ModelAndView("/detail/index"); modelAndView.addObject("product", productModel); return modelAndView; } @PostMapping(value = "/web/product") public ModelAndView searchProductByName(@RequestParam String productName) { ModelAndView modelAndView = new ModelAndView("/home/index"); List<ProductModel> products = productService.findProductByName(productName); modelAndView.addObject("products", products); return modelAndView; } }
648d4b540becaf507b2ba896bacf5b52ead3945e
b43d7769bdd97adcf647193fb39c4a59662dceba
/hoodie-common/src/main/java/com/uber/hoodie/exception/HoodieIndexException.java
93da5b9d87a3c7c9bb4524187e8c929cda4b59b3
[ "BSD-3-Clause", "MIT", "LicenseRef-scancode-protobuf", "CC-BY-3.0", "Apache-2.0" ]
permissive
jianxu/hoodie
34e56c9f7ba972759bb979beaef4a60715cdc4bb
8529fa61149c41edd2b4d2e6b6e17912370643d3
refs/heads/master
2020-12-07T02:39:34.721812
2017-10-10T21:07:24
2017-11-08T19:52:52
95,495,458
0
0
null
2017-06-26T22:39:41
2017-06-26T22:39:41
null
UTF-8
Java
false
false
979
java
/* * Copyright (c) 2016 Uber Technologies, Inc. ([email protected]) * * 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.uber.hoodie.exception; /** * <p> * Exception thrown for HoodieIndex related errors. * </p> */ public class HoodieIndexException extends HoodieException { public HoodieIndexException(String msg) { super(msg); } public HoodieIndexException(String msg, Throwable e) { super(msg, e); } }
d362bbf3044c9c843b05bcdb10fcf44a7e7b6e78
2804968f274b13f058dc98f3adeb2f984c347177
/app/src/main/java/tj/beataddiction/ResetDataReceiver.java
feca74f021555b7975ffd165de92863effc6c7dc
[]
no_license
ridwanultanvir/BeatAddiction
60a498002a04dad62aadc928f22bada034a50d66
19466e946ceae3b980a522ab0888f94cacb084d0
refs/heads/master
2022-07-18T08:30:57.315986
2020-05-21T23:13:12
2020-05-21T23:13:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
406
java
package tj.beataddiction; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class ResetDataReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { DatabaseHelper dbHelper = new DatabaseHelper(context); dbHelper.resetAllIsUsageExceeded(); dbHelper.close(); } }
6899ff0ce033ef7d0841a98a437db94ae18a61a0
cad84a0b50222f584d65a05e7ef0f4111371bba0
/practiceJava/src/lintCode/Q93_BalancedBinaryTree.java
75d2d89e2a5153f014850b729e6b72440945f8e3
[]
no_license
pengshuai2010/practiceJava
cb14348811160789d1a59df69e5c7d7eb1319688
a1e03dc0290ab829e0458db52a406aaf74f54d15
refs/heads/master
2021-03-13T01:55:26.656627
2017-04-29T03:31:15
2017-04-29T03:31:15
38,922,341
2
0
null
null
null
null
UTF-8
Java
false
false
1,605
java
package lintCode; import basicAlgorithms.TreeNode; /** * Created by speng on 8/10/16. */ public class Q93_BalancedBinaryTree { /** * @param root: The root of binary tree. * @return: True if this Binary tree is Balanced, or false. */ public boolean isBalanced(TreeNode root) { return -1 != getTreeHeight(root); } /** * Divided and conquer. * Definition of balanced tree: a tree is balanced if and only if its left and right subtree are both balanced, and * the difference of the height of left and right subtree is no more than 1. * The definition itself follows a divided-and-conquer approach. From the definition we know that for each subtree * we need two kinds of information: height and if its balanced. One way is to definde a ResultType class. But since * height is no longer useful once we know the tree is not balanced, we can use just one integer as return value. * Return value is -1 means that the tree is not balanced, otherwise the return value is the height of the tree. * * @param root * @return */ private int getTreeHeight(TreeNode root) { if (root == null) { return 0; } int leftHeight = getTreeHeight(root.left); if (leftHeight == -1) { return -1; } int rightHeight = getTreeHeight(root.right); if (rightHeight == -1) { return -1; } if (Math.abs(leftHeight - rightHeight) > 1) { return -1; } return Math.max(leftHeight, rightHeight) + 1; } }
87b5a0d83feaaffb5234d910087bfe477ba16f1f
f4d7f96559a64ce5d8cdc48e4b78ab1a0652034a
/trApi/src/main/java/com/taoren/model/lb/Label.java
06d1b4c52f2e345774fff87ce43532c806867d83
[]
no_license
wangss/du-ma-se
84d6cbff38f23b612e4a96a56a9a89278a051324
4de4361d7fa110ff50d9b364e77eaa911d4dd5e5
refs/heads/master
2021-01-10T01:37:01.456403
2015-12-08T16:14:40
2015-12-08T16:14:40
47,631,479
0
0
null
null
null
null
UTF-8
Java
false
false
4,533
java
package com.taoren.model.lb; import java.io.Serializable; import java.sql.Timestamp; import java.util.List; /** * Created by wangshuisheng on 2015/5/26. */ public class Label implements Serializable { private Long id; private Long uid;//所属人id private String labelName; private String labelDetail; private Timestamp addTime; private Timestamp editTime; private Double longitude;//发布经度 private Double latitude;//发布纬度 private String geohash;//经纬度hash private String area;//发布地区 private Integer positionType;//坐标类型 1固定 2移动 private Integer deadlineType;//有效时间类型 1永久 2时间段 private Timestamp startTime;//有效开始时间 private Timestamp endTime;//有效结束时间 private Integer zan;//赞数量 private Integer commentCount;//评论数 private boolean haveZan;//是否已赞 private Long zanUid; private String msg;//msg private Integer status;//标签状态 1创建 2生效 3失效 4废除 private List<LabelMedia> mediaList; private List<LabelZanUser> zanUserList; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUid() { return uid; } public void setUid(Long uid) { this.uid = uid; } public String getLabelName() { return labelName; } public void setLabelName(String labelName) { this.labelName = labelName; } public String getLabelDetail() { return labelDetail; } public void setLabelDetail(String labelDetail) { this.labelDetail = labelDetail; } public Timestamp getAddTime() { return addTime; } public void setAddTime(Timestamp addTime) { this.addTime = addTime; } public Timestamp getEditTime() { return editTime; } public void setEditTime(Timestamp editTime) { this.editTime = editTime; } public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public Integer getDeadlineType() { return deadlineType; } public void setDeadlineType(Integer deadlineType) { this.deadlineType = deadlineType; } public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } public String getGeohash() { return geohash; } public void setGeohash(String geohash) { this.geohash = geohash; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } public Integer getPositionType() { return positionType; } public void setPositionType(Integer positionType) { this.positionType = positionType; } public Timestamp getStartTime() { return startTime; } public void setStartTime(Timestamp startTime) { this.startTime = startTime; } public Timestamp getEndTime() { return endTime; } public void setEndTime(Timestamp endTime) { this.endTime = endTime; } public Integer getZan() { return zan; } public void setZan(Integer zan) { this.zan = zan; } public boolean isHaveZan() { return haveZan; } public void setHaveZan(boolean haveZan) { this.haveZan = haveZan; } public Long getZanUid() { return zanUid; } public void setZanUid(Long zanUid) { this.zanUid = zanUid; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public List<LabelMedia> getMediaList() { return mediaList; } public void setMediaList(List<LabelMedia> mediaList) { this.mediaList = mediaList; } public List<LabelZanUser> getZanUserList() { return zanUserList; } public void setZanUserList(List<LabelZanUser> zanUserList) { this.zanUserList = zanUserList; } public Integer getCommentCount() { return commentCount; } public void setCommentCount(Integer commentCount) { this.commentCount = commentCount; } }
e5981b83f71e1a8b56b8fb7520aac063fc61c368
180936d239d44b077cbb3728fdb6b195f52726d9
/src/main/java/com/jj/ranger/client/v1/domain/SearchRepositoriesCriteria.java
744cb7f9503cdad8654ce1cd2028d6cfe65a14e3
[]
no_license
jjmeyer0/ranger-client
11602e5927f6e0fa3d50b4f6d20e944c44ee51db
d4a73ace6a359a62276a72d0c4d4320696f690e1
refs/heads/master
2021-01-20T22:20:18.211282
2016-06-28T18:15:32
2016-06-28T18:15:32
62,163,929
0
1
null
null
null
null
UTF-8
Java
false
false
2,180
java
package com.jj.ranger.client.v1.domain; public class SearchRepositoriesCriteria { private Integer pageSize; private Integer startIndex; private String name; private String type; private Boolean status; public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public Integer getStartIndex() { return startIndex; } public void setStartIndex(Integer startIndex) { this.startIndex = startIndex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Boolean isStatus() { return status; } public void setStatus(Boolean status) { this.status = status; } @Override public String toString() { return "SearchRepositoriesCriteria{" + "pageSize=" + pageSize + ", startIndex=" + startIndex + ", name='" + name + '\'' + ", type='" + type + '\'' + ", status=" + status + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SearchRepositoriesCriteria that = (SearchRepositoriesCriteria) o; if (pageSize != that.pageSize) return false; if (startIndex != that.startIndex) return false; if (status != that.status) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; return type != null ? type.equals(that.type) : that.type == null; } @Override public int hashCode() { Integer result = pageSize; result = 31 * result + startIndex; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + (status ? 1 : 0); return result; } }
f43486ad2bd0cbc699d9987d075cef684e153234
2116fd1518705b413df43e243a3cea576c6a5933
/bloSSOME2/src/blossome/command/message/CmdMsgSendList.java
87dd4f703d26f5162269a7167814f4db3a169c1d
[]
no_license
kws4211/jsp
433b0a40224e11c0a00213991cbe9efb706a1732
b483d5e60022caf5f53263842f0cc65be40e3852
refs/heads/master
2021-01-20T07:23:42.532659
2017-05-17T07:24:45
2017-05-17T07:24:45
89,915,762
0
0
null
null
null
null
UTF-8
Java
false
false
825
java
package blossome.command.message; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import blossome.command.Command; import blossome.command.CommandException; import blossome.session.MessageRepository; import blossome.vo.MsgVO; public class CmdMsgSendList implements Command{ private String next; public CmdMsgSendList( String _next ){ next = _next; } public String execute(HttpServletRequest request) throws CommandException { HttpSession session = request.getSession(); String id = (String)session.getAttribute("id"); //msg 리스를 불러와서 출력 MessageRepository repo = new MessageRepository(); List<MsgVO> list = repo.Sendalllist(id); request.setAttribute("list", list); return next; } }
800b1319d5247d803c5d62da25db5fa0d9788e64
0288e3f1c97335267febfe16aafdf4c88b34a077
/other/RMI_BioAPI_AsteriskJava_Server.java
e2a0ff030af0ecf8b9e13a0989f7d74b60578a6c
[]
no_license
x358792975/RMI-Project
eb1c6057080f42be4bb8dadf32318c59de88e6fa
8090d9518b5b71d94d158d47144752a2c3458746
refs/heads/master
2021-01-20T02:37:42.574410
2017-04-27T05:00:06
2017-04-27T05:00:06
89,431,244
0
0
null
null
null
null
UTF-8
Java
false
false
3,701
java
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.rmi.RemoteException; import java.net.*; import java.rmi.server.*; import java.rmi.Naming; /** * */ /** * @author bon * */ public class RMI_BioAPI_AsteriskJava_Server extends UnicastRemoteObject implements RMI_BioAPI_AsteriskJava_Interface { public RMI_BioAPI_AsteriskJava_Server(int port) throws RemoteException { super(port); } /* (non-Javadoc) * @see RMI_BioAPI_AsteriskJava_Interface#RPC_FileRead(java.lang.String, java.lang.String) */ @Override public void RPC_FileRead(String Service_UID, String srcFileName, String socket_ip, int socket_port, String remote_fileName) throws RemoteException { // TODO Auto-generated method stub Socket soc; PrintWriter pw=null; // BufferedReader br = null; File fileName = new File(srcFileName); BufferedReader brf=null; try { brf = new BufferedReader(new InputStreamReader( new FileInputStream(fileName.getAbsolutePath()))); }catch ( IOException ioe ) {throw new RuntimeException(ioe);} try { if ( brf == null ) throw new RuntimeException("Cannot read from closed file " + fileName.getAbsolutePath() + "."); try { // System.out.println("Server address connected to is "+addr+" and port is "+port); soc = new Socket(socket_ip, socket_port); pw=new PrintWriter(soc.getOutputStream(), true); pw.println("StartXfer"); //Signaling message to start xfer to the remote socket server pw.println(remote_fileName); //Signaling message about remote file name String line = brf.readLine(); int counter=0; while ( line != null){ System.out.println(line); pw.println(line); counter++; line = brf.readLine(); } pw.println("Done!!"); //Signaling message to terminate the remote socket server brf.close(); soc.close(); } catch (UnknownHostException e) { System.err.println("Don't know about host."); System.exit(1); e.printStackTrace(); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to server."); System.exit(1); e.printStackTrace(); } }catch (Exception e) {throw new RuntimeException(e);} } // method RPC_FileRead() /** * @param args */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub if (args.length != 1) { System.out.println ("Syntax - java RMI_BioAPI_AsteriskJava_Server_Package/RMI_BioAPI_AsteriskJava_Server_Impl host_port"); System.exit(1); } //to client ip System.setProperty("java.rmi.server.hostname","127.0.0.1"); System.setProperty("java.rmi.server.useCodbaseOnly","true"); // Create an instance of our service server ... RMI_BioAPI_AsteriskJava_Server svr = new RMI_BioAPI_AsteriskJava_Server(Integer.parseInt(args[0])); // System.out.println("RmiRegistry listens at port 1099 "); System.out.println("AsteriskJava BSP Server is ready to listen on " + args[0]); // System.out.println(InetAddress.getLocalHost().getHostName()); Naming.bind("RMI_BioAPI_AsteriskJava", svr); System.out.println("BioAPI AsteriskJava RMI server starts ... "); } }
b476132f743547edc4040a92d6c4d1f77e0446a3
bb9140f335d6dc44be5b7b848c4fe808b9189ba4
/Extra-DS/Corpus/class/aspectj/1466.java
0b60f7abf3acd6db1cf5f3cd8483ea7f4d198d48
[]
no_license
masud-technope/EMSE-2019-Replication-Package
4fc04b7cf1068093f1ccf064f9547634e6357893
202188873a350be51c4cdf3f43511caaeb778b1e
refs/heads/master
2023-01-12T21:32:46.279915
2022-12-30T03:22:15
2022-12-30T03:22:15
186,221,579
5
3
null
null
null
null
UTF-8
Java
false
false
1,089
java
/* ******************************************************************* * Copyright (c) 2005 Contributors. * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Eclipse Public License v1.0 * which accompanies this distribution and is available at * http://eclipse.org/legal/epl-v10.html * * Contributors: * Adrian Colyer Initial implementation * ******************************************************************/ package org.aspectj.weaver.reflect; import org.aspectj.weaver.tools.PointcutParameter; public class PointcutParameterImpl implements PointcutParameter { String name; Class type; Object binding; public PointcutParameterImpl(String name, Class type) { this.name = name; this.type = type; } public String getName() { return name; } public Class getType() { return type; } public Object getBinding() { return binding; } void setBinding(Object boundValue) { this.binding = boundValue; } }
477459d31222bbd99a1388aa2e21ed56af15255f
29b72f6cc5730f990262cb24a336adf8d13a5a31
/sdk/src/main/java/com/finbourne/lusid/model/AllocationSetRequest.java
9228adbb45e16c0e3d1512a20609483666bc9417
[ "MIT" ]
permissive
bogdanLicaFinbourne/lusid-sdk-java-preview
0c956b453f5dd37888f11e0128d8a2e32abda236
3e6d1ed20bf398fafed58364360895a1f2f0476f
refs/heads/master
2023-04-06T06:21:49.057202
2021-04-19T18:50:06
2021-04-19T18:50:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
32,151
java
/* * LUSID API * # Introduction This page documents the [LUSID APIs](https://www.lusid.com/api/swagger), which allows authorised clients to query and update their data within the LUSID platform. SDKs to interact with the LUSID APIs are available in the following languages and frameworks: * [C#](https://github.com/finbourne/lusid-sdk-csharp) * [Java](https://github.com/finbourne/lusid-sdk-java) * [JavaScript](https://github.com/finbourne/lusid-sdk-js) * [Python](https://github.com/finbourne/lusid-sdk-python) * [Angular](https://github.com/finbourne/lusid-sdk-angular) # Data Model The LUSID API has a relatively lightweight but extremely powerful data model. One of the goals of LUSID was not to enforce on clients a single rigid data model but rather to provide a flexible foundation onto which clients can map their own data models. The core entities in LUSID provide a minimal structure and set of relationships, and the data model can be extended using Properties. The LUSID data model is exposed through the LUSID APIs. The APIs provide access to both business objects and the meta data used to configure the systems behaviours. The key business entities are: - * **Portfolios** A portfolio is a container for transactions and holdings (a **Transaction Portfolio**) or constituents (a **Reference Portfolio**). * **Derived Portfolios**. Derived Portfolios allow Portfolios to be created based on other Portfolios, by overriding or adding specific items. * **Holdings** A Holding is a quantity of an Instrument or a balance of cash within a Portfolio. Holdings can only be adjusted via Transactions. * **Transactions** A Transaction is an economic event that occurs in a Portfolio, causing its holdings to change. * **Corporate Actions** A corporate action is a market event which occurs to an Instrument and thus applies to all portfolios which holding the instrument. Examples are stock splits or mergers. * **Constituents** A constituent is a record in a Reference Portfolio containing an Instrument and an associated weight. * **Instruments** An instrument represents a currency, tradable instrument or OTC contract that is attached to a transaction and a holding. * **Properties** All major entities allow additional user defined properties to be associated with them. For example, a Portfolio manager may be associated with a portfolio. Meta data includes: - * **Transaction Types** Transactions are booked with a specific transaction type. The types are client defined and are used to map the Transaction to a series of movements which update the portfolio holdings. * **Properties Types** Types of user defined properties used within the system. ## Scope All data in LUSID is segregated at the client level. Entities in LUSID are identifiable by a unique code. Every entity lives within a logical data partition known as a Scope. Scope is an identity namespace allowing two entities with the same unique code to co-exist within individual address spaces. For example, prices for equities from different vendors may be uploaded into different scopes such as `client/vendor1` and `client/vendor2`. A portfolio may then be valued using either of the price sources by referencing the appropriate scope. LUSID Clients cannot access scopes of other clients. ## Instruments LUSID has its own built-in instrument master which you can use to master your own instrument universe. Every instrument must be created with one or more unique market identifiers, such as [FIGI](https://openfigi.com/). For any non-listed instruments (eg OTCs), you can upload an instrument against a custom ID of your choosing. In addition, LUSID will allocate each instrument a unique 'LUSID instrument identifier'. The LUSID instrument identifier is what is used when uploading transactions, holdings, prices, etc. The API exposes an `instrument/lookup` endpoint which can be used to lookup these LUSID identifiers using their market identifiers. Cash can be referenced using the ISO currency code prefixed with \"`CCY_`\" e.g. `CCY_GBP` ## Instrument Data Instrument data can be uploaded to the system using the [Instrument Properties](#operation/UpsertInstrumentsProperties) endpoint. | Field|Type|Description | | ---|---|--- | | Key|propertykey|The key of the property. This takes the format {domain}/{scope}/{code} e.g. 'Instrument/system/Name' or 'Transaction/strategy/quantsignal'. | | Value|string|The value of the property. | | EffectiveFrom|datetimeoffset|The effective datetime from which the property is valid. | | EffectiveUntil|datetimeoffset|The effective datetime until which the property is valid. If not supplied this will be valid indefinitely, or until the next 'effectiveFrom' datetime of the property. | ## Transaction Portfolios Portfolios are the top-level entity containers within LUSID, containing transactions, corporate actions and holdings. The transactions build up the portfolio holdings on which valuations, analytics profit & loss and risk can be calculated. Properties can be associated with Portfolios to add in additional data. Portfolio properties can be changed over time, for example to allow a Portfolio Manager to be linked with a Portfolio. Additionally, portfolios can be securitised and held by other portfolios, allowing LUSID to perform \"drill-through\" into underlying fund holdings ### Derived Portfolios LUSID also allows for a portfolio to be composed of another portfolio via derived portfolios. A derived portfolio can contain its own transactions and also inherits any transactions from its parent portfolio. Any changes made to the parent portfolio are automatically reflected in derived portfolio. Derived portfolios in conjunction with scopes are a powerful construct. For example, to do pre-trade what-if analysis, a derived portfolio could be created a new namespace linked to the underlying live (parent) portfolio. Analysis can then be undertaken on the derived portfolio without affecting the live portfolio. ### Transactions A transaction represents an economic activity against a Portfolio. Transactions are processed according to a configuration. This will tell the LUSID engine how to interpret the transaction and correctly update the holdings. LUSID comes with a set of transaction types you can use out of the box, or you can configure your own set(s) of transactions. For more details see the [LUSID Getting Started Guide for transaction configuration.](https://support.lusid.com/configuring-transaction-types) | Field|Type|Description | | ---|---|--- | | TransactionId|string|The unique identifier for the transaction. | | Type|string|The type of the transaction e.g. 'Buy', 'Sell'. The transaction type should have been pre-configured via the System Configuration API endpoint. If it hasn't been pre-configured the transaction will still be updated or inserted however you will be unable to generate the resultant holdings for the portfolio that contains this transaction as LUSID does not know how to process it. | | InstrumentIdentifiers|map|A set of instrument identifiers to use to resolve the transaction to a unique instrument. | | TransactionDate|dateorcutlabel|The date of the transaction. | | SettlementDate|dateorcutlabel|The settlement date of the transaction. | | Units|decimal|The number of units transacted in the associated instrument. | | TransactionPrice|transactionprice|The price for each unit of the transacted instrument in the transaction currency. | | TotalConsideration|currencyandamount|The total value of the transaction in the settlement currency. | | ExchangeRate|decimal|The exchange rate between the transaction and settlement currency (settlement currency being represented by the TotalConsideration.Currency). For example if the transaction currency is in USD and the settlement currency is in GBP this this the USD/GBP rate. | | TransactionCurrency|currency|The transaction currency. | | Properties|map|Set of unique transaction properties and associated values to store with the transaction. Each property must be from the 'Transaction' domain. | | CounterpartyId|string|The identifier for the counterparty of the transaction. | | Source|string|The source of the transaction. This is used to look up the appropriate transaction group set in the transaction type configuration. | From these fields, the following values can be calculated * **Transaction value in Transaction currency**: TotalConsideration / ExchangeRate * **Transaction value in Portfolio currency**: Transaction value in Transaction currency * TradeToPortfolioRate #### Example Transactions ##### A Common Purchase Example Three example transactions are shown in the table below. They represent a purchase of USD denominated IBM shares within a Sterling denominated portfolio. * The first two transactions are for separate buy and fx trades * Buying 500 IBM shares for $71,480.00 * A spot foreign exchange conversion to fund the IBM purchase. (Buy $71,480.00 for &#163;54,846.60) * The third transaction is an alternate version of the above trades. Buying 500 IBM shares and settling directly in Sterling. | Column | Buy Trade | Fx Trade | Buy Trade with foreign Settlement | | ----- | ----- | ----- | ----- | | TransactionId | FBN00001 | FBN00002 | FBN00003 | | Type | Buy | FxBuy | Buy | | InstrumentIdentifiers | { \"figi\", \"BBG000BLNNH6\" } | { \"CCY\", \"CCY_USD\" } | { \"figi\", \"BBG000BLNNH6\" } | | TransactionDate | 2018-08-02 | 2018-08-02 | 2018-08-02 | | SettlementDate | 2018-08-06 | 2018-08-06 | 2018-08-06 | | Units | 500 | 71480 | 500 | | TransactionPrice | 142.96 | 1 | 142.96 | | TradeCurrency | USD | USD | USD | | ExchangeRate | 1 | 0.7673 | 0.7673 | | TotalConsideration.Amount | 71480.00 | 54846.60 | 54846.60 | | TotalConsideration.Currency | USD | GBP | GBP | | Trade/default/TradeToPortfolioRate&ast; | 0.7673 | 0.7673 | 0.7673 | [&ast; This is a property field] ##### A Forward FX Example LUSID has a flexible transaction modelling system, meaning there are a number of different ways of modelling forward fx trades. The default LUSID transaction types are FwdFxBuy and FwdFxSell. Using these transaction types, LUSID will generate two holdings for each Forward FX trade, one for each currency in the trade. An example Forward Fx trade to sell GBP for USD in a JPY-denominated portfolio is shown below: | Column | Forward 'Sell' Trade | Notes | | ----- | ----- | ---- | | TransactionId | FBN00004 | | | Type | FwdFxSell | | | InstrumentIdentifiers | { \"Instrument/default/Currency\", \"GBP\" } | | | TransactionDate | 2018-08-02 | | | SettlementDate | 2019-02-06 | Six month forward | | Units | 10000.00 | Units of GBP | | TransactionPrice | 1 | | | TradeCurrency | GBP | Currency being sold | | ExchangeRate | 1.3142 | Agreed rate between GBP and USD | | TotalConsideration.Amount | 13142.00 | Amount in the settlement currency, USD | | TotalConsideration.Currency | USD | Settlement currency | | Trade/default/TradeToPortfolioRate | 142.88 | Rate between trade currency, GBP and portfolio base currency, JPY | Please note that exactly the same economic behaviour could be modelled using the FwdFxBuy Transaction Type with the amounts and rates reversed. ### Holdings A holding represents a position in an instrument or cash on a given date. | Field|Type|Description | | ---|---|--- | | InstrumentUid|string|The unqiue Lusid Instrument Id (LUID) of the instrument that the holding is in. | | SubHoldingKeys|map|The sub-holding properties which identify the holding. Each property will be from the 'Transaction' domain. These are configured when a transaction portfolio is created. | | Properties|map|The properties which have been requested to be decorated onto the holding. These will be from the 'Instrument' or 'Holding' domain. | | HoldingType|string|The type of the holding e.g. Position, Balance, CashCommitment, Receivable, ForwardFX etc. | | Units|decimal|The total number of units of the holding. | | SettledUnits|decimal|The total number of settled units of the holding. | | Cost|currencyandamount|The total cost of the holding in the transaction currency. | | CostPortfolioCcy|currencyandamount|The total cost of the holding in the portfolio currency. | | Transaction|transaction|The transaction associated with an unsettled holding. | | Currency|currency|The holding currency. | ## Corporate Actions Corporate actions are represented within LUSID in terms of a set of instrument-specific 'transitions'. These transitions are used to specify the participants of the corporate action, and the effect that the corporate action will have on holdings in those participants. ### Corporate Action | Field|Type|Description | | ---|---|--- | | CorporateActionCode|code|The unique identifier of this corporate action | | Description|string| | | AnnouncementDate|datetimeoffset|The announcement date of the corporate action | | ExDate|datetimeoffset|The ex date of the corporate action | | RecordDate|datetimeoffset|The record date of the corporate action | | PaymentDate|datetimeoffset|The payment date of the corporate action | | Transitions|corporateactiontransition[]|The transitions that result from this corporate action | ### Transition | Field|Type|Description | | ---|---|--- | | InputTransition|corporateactiontransitioncomponent|Indicating the basis of the corporate action - which security and how many units | | OutputTransitions|corporateactiontransitioncomponent[]|What will be generated relative to the input transition | ### Example Corporate Action Transitions #### A Dividend Action Transition In this example, for each share of IBM, 0.20 units (or 20 pence) of GBP are generated. | Column | Input Transition | Output Transition | | ----- | ----- | ----- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"ccy\" : \"CCY_GBP\" } | | Units Factor | 1 | 0.20 | | Cost Factor | 1 | 0 | #### A Split Action Transition In this example, for each share of IBM, we end up with 2 units (2 shares) of IBM, with total value unchanged. | Column | Input Transition | Output Transition | | ----- | ----- | ----- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000BLNNH6\" } | | Units Factor | 1 | 2 | | Cost Factor | 1 | 1 | #### A Spinoff Action Transition In this example, for each share of IBM, we end up with 1 unit (1 share) of IBM and 3 units (3 shares) of Celestica, with 85% of the value remaining on the IBM share, and 5% in each Celestica share (15% total). | Column | Input Transition | Output Transition 1 | Output Transition 2 | | ----- | ----- | ----- | ----- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000HBGRF3\" } | | Units Factor | 1 | 1 | 3 | | Cost Factor | 1 | 0.85 | 0.15 | ## Reference Portfolios Reference portfolios are portfolios that contain constituents with weights. They are designed to represent entities such as indices and benchmarks. ### Constituents | Field|Type|Description | | ---|---|--- | | InstrumentIdentifiers|map|Unique instrument identifiers | | InstrumentUid|string|LUSID's internal unique instrument identifier, resolved from the instrument identifiers | | Currency|decimal| | | Weight|decimal| | | FloatingWeight|decimal| | ## Portfolio Groups Portfolio groups allow the construction of a hierarchy from portfolios and groups. Portfolio operations on the group are executed on an aggregated set of portfolios in the hierarchy. For example: * Global Portfolios _(group)_ * APAC _(group)_ * Hong Kong _(portfolio)_ * Japan _(portfolio)_ * Europe _(group)_ * France _(portfolio)_ * Germany _(portfolio)_ * UK _(portfolio)_ In this example **Global Portfolios** is a group that consists of an aggregate of **Hong Kong**, **Japan**, **France**, **Germany** and **UK** portfolios. ## Properties Properties are key-value pairs that can be applied to any entity within a domain (where a domain is `trade`, `portfolio`, `security` etc). Properties must be defined before use with a `PropertyDefinition` and can then subsequently be added to entities. ## Schema A detailed description of the entities used by the API and parameters for endpoints which take a JSON document can be retrieved via the `schema` endpoint. ## Meta data The following headers are returned on all responses from LUSID | Name | Purpose | | --- | --- | | lusid-meta-duration | Duration of the request | | lusid-meta-success | Whether or not LUSID considered the request to be successful | | lusid-meta-requestId | The unique identifier for the request | | lusid-schema-url | Url of the schema for the data being returned | | lusid-property-schema-url | Url of the schema for any properties | # Error Codes | Code|Name|Description | | ---|---|--- | | <a name=\"-10\">-10</a>|Server Configuration Error| | | <a name=\"-1\">-1</a>|Unknown error|An unexpected error was encountered on our side. | | <a name=\"102\">102</a>|Version Not Found| | | <a name=\"103\">103</a>|Api Rate Limit Violation| | | <a name=\"104\">104</a>|Instrument Not Found| | | <a name=\"105\">105</a>|Property Not Found| | | <a name=\"106\">106</a>|Portfolio Recursion Depth| | | <a name=\"108\">108</a>|Group Not Found| | | <a name=\"109\">109</a>|Portfolio Not Found| | | <a name=\"110\">110</a>|Property Schema Not Found| | | <a name=\"111\">111</a>|Portfolio Ancestry Not Found| | | <a name=\"112\">112</a>|Portfolio With Id Already Exists| | | <a name=\"113\">113</a>|Orphaned Portfolio| | | <a name=\"119\">119</a>|Missing Base Claims| | | <a name=\"121\">121</a>|Property Not Defined| | | <a name=\"122\">122</a>|Cannot Delete System Property| | | <a name=\"123\">123</a>|Cannot Modify Immutable Property Field| | | <a name=\"124\">124</a>|Property Already Exists| | | <a name=\"125\">125</a>|Invalid Property Life Time| | | <a name=\"126\">126</a>|Property Constraint Style Excludes Properties| | | <a name=\"127\">127</a>|Cannot Modify Default Data Type| | | <a name=\"128\">128</a>|Group Already Exists| | | <a name=\"129\">129</a>|No Such Data Type| | | <a name=\"130\">130</a>|Undefined Value For Data Type| | | <a name=\"131\">131</a>|Unsupported Value Type Defined On Data Type| | | <a name=\"132\">132</a>|Validation Error| | | <a name=\"133\">133</a>|Loop Detected In Group Hierarchy| | | <a name=\"134\">134</a>|Undefined Acceptable Values| | | <a name=\"135\">135</a>|Sub Group Already Exists| | | <a name=\"138\">138</a>|Price Source Not Found| | | <a name=\"139\">139</a>|Analytic Store Not Found| | | <a name=\"141\">141</a>|Analytic Store Already Exists| | | <a name=\"143\">143</a>|Client Instrument Already Exists| | | <a name=\"144\">144</a>|Duplicate In Parameter Set| | | <a name=\"147\">147</a>|Results Not Found| | | <a name=\"148\">148</a>|Order Field Not In Result Set| | | <a name=\"149\">149</a>|Operation Failed| | | <a name=\"150\">150</a>|Elastic Search Error| | | <a name=\"151\">151</a>|Invalid Parameter Value| | | <a name=\"153\">153</a>|Command Processing Failure| | | <a name=\"154\">154</a>|Entity State Construction Failure| | | <a name=\"155\">155</a>|Entity Timeline Does Not Exist| | | <a name=\"156\">156</a>|Concurrency Conflict Failure| | | <a name=\"157\">157</a>|Invalid Request| | | <a name=\"158\">158</a>|Event Publish Unknown| | | <a name=\"159\">159</a>|Event Query Failure| | | <a name=\"160\">160</a>|Blob Did Not Exist| | | <a name=\"162\">162</a>|Sub System Request Failure| | | <a name=\"163\">163</a>|Sub System Configuration Failure| | | <a name=\"165\">165</a>|Failed To Delete| | | <a name=\"166\">166</a>|Upsert Client Instrument Failure| | | <a name=\"167\">167</a>|Illegal As At Interval| | | <a name=\"168\">168</a>|Illegal Bitemporal Query| | | <a name=\"169\">169</a>|Invalid Alternate Id| | | <a name=\"170\">170</a>|Cannot Add Source Portfolio Property Explicitly| | | <a name=\"171\">171</a>|Entity Already Exists In Group| | | <a name=\"173\">173</a>|Entity With Id Already Exists| | | <a name=\"174\">174</a>|Derived Portfolio Details Do Not Exist| | | <a name=\"176\">176</a>|Portfolio With Name Already Exists| | | <a name=\"177\">177</a>|Invalid Transactions| | | <a name=\"178\">178</a>|Reference Portfolio Not Found| | | <a name=\"179\">179</a>|Duplicate Id| | | <a name=\"180\">180</a>|Command Retrieval Failure| | | <a name=\"181\">181</a>|Data Filter Application Failure| | | <a name=\"182\">182</a>|Search Failed| | | <a name=\"183\">183</a>|Movements Engine Configuration Key Failure| | | <a name=\"184\">184</a>|Fx Rate Source Not Found| | | <a name=\"185\">185</a>|Accrual Source Not Found| | | <a name=\"186\">186</a>|Access Denied| | | <a name=\"187\">187</a>|Invalid Identity Token| | | <a name=\"188\">188</a>|Invalid Request Headers| | | <a name=\"189\">189</a>|Price Not Found| | | <a name=\"190\">190</a>|Invalid Sub Holding Keys Provided| | | <a name=\"191\">191</a>|Duplicate Sub Holding Keys Provided| | | <a name=\"192\">192</a>|Cut Definition Not Found| | | <a name=\"193\">193</a>|Cut Definition Invalid| | | <a name=\"194\">194</a>|Time Variant Property Deletion Date Unspecified| | | <a name=\"195\">195</a>|Perpetual Property Deletion Date Specified| | | <a name=\"196\">196</a>|Time Variant Property Upsert Date Unspecified| | | <a name=\"197\">197</a>|Perpetual Property Upsert Date Specified| | | <a name=\"200\">200</a>|Invalid Unit For Data Type| | | <a name=\"201\">201</a>|Invalid Type For Data Type| | | <a name=\"202\">202</a>|Invalid Value For Data Type| | | <a name=\"203\">203</a>|Unit Not Defined For Data Type| | | <a name=\"204\">204</a>|Units Not Supported On Data Type| | | <a name=\"205\">205</a>|Cannot Specify Units On Data Type| | | <a name=\"206\">206</a>|Unit Schema Inconsistent With Data Type| | | <a name=\"207\">207</a>|Unit Definition Not Specified| | | <a name=\"208\">208</a>|Duplicate Unit Definitions Specified| | | <a name=\"209\">209</a>|Invalid Units Definition| | | <a name=\"210\">210</a>|Invalid Instrument Identifier Unit| | | <a name=\"211\">211</a>|Holdings Adjustment Does Not Exist| | | <a name=\"212\">212</a>|Could Not Build Excel Url| | | <a name=\"213\">213</a>|Could Not Get Excel Version| | | <a name=\"214\">214</a>|Instrument By Code Not Found| | | <a name=\"215\">215</a>|Entity Schema Does Not Exist| | | <a name=\"216\">216</a>|Feature Not Supported On Portfolio Type| | | <a name=\"217\">217</a>|Quote Not Found| | | <a name=\"218\">218</a>|Invalid Quote Identifier| | | <a name=\"219\">219</a>|Invalid Metric For Data Type| | | <a name=\"220\">220</a>|Invalid Instrument Definition| | | <a name=\"221\">221</a>|Instrument Upsert Failure| | | <a name=\"222\">222</a>|Reference Portfolio Request Not Supported| | | <a name=\"223\">223</a>|Transaction Portfolio Request Not Supported| | | <a name=\"224\">224</a>|Invalid Property Value Assignment| | | <a name=\"230\">230</a>|Transaction Type Not Found| | | <a name=\"231\">231</a>|Transaction Type Duplication| | | <a name=\"232\">232</a>|Portfolio Does Not Exist At Given Date| | | <a name=\"233\">233</a>|Query Parser Failure| | | <a name=\"234\">234</a>|Duplicate Constituent| | | <a name=\"235\">235</a>|Unresolved Instrument Constituent| | | <a name=\"236\">236</a>|Unresolved Instrument In Transition| | | <a name=\"237\">237</a>|Missing Side Definitions| | | <a name=\"299\">299</a>|Invalid Recipe| | | <a name=\"300\">300</a>|Missing Recipe| | | <a name=\"301\">301</a>|Dependencies| | | <a name=\"304\">304</a>|Portfolio Preprocess Failure| | | <a name=\"310\">310</a>|Valuation Engine Failure| | | <a name=\"311\">311</a>|Task Factory Failure| | | <a name=\"312\">312</a>|Task Evaluation Failure| | | <a name=\"313\">313</a>|Task Generation Failure| | | <a name=\"314\">314</a>|Engine Configuration Failure| | | <a name=\"315\">315</a>|Model Specification Failure| | | <a name=\"320\">320</a>|Market Data Key Failure| | | <a name=\"321\">321</a>|Market Resolver Failure| | | <a name=\"322\">322</a>|Market Data Failure| | | <a name=\"330\">330</a>|Curve Failure| | | <a name=\"331\">331</a>|Volatility Surface Failure| | | <a name=\"332\">332</a>|Volatility Cube Failure| | | <a name=\"350\">350</a>|Instrument Failure| | | <a name=\"351\">351</a>|Cash Flows Failure| | | <a name=\"352\">352</a>|Reference Data Failure| | | <a name=\"360\">360</a>|Aggregation Failure| | | <a name=\"361\">361</a>|Aggregation Measure Failure| | | <a name=\"370\">370</a>|Result Retrieval Failure| | | <a name=\"371\">371</a>|Result Processing Failure| | | <a name=\"372\">372</a>|Vendor Result Processing Failure| | | <a name=\"373\">373</a>|Vendor Result Mapping Failure| | | <a name=\"374\">374</a>|Vendor Library Unauthorised| | | <a name=\"375\">375</a>|Vendor Connectivity Error| | | <a name=\"376\">376</a>|Vendor Interface Error| | | <a name=\"377\">377</a>|Vendor Pricing Failure| | | <a name=\"378\">378</a>|Vendor Translation Failure| | | <a name=\"379\">379</a>|Vendor Key Mapping Failure| | | <a name=\"380\">380</a>|Vendor Reflection Failure| | | <a name=\"390\">390</a>|Attempt To Upsert Duplicate Quotes| | | <a name=\"391\">391</a>|Corporate Action Source Does Not Exist| | | <a name=\"392\">392</a>|Corporate Action Source Already Exists| | | <a name=\"393\">393</a>|Instrument Identifier Already In Use| | | <a name=\"394\">394</a>|Properties Not Found| | | <a name=\"395\">395</a>|Batch Operation Aborted| | | <a name=\"400\">400</a>|Invalid Iso4217 Currency Code| | | <a name=\"401\">401</a>|Cannot Assign Instrument Identifier To Currency| | | <a name=\"402\">402</a>|Cannot Assign Currency Identifier To Non Currency| | | <a name=\"403\">403</a>|Currency Instrument Cannot Be Deleted| | | <a name=\"404\">404</a>|Currency Instrument Cannot Have Economic Definition| | | <a name=\"405\">405</a>|Currency Instrument Cannot Have Lookthrough Portfolio| | | <a name=\"406\">406</a>|Cannot Create Currency Instrument With Multiple Identifiers| | | <a name=\"407\">407</a>|Specified Currency Is Undefined| | | <a name=\"410\">410</a>|Index Does Not Exist| | | <a name=\"411\">411</a>|Sort Field Does Not Exist| | | <a name=\"413\">413</a>|Negative Pagination Parameters| | | <a name=\"414\">414</a>|Invalid Search Syntax| | | <a name=\"415\">415</a>|Filter Execution Timeout| | | <a name=\"420\">420</a>|Side Definition Inconsistent| | | <a name=\"450\">450</a>|Invalid Quote Access Metadata Rule| | | <a name=\"451\">451</a>|Access Metadata Not Found| | | <a name=\"452\">452</a>|Invalid Access Metadata Identifier| | | <a name=\"460\">460</a>|Standard Resource Not Found| | | <a name=\"461\">461</a>|Standard Resource Conflict| | | <a name=\"462\">462</a>|Calendar Not Found| | | <a name=\"463\">463</a>|Date In A Calendar Not Found| | | <a name=\"464\">464</a>|Invalid Date Source Data| | | <a name=\"465\">465</a>|Invalid Timezone| | | <a name=\"601\">601</a>|Person Identifier Already In Use| | | <a name=\"602\">602</a>|Person Not Found| | | <a name=\"603\">603</a>|Cannot Set Identifier| | | <a name=\"617\">617</a>|Invalid Recipe Specification In Request| | | <a name=\"618\">618</a>|Inline Recipe Deserialisation Failure| | | <a name=\"619\">619</a>|Identifier Types Not Set For Entity| | | <a name=\"620\">620</a>|Cannot Delete All Client Defined Identifiers| | | <a name=\"650\">650</a>|The Order requested was not found.| | | <a name=\"654\">654</a>|The Allocation requested was not found.| | | <a name=\"655\">655</a>|Cannot build the fx forward target with the given holdings.| | | <a name=\"656\">656</a>|Group does not contain expected entities.| | | <a name=\"667\">667</a>|Relation definition already exists| | | <a name=\"673\">673</a>|Missing entitlements for entities in Group| | | <a name=\"674\">674</a>|Next Best Action not found| | | <a name=\"676\">676</a>|Relation definition not defined| | | <a name=\"677\">677</a>|Invalid entity identifier for relation| | | <a name=\"681\">681</a>|Sorting by specified field not supported|One or more of the provided fields to order by were either invalid or not supported. | | <a name=\"682\">682</a>|Too many fields to sort by|The number of fields to sort the data by exceeds the number allowed by the endpoint | | <a name=\"684\">684</a>|Sequence Not Found| | | <a name=\"685\">685</a>|Sequence Already Exists| | | <a name=\"686\">686</a>|Non-cycling sequence has been exhausted| | | <a name=\"687\">687</a>|Legal Entity Identifier Already In Use| | | <a name=\"688\">688</a>|Legal Entity Not Found| | | <a name=\"689\">689</a>|The supplied pagination token is invalid| | | <a name=\"690\">690</a>|Property Type Is Not Supported| | | <a name=\"691\">691</a>|Multiple Tax-lots For Currency Type Is Not Supported| | | <a name=\"692\">692</a>|This endpoint does not support impersonation| | | <a name=\"693\">693</a>|Entity type is not supported for Relationship| | | <a name=\"694\">694</a>|Relationship Validation Failure| | | <a name=\"695\">695</a>|Relationship Not Found| | | <a name=\"697\">697</a>|Derived Property Formula No Longer Valid| | | <a name=\"698\">698</a>|Story is not available| | | <a name=\"703\">703</a>|Corporate Action Does Not Exist| | * * The version of the OpenAPI document: 0.11.2863 * Contact: [email protected] * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.finbourne.lusid.model; import java.util.Objects; import java.util.Arrays; import com.finbourne.lusid.model.AllocationRequest; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * A request to create or update multiple Allocations. */ @ApiModel(description = "A request to create or update multiple Allocations.") public class AllocationSetRequest { public static final String SERIALIZED_NAME_ALLOCATION_REQUESTS = "allocationRequests"; @SerializedName(SERIALIZED_NAME_ALLOCATION_REQUESTS) private List<AllocationRequest> allocationRequests = new ArrayList<>(); public AllocationSetRequest allocationRequests(List<AllocationRequest> allocationRequests) { this.allocationRequests = allocationRequests; return this; } public AllocationSetRequest addAllocationRequestsItem(AllocationRequest allocationRequestsItem) { if (this.allocationRequests == null) { this.allocationRequests = new ArrayList<>(); } this.allocationRequests.add(allocationRequestsItem); return this; } /** * A collection of AllocationRequests. * @return allocationRequests **/ @ApiModelProperty(value = "A collection of AllocationRequests.") public List<AllocationRequest> getAllocationRequests() { return allocationRequests; } public void setAllocationRequests(List<AllocationRequest> allocationRequests) { this.allocationRequests = allocationRequests; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } return true; } @Override public int hashCode() { return super.hashCode(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AllocationSetRequest {\n"); sb.append(" allocationRequests: ").append(toIndentedString(allocationRequests)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
92437c624b0960ec8c61d83c332c79bb58c951c1
6c7acf7a75595f74d7f92ef6ef2dd3369bc4547e
/src/DesignPattern2/abstractFactory/XiaomiPhone.java
3c93147833ddb3406153d414fbc293fb06f27818
[]
no_license
Xt6253555/sjjj
ddeb3c237cace0f994aa3bfbef148110d2b5d48e
ab755211259d0d6364c6b1efdfd20ee9658cd07e
refs/heads/master
2023-08-18T03:12:00.254005
2021-09-26T02:39:51
2021-09-26T02:39:51
367,583,312
0
0
null
null
null
null
UTF-8
Java
false
false
273
java
package DesignPattern2.abstractFactory; public class XiaomiPhone implements PhoneProduct { @Override public void Start() { System.out.println("手机开始"); } @Override public void End() { System.out.println("手机结束"); } }
44ffb7054c1df4749433e77be9d7906fcfedb962
9d6bd3c8a48116cf6897f3a3d1d5529421e2f041
/Lecture1/src/com/company/AbstractClassExample.java
a9b7a4f15a202014370dd7bc62642db78d88a187
[]
no_license
yadp/JavaAdvanced2021
ec689316699d4670af8e7509d16bc1ee9779feae
17068b9dd1b6c375fe29dbb66bd9ddf76e8fb302
refs/heads/master
2023-04-26T04:05:42.724616
2021-05-15T09:49:35
2021-05-15T09:49:35
338,831,434
0
0
null
2021-03-06T11:28:16
2021-02-14T15:06:54
Java
UTF-8
Java
false
false
224
java
package com.company; public abstract class AbstractClassExample implements TestInterface{ abstract void abstractMethod(); @Override public void testMethod() { System.out.println("testMethod"); } }
e097c2cb39a0b1f28d3c2e03a7607df859747ec3
ad0300c29aa79d6b25e430efd128344f1c283369
/clojure/core_sorted_map.java
0892362ab10d84082fbb8c5540dfe5d184ec6db9
[]
no_license
galdolber/clojure-core-java
d7cedc6e68d3755f3ff446e9bbec988d8739c74d
1ef06a7ecd400fa9f91cb17f636ebcf308f3b320
refs/heads/master
2016-09-10T12:52:54.014593
2014-01-25T22:04:10
2014-01-25T22:04:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
410
java
package clojure; import clojure.lang.*; public final class core_sorted_map extends clojure.lang.RestFn { static { } public core_sorted_map() { super(); } public java.lang.Object doInvoke(java.lang.Object keyvals1) { return ((clojure.lang.PersistentTreeMap)clojure.lang.PersistentTreeMap.create((clojure.lang.ISeq)((clojure.lang.ISeq)keyvals1))); } public int getRequiredArity() { return 0; } }
8e5a051baa7f05aa22a9657675798d843106aadd
f0f6daa8e6ac0b848c6872b507e49f9d0a5d0755
/src/main/model/Todo.java
e32ea7f9a3f3be45ea9ab0f47d3966b5887d07f3
[]
no_license
StrawberryMilsc/ToDoList
d9f12c0c24ff95dbe97c059ae5f0436e10d513db
93fdaee537c0755fd5f43fb525c9dd5c0a8f656f
refs/heads/main
2023-04-03T03:09:26.334418
2021-04-08T01:33:14
2021-04-08T01:33:14
355,726,051
0
0
null
null
null
null
UTF-8
Java
false
false
1,925
java
package model; import model.exceptions.EmptyStringException; import model.exceptions.NullArgumentException; public abstract class Todo { protected String description; protected int progress; protected int etcHours; // Estimated Time To Complete protected Priority priority; // MODIFIES: this // EFFECTS: sets the "description" using the given description // sets "progress" and "estimated time to complete" to zero // throws EmptyStringException if description is null or empty public Todo(String description) throws EmptyStringException { if (description == null) { throw new EmptyStringException("Description cannot be null"); } this.description = description; progress = 0; etcHours = 0; priority = new Priority(4); } // MODIFIES: this // EFFECTS: sets the priority of this task // throws NullArgumentException when priority is null public void setPriority(Priority priority) { if (priority == null) { throw new NullArgumentException("Illegal argument: priority is null"); } this.priority = priority; } // EFFECTS: returns the priority of this task public Priority getPriority() { return priority; } // EFFECTS: returns the description public String getDescription() { return description; } // EFFECTS: return a non-negative integer as the Estimated Time To Complete // Note: Estimated time to complete is a value that is expressed in // hours of work required to complete a task or project. public abstract int getEstimatedTimeToComplete(); // EFFECTS: returns an integer between 0 and 100 which represents // the percentage of completion (rounded down to the closest integer). public abstract int getProgress(); }
24d268c3be311ba2a79a7488c95d200b47eba4ef
1e3aac1b8f56d7dc8960a842811153c9cbfbc3c0
/pharmacies/src/main/java/isa/tim28/pharmacies/model/MedicineConsumption.java
f76ae2d5d14e7fcf1045165d2e47afe5c83ecb72
[]
no_license
tamararankovic/pharmacies_backend
e8c156a034615f9ee1c2cf23cc359401ab7a98f1
bf0b84fe86771b6969aa483b43756c6895e1757b
refs/heads/master
2023-05-22T21:11:12.571071
2021-06-04T09:30:22
2021-06-04T09:30:22
333,131,431
0
0
null
null
null
null
UTF-8
Java
false
false
1,873
java
package isa.tim28.pharmacies.model; import java.time.LocalDate; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import isa.tim28.pharmacies.exceptions.ForbiddenOperationException; @Entity public class MedicineConsumption { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST) private Medicine medicine; @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST) private Pharmacy pharmacy; @Column(name = "quantity", nullable = false) private int quantity; @Column(name = "dateCreated", nullable = false) private LocalDate dateCreated; public MedicineConsumption() { super(); // TODO Auto-generated constructor stub } public MedicineConsumption(Medicine medicine, Pharmacy pharmacy, int quantity) throws ForbiddenOperationException { if(!pharmacy.offers(medicine)) throw new ForbiddenOperationException("Pharmacy doesn't offer selected medicine"); this.medicine = medicine; this.pharmacy = pharmacy; this.quantity = quantity; this.dateCreated = LocalDate.now(); } public MedicineConsumption(long id, Medicine medicine, Pharmacy pharmacy, int quantity, LocalDate dateCreated) { super(); this.id = id; this.medicine = medicine; this.pharmacy = pharmacy; this.quantity = quantity; this.dateCreated = dateCreated; } public long getId() { return id; } public Medicine getMedicine() { return medicine; } public Pharmacy getPharmacy() { return pharmacy; } public int getQuantity() { return quantity; } public LocalDate getDateCreated() { return dateCreated; } }
fc8bb62cf4a9c8706c070426ff6758cdc0647ec1
e12a58e4a2b2d72bbb64cc3cb907093b9c621092
/src/main/java/org/bpt/cpp/dp/tsp/CollectingBeepers.java
5f53917b51d810d344292be193e949961640017a
[]
no_license
toaler/CPP
3f8b3f78d700eaef06266de5ea21dbf8664045d8
d3fe0e914e0491a2dba84800d78f53f98f5a14d1
refs/heads/master
2020-05-31T12:29:26.436163
2015-07-07T07:23:49
2015-07-07T07:23:49
15,200,294
0
0
null
null
null
null
UTF-8
Java
false
false
2,794
java
package org.bpt.cpp.dp.tsp; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Solution to 10496 - {@code Collecting Beepers}, see {@linktourl http://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=1437} * for full details */ public class CollectingBeepers { private static int[][] memorizer; private static int[][] distance; public static void main(String[] args) throws Exception { mainWork(new BufferedReader(new InputStreamReader(System.in)), System.out); } public static void mainWork(BufferedReader reader, PrintStream ps) { Scanner scanner = new Scanner(reader); try { int scenarios = scanner.nextInt(); while (scenarios-- > 0) { scanner.nextInt(); // skip x scanner.nextInt(); // skip y List<Node> nodes = new ArrayList<>(); nodes.add(new Node(scanner.nextInt(), scanner.nextInt())); final int beepers = scanner.nextInt(); for (int beeper = 0; beeper < beepers; beeper++) { nodes.add(new Node(scanner.nextInt(), scanner.nextInt())); } distance = new int[beepers + 1][beepers + 1]; for (int i = 0; i < nodes.size(); i++) { for (int j = 0; j < nodes.size(); j++) { Node start = nodes.get(i); Node end = nodes.get(j); distance[i][j] = end.distance(start); } } memorizer = new int[distance.length][1 << distance.length]; for (int i = 0; i < distance.length; i++) { for (int j = 0; j < (1 << distance.length); j++) { memorizer[i][j] = -1; } } StringBuilder sb = new StringBuilder(); sb.append("The shortest path has length ") .append(String.valueOf(tsp(0, 1))).append("\n"); ps.append(sb); } } catch (Exception e) { scanner.close(); e.printStackTrace(); } } private static int tsp(int currentNode, int visitedNodes) { if (visitedNodes == (1 << distance.length) - 1) { return distance[currentNode][0]; } if (memorizer[currentNode][visitedNodes] != -1) { return memorizer[currentNode][visitedNodes]; } int min = Integer.MAX_VALUE; for (int next = 0; next < distance.length; next++) { if (next != currentNode && ((visitedNodes & (1 << next)) == 0)) { min = Math.min( min, distance[currentNode][next] + tsp(next, visitedNodes | (1 << next))); } } return memorizer[currentNode][visitedNodes] = min; } private static class Node { private int x; private int y; public Node(int x, int y) { this.x = x; this.y = y; } public int distance(Node start) { return Math.abs(x - start.x) + Math.abs(y - start.y); } @Override public String toString() { return "{" + x + ", " + y + "}"; } } }
60db935469efde31efe645205f7d0f44d8ea4f8e
0f232fc4da65ae4ca6f794d023637890758c56bf
/yeb-server/src/main/java/com/maple/server/pojo/PoliticsStatus.java
caab9c531b68962be0e3cb75a3c715b5614e8ed7
[]
no_license
ashilye/yeb
e53ab96d5ef9065457300485d1a17186f4f7cf7a
3a88baa1c50eff048d3a3711782ed6d013933172
refs/heads/master
2023-03-17T10:58:37.208446
2021-03-08T09:32:03
2021-03-08T09:32:03
340,890,222
0
0
null
null
null
null
UTF-8
Java
false
false
857
java
package com.maple.server.pojo; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import java.io.Serializable; /** * <p> * * </p> * * @author gaoguanqi * @since 2021-02-23 */ @Data @EqualsAndHashCode(callSuper = false) @TableName("t_politics_status") @ApiModel(value="PoliticsStatus对象", description="") public class PoliticsStatus implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "id") @TableId(value = "id", type = IdType.AUTO) private Integer id; @ApiModelProperty(value = "政治面貌") private String name; }
f9c852dfa5572bd6f82153efcbdb0c89adaaf2d6
6a5dbc1d7558ebb753487e1cdafee7adcfd595c1
/src/com/company/Hackerblock/String/Uppercase.java
ba679acb784ccadc16903beae3bfc77aa449f86f
[]
no_license
abbisk/Cruxx
ec60924aa8f871ed2d4fb1094a72ac56c166f003
fb206cfe01dc946527f6556f59caf841f84fe6d4
refs/heads/master
2020-06-01T12:47:19.981749
2019-10-21T00:35:21
2019-10-21T00:35:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
476
java
package com.company.Hackerblock.String; import java.util.Scanner; public class Uppercase { public static void main(String[] args) { Scanner obj = new Scanner(System.in); Character c = obj.next().charAt(0); if (c >= 'a' && c <= 'z') { System.out.println("lowercase"); } else if (c >= 'A' && c <= 'Z') { System.out.println("UPPERCASE"); } else { System.out.println("Invalid"); } } }
eaa9991e40dfe8fcc0ab3d53ce3fe995ea1feec8
426ade448d9c591501c2ae05341d8f1c785f2440
/Final Project/Reversi-master/src/reversi/GameView.java
8305ef42147ed57d410fd59d58c8b2f50ab9cf20
[ "MIT" ]
permissive
zenofchaos/CS4341
152ec392086bd6eb19f2c225e43f4b0ce71d84b8
6d121fdd2bb3d41f93ea4b045ce04dae29086f35
refs/heads/master
2021-01-11T11:26:38.712564
2017-03-03T00:40:22
2017-03-03T00:40:22
80,022,973
0
1
null
2017-03-03T00:40:22
2017-01-25T14:40:22
Java
UTF-8
Java
false
false
1,719
java
/* * Copyright (c) 2010 Georgios Migdos <[email protected]>, Filia Dova * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package reversi; public interface GameView { public void notifyGameChanged(GameController g); public void forceUpdate(); public void setController(GameController g); public Board getBoard(); public void setBoard(Board b); public void setAI1IsPlaying(boolean AI1IsPlaying); public boolean getAI1IsPlaying(); public void setAI2IsPlaying(boolean AI2IsPlaying); public boolean getAI2IsPlaying(); public void setPlayerHasNoMovesAvailable(boolean playerHasNoValidMoves, String player); }
5b2c6a3aa5500d229b5b0ec40566c58bf9b54554
b308cb7b6c6551cca63f374ff24f5da89f2f94f1
/src/com/yml/stack/StackIterator.java
1eaf84d26b2821da971168961963c51e2803cba6
[]
no_license
StalinChristopher/Object_oriented_programs
8154f09c0f513fa8dc603cf7bf13fdbe997653cd
0be8a356dcfef631be2ca9ea09cbeed0be33f826
refs/heads/main
2023-08-07T20:28:40.685618
2021-09-16T18:01:39
2021-09-16T18:01:39
403,945,421
0
0
null
null
null
null
UTF-8
Java
false
false
465
java
package com.yml.stack; import java.util.Iterator; import com.yml.linkedlist.Node; public class StackIterator <T> implements Iterator<Node<T>> { Node<T> current; public StackIterator(Node<T> top) { current = top; } @Override public boolean hasNext() { return current != null; } @Override public Node<T> next() { Node<T> temp = current; current = current.getNext(); return temp; } }
b991338853a899667f03eafe568777b7e728c635
1a943acc2c3e883d1d73f858e19fa3c6bcbba8ab
/SpringExampleIII/src/com/tutorialspoint/MainApp.java
a4a011b7ab28b376baebfa90a4c1a3438030b112
[]
no_license
mscyan/SpringExercise
e4423e266567a7a490b77104ec668696a7b2a06d
94c65c4aecf6fa6e402ede867a43e60e752a9fab
refs/heads/master
2021-04-26T23:02:11.395782
2018-03-09T08:02:25
2018-03-09T08:02:25
123,919,338
0
0
null
null
null
null
UTF-8
Java
false
false
493
java
package com.tutorialspoint; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); context.registerShutdownHook(); obj.getMessage(); } }
078098e585c23f90134ade36f86b7bfe57a174d2
ed44df19374f0e86a9faa58ad57c77a641c73ac7
/aws-java-sdk-rekognition/src/main/java/com/amazonaws/services/rekognition/model/ProvisionedThroughputExceededException.java
39d959cc9abd28def2168730574fe52bb9771dba
[ "Apache-2.0" ]
permissive
da-demo-account/aws-sdk-java
2ef5c1f4e29e02fcc9e3310accb71f2f71183ef9
fe64a1bbb11d9385a96e11e27fdafe606ad5c0d9
refs/heads/master
2021-01-11T21:36:38.624023
2017-01-11T20:46:23
2017-01-11T20:46:23
78,815,415
0
0
null
2017-01-13T04:31:36
2017-01-13T04:31:36
null
UTF-8
Java
false
false
1,254
java
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.rekognition.model; /** * <p> * The number of requests exceeded your throughput limit. If you want to increase this limit, contact Amazon * Rekognition. * </p> */ public class ProvisionedThroughputExceededException extends com.amazonaws.services.rekognition.model.AmazonRekognitionException { private static final long serialVersionUID = 1L; /** * Constructs a new ProvisionedThroughputExceededException with the specified error message. * * @param message * Describes the error encountered. */ public ProvisionedThroughputExceededException(String message) { super(message); } }
[ "" ]
4081b49e3f55f6dcc5e7a6c663b74fb92369e70f
673fa147a68a8a5d9cfb01f3b210c1a8a88b04e7
/sorting_algorithms/algos.java
e5e52b300848acbb7a03a1d254bd6bccadfa0d17
[]
no_license
SchwartzCode/java_data_structs_and_algos
0f970d933f024f5539593b4a89c5c039c91c6bf8
62b71503e1307858d84f267a66aab93386db8b71
refs/heads/master
2020-04-04T20:08:58.873397
2019-01-07T00:53:09
2019-01-07T00:53:09
156,234,714
0
0
null
null
null
null
UTF-8
Java
false
false
2,031
java
package sorting_algorithms; //some simple sorting algorithms implemented in java public class algos { public static void swap(int[] arr, int pos1, int pos2) { int temp = arr[pos1]; arr[pos1] = arr[pos2]; arr[pos2] = temp; } public static void bubbleSort(int[] in) { int size = in.length; for (int i=0; i<(size-1); i++) { for (int j=i+1; j<size; j++) { if(in[i] > in[j]) { swap(in, i, j); } } } } public static void selectionSort(int[] in) { int size = in.length; for (int i=0; i<size - 1; i++) { int min = i; for (int j=i+1; j<size; j++) { if(in[min] > in[j]) { min = j; } } swap(in, i, min); } } public static void mergeSort(int[] in, int begin, int end) { int size = in.length; int[] temp = new int[size]; if (begin > end) { return; } else if (end-begin > 1) { int middle = (begin + end)/2; mergeSort(in, begin, middle); mergeSort(in, middle+1, end); mergeHalves(in, temp, begin, middle, end); } } public static void mergeHalves(int[] array, int[] temp, int start, int middle, int end) { for (int i = start; i <= end; i++) { temp[i] = array[i]; } int i = start; int j = middle + 1; int k = start; while (i <= middle && j <= end) { if (temp[i] <= temp[j]) { array[k] = temp[i]; i++; } else { array[k] = temp[j]; j++; } k++; } while (i <= middle) { array[k] = temp[i]; k++; i++; } } public static void main(String[] args) { int[] pizza = {2, 7, 3, 8, 891, 1, 99, -2, 4}; for (int i:pizza) { System.out.print(i + " "); } System.out.println(); mergeSort(pizza, 0, pizza.length-1); for (int i:pizza) { System.out.print(i + " "); } System.out.println(); } }
00b30248890f3ddab434eff3e3ed83b26bc1534e
40665051fadf3fb75e5a8f655362126c1a2a3af6
/geosolutions-it-MapStoreMobile/1995bcf7919e4d6eb547052b8b4353d6f49c5fa7/206/PendingMissionDetailFragment.java
8eac324327d05a44ccc10d9064441c667a3c90f5
[]
no_license
fermadeiral/StyleErrors
6f44379207e8490ba618365c54bdfef554fc4fde
d1a6149d9526eb757cf053bc971dbd92b2bfcdf1
refs/heads/master
2020-07-15T12:55:10.564494
2019-10-24T02:30:45
2019-10-24T02:30:45
205,546,543
2
0
null
null
null
null
UTF-8
Java
false
false
14,708
java
/* * GeoSolutions - MapstoreMobile - GeoSpatial Framework on Android based devices * Copyright (C) 2014 GeoSolutions (www.geo-solutions.it) * * 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 3 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, see <http://www.gnu.org/licenses/>. */ package it.geosolutions.geocollect.android.core.mission; import java.util.HashMap; import java.util.List; import jsqlite.Exception; import jsqlite.Stmt; import it.geosolutions.android.map.fragment.MapFragment; import it.geosolutions.android.map.wfs.geojson.feature.Feature; import it.geosolutions.geocollect.android.core.BuildConfig; import it.geosolutions.geocollect.android.core.R; import it.geosolutions.geocollect.android.core.form.FormEditActivity; import it.geosolutions.geocollect.android.core.form.utils.FormBuilder; import it.geosolutions.geocollect.android.core.mission.utils.MissionUtils; import it.geosolutions.geocollect.android.core.mission.utils.PersistenceUtils; import it.geosolutions.geocollect.model.config.MissionTemplate; import it.geosolutions.geocollect.model.viewmodel.Field; import it.geosolutions.geocollect.model.viewmodel.type.XType; import org.mapsforge.core.model.GeoPoint; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.Loader; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.ScrollView; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.vividsolutions.jts.geom.Point; /** * A fragment representing a single Pending Mission detail screen. This fragment * is either contained in a {@link PendingMissionListActivity} in two-pane mode * (on tablets) or a {@link PendingMissionDetailActivity} on handsets. */ public class PendingMissionDetailFragment extends MapFragment implements LoaderCallbacks<Void> { /** * Tag for logging */ public static final String TAG = "MissionDetail"; public static final int EDIT_ACTIVITY_CODE = 0; /** * The fragment argument representing the item ID that this fragment * represents. */ public static final String ARG_ITEM_ID = "item_id"; public static final String ARG_ITEM_FEATURE = "item_FEATURE"; /** * The <ScrollView> that display fragment content */ private ScrollView mScrollView; /** * The <LinearLayout> inside the <ScrollView> * This displays dynamic content as the other forms. */ private LinearLayout mFormView; /** * <ProgressBar> for loading */ private ProgressBar mProgressView; private boolean mDone; protected Mission mission; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments().containsKey(ARG_ITEM_ID)) { // TODO: get the Feature from db Log.d(TAG, "onCreate() ARG_ITEM_ID: " + getArguments().getString(ARG_ITEM_ID)); } setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(TAG, "onCreateView(): container = " + container + "savedInstanceState = " + savedInstanceState); if (mScrollView == null) { // normally inflate the view hierarchy mScrollView = (ScrollView) inflater.inflate(R.layout.preview_page_fragment, container, false); mFormView = (LinearLayout) mScrollView.findViewById(R.id.formcontent); mProgressView = (ProgressBar) mScrollView .findViewById(R.id.loading); } else { // mScrollView is still attached to the previous view hierarchy // we need to remove it and re-attach it to the current one ViewGroup parent = (ViewGroup) mScrollView.getParent(); parent.removeView(mScrollView); } //TODO it should be false because orientation change can // have different layout (for map view ) //setRetainInstance(true); return mScrollView; } @Override public void onCreateOptionsMenu( Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.nav_map_editable, menu); } /* (non-Javadoc) * @see com.actionbarsherlock.app.SherlockFragment#onOptionsItemSelected(com.actionbarsherlock.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if(id==R.id.accept){ Intent i = new Intent(getSherlockActivity(),FormEditActivity.class); i.putExtra("MISSION", mission); startActivityForResult(i, EDIT_ACTIVITY_CODE); return true; }else if(id == R.id.full_map){ final GeoPoint geoPoint = getOriginGeoPoint(); if(geoPoint != null){ Intent mapIntent = new Intent(getSherlockActivity(),SimpleMapActivity.class); mapIntent.putExtra(SimpleMapActivity.ARG_PRIORITY_COLOR, getPriorityColor()); mapIntent.putExtra(SimpleMapActivity.ARG_FIRST_POINT_LAT, geoPoint.latitude); mapIntent.putExtra(SimpleMapActivity.ARG_FIRST_POINT_LON, geoPoint.longitude); mapIntent.putExtra(SimpleMapActivity.ARG_ZOOM,((byte) 18)); final GeoPoint updatedPoint = getUpdatedGeoPoint(); if(updatedPoint != null){ mapIntent.putExtra(SimpleMapActivity.ARG_SECOND_POINT_LAT, updatedPoint.latitude); mapIntent.putExtra(SimpleMapActivity.ARG_SECOND_POINT_LON, updatedPoint.longitude); } startActivity(mapIntent); }else{ Log.e(TAG, "could not retrieve geopoint"); } }else if(id == R.id.navigate){ //start an intent to navigate to this position GeoPoint geoPoint = getUpdatedGeoPoint(); if(geoPoint == null){ geoPoint = getOriginGeoPoint(); } if(geoPoint == null){ Log.e(TAG, "no coordinate to navigate to available"); return super.onOptionsItemSelected(item); } /** * http://stackoverflow.com/questions/5801684/intent-to-start-a-navigation-activity * * The bad news is, there isn't a standard Intent URI for navigation. * * possibilities : * * Uri.parse("google.navigation:q= lat,lon) //won't start navigation * Uri.parse("geo:latitude,longitude //will only zoom map on position * Uri.parse("http://maps.google.com/maps?daddr=lat,lon) worked best for now * * problematic for users without google maps App but they should be few ?! */ // String uri_string = String.format("google.navigation:q%f",geoPoint.latitude,geoPoint.longitude); String uri_string = String.format("http://maps.google.com/maps?daddr=%s,%s",Double.toString(geoPoint.latitude),Double.toString(geoPoint.longitude)); Log.d(TAG, "uri "+ uri_string); Intent navIntent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri_string)); startActivity(navIntent); } return super.onOptionsItemSelected(item); } public int getPriorityColor(){ Field colorField = getField(XType.separatorWithIcon); HashMap <String,String> colors = mission.getTemplate().priorityValuesColors; final String key = mission.getValueAsString(getActivity(), colorField); final String color = colors.get(key); return Color.parseColor(color); } /** * reads out the missions origin GeoPoint by retrieving the mapView field and using it * to extract it out of the missions tags * @return the geopoint of this mission */ public GeoPoint getOriginGeoPoint(){ final Field mapField = getField(XType.mapViewPoint); //extract the point GeoPoint geoPoint = null; List<String> tags = MissionUtils.getTags(mapField.value); if(tags != null && tags.size() ==1){ Point geom = (Point) mission.getValueByTag(getActivity(), tags.get(0)); if(geom !=null){ if(!geom.isEmpty()){ double lat = geom.getY(); double lon = geom.getX(); geoPoint = new GeoPoint(lat, lon); } } } return geoPoint; } /** * accesses the database to acquire an updated position for this mission * @return the updated GeoPoint or null if none available */ public GeoPoint getUpdatedGeoPoint(){ final Field f = getField(XType.mapViewPoint); final String tableName = getTablename(); // Default ID String originIDString = MissionUtils.getMissionGCID(mission); final String s = "SELECT Y(" + f.fieldId + "), X(" + f.fieldId + ") FROM '" + tableName + "' WHERE ORIGIN_ID = '" + originIDString +"';"; if(mission == null || mission.db == null){ Log.w(TAG, "Cannot retrieve mission database"); return null; } try { if(jsqlite.Database.complete(s)){ Stmt st = mission.db.prepare(s); if(st.step()){ final GeoPoint p = new GeoPoint(st.column_double(0), st.column_double(1)); st.close(); return p; } }else{ if(BuildConfig.DEBUG){ Log.w(TAG, "Query is not complete:\n"+s); } } } catch (Exception e) { Log.e(TAG, "Error retrieving updatedPoint",e); } return null; } /** * returns a field from the default templates previews form * @param xType to search for * @return the field according to the xType */ public Field getField(final XType xType){ final MissionTemplate t = MissionUtils.getDefaultTemplate(getSherlockActivity()); for(Field f : t.preview.fields){ if(f.xtype == xType){ return f; } } return null; } /** * gets the tablename of this mission's results * @return */ public String getTablename(){ String tableName = mission.getTemplate().id+"_data"; if(mission.getTemplate().schema_sop != null && mission.getTemplate().schema_sop.localFormStore != null && !mission.getTemplate().schema_sop.localFormStore.isEmpty()){ tableName = mission.getTemplate().schema_sop.localFormStore; } return tableName; } /** * Handle the results */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult()"); super.onActivityResult(requestCode, resultCode, data); if(requestCode == EDIT_ACTIVITY_CODE){ MissionTemplate t = MissionUtils.getDefaultTemplate(getSherlockActivity()); PersistenceUtils.loadPageData(t.preview, mFormView, mission, getSherlockActivity(),true); } } /** * Fills the Page layout with widgets based on page template */ private void buildForm() { // if the view hierarchy was already build, skip this if (mDone) return; MissionTemplate t = MissionUtils.getDefaultTemplate(getSherlockActivity()); FormBuilder.buildForm(getActivity(), this.mFormView,t.preview.fields,mission);//TODO page is not enough, some data should be accessible like constants and data PersistenceUtils.loadPageData(t.preview, mFormView, mission, getSherlockActivity(),false); // the view hierarchy is now complete mDone = true; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.d(TAG, "onActivityCreated(): savedInstanceState = " + savedInstanceState); if(savedInstanceState == null){ toggleLoading(true); getLoaderManager().restartLoader(0, null, this); }else{ toggleLoading(true); Feature origin = (Feature)savedInstanceState.getSerializable(ARG_ITEM_FEATURE); Mission m = new Mission(); m.setTemplate(MissionUtils.getDefaultTemplate(getSherlockActivity())); m.setOrigin(origin); if(getSherlockActivity() instanceof PendingMissionDetailActivity){ Log.d(TAG, "Loader: Connecting to Activity database"); m.db = ((PendingMissionDetailActivity)getSherlockActivity()).spatialiteDatabase; }else if(getSherlockActivity() instanceof PendingMissionListActivity){ Log.d(TAG, "Loader: Connecting to Activity database"); m.db = ((PendingMissionListActivity)getSherlockActivity()).spatialiteDatabase; }else { Log.w(TAG, "Loader: Could not connect to Activity database"); } mission =m; toggleLoading(false); buildForm(); } } /** * Load the mission and template data either from the database or from the intent */ public Loader<Void> onCreateLoader(int id, Bundle args) { Log.d(TAG, "onCreateLoader(): id=" + id); Loader<Void> loader = new AsyncTaskLoader<Void>(getActivity()) { @Override public Void loadInBackground() { Activity activity = getSherlockActivity(); Feature myFeature = (Feature) getArguments().getSerializable(ARG_ITEM_FEATURE); Mission m = new Mission(); m.setTemplate(MissionUtils.getDefaultTemplate(activity)); m.setOrigin(myFeature); if(activity instanceof PendingMissionDetailActivity){ Log.d(TAG, "Loader: Connecting to Activity database"); m.db = ((PendingMissionDetailActivity)activity).spatialiteDatabase; }else if(activity instanceof PendingMissionListActivity){ Log.d(TAG, "Loader: Connecting to Activity database"); m.db = ((PendingMissionListActivity)activity).spatialiteDatabase; }else{ Log.w(TAG, "Loader: Could not connect to Activity database"); } mission =m; return null; } }; //TODO create loader; loader.forceLoad(); return loader; } @Override public void onSaveInstanceState(Bundle outState) { //save the origin outState.putSerializable(ARG_ITEM_FEATURE, mission.getOrigin()); } public void onLoadFinished(Loader<Void> id, Void result) { Log.d(TAG, "onLoadFinished(): id=" + id); toggleLoading(false); buildForm(); } public void onLoaderReset(Loader<Void> loader) { Log.d(TAG, "onLoaderReset(): id=" + loader.getId()); } private void toggleLoading(boolean show) { mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); mFormView.setGravity(show ? Gravity.CENTER : Gravity.TOP); } @Override public void onDestroyView() { super.onDestroyView(); Log.d(TAG, "onDestroyView()"); } @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy()"); } @Override public void onDetach() { super.onDetach(); Log.d(TAG, "onDetach()"); } }
abf0b4cfe6d299fc72f9494cc5dabbef8039a240
b2b4a6bab187aaa35f5bfc324f0ef07d37c8914a
/tree/L426.java
25ed14cfd73d8726409c0d509d3a9b4a04b58251
[]
no_license
fyiyu091/Leetcode
7dd908a39bde4c019bda98038538ddcbfaf2e9c7
54c0a823cbf742f4693bb8c7824d9d67221fc5bb
refs/heads/master
2023-07-19T05:37:41.645801
2021-08-31T03:25:25
2021-08-31T03:25:25
275,048,455
0
0
null
null
null
null
UTF-8
Java
false
false
675
java
package tree; /* Convert binary search tree to sorted doubly linked list */ public class L426 { Node prev = null; Node head = null; public Node treeToDoublyList(Node root) { inOrder(root); if (prev != null && head != null) { prev.right = head; head.left = prev; } return head; } private void inOrder(Node root) { if (root == null) return; inOrder(root.left); if (prev == null) { head = root; } else { prev.right = root; } root.left = prev; prev = root; inOrder(root.right); return; } }
bd9f521d7b91297236682f931562cd9b45641f25
4c703df6fdc0596b78b1e178a6245396152d1d35
/src/main/java/org/bdc/dcm/data/convert/lqmdb/LqcmdbLoopCheckStateThread.java
cab36e32c3c73b4ae5eb653e01dc2177049b9a93
[]
no_license
lightechnology/dcm
38dba899f583dae62de8b089e9ab89e92dfff8de
758e16055f4ab5257441b433b1e0baa67ff18206
refs/heads/master
2020-12-02T18:12:41.391243
2017-08-30T10:56:56
2017-08-30T10:56:56
96,495,486
1
1
null
2017-08-30T08:36:30
2017-07-07T03:28:02
Java
UTF-8
Java
false
false
2,008
java
package org.bdc.dcm.data.convert.lqmdb; import java.util.Optional; import org.bdc.dcm.conf.IntfConf; import org.bdc.dcm.vo.Server; import org.bdc.dcm.vo.e.DataType; import org.bdc.dcm.vo.e.ServerType; import com.util.tools.Public; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; public class LqcmdbLoopCheckStateThread implements Runnable { private boolean isRun; private ChannelHandlerContext ctx; public LqcmdbLoopCheckStateThread() { super(); this.isRun = false; } public boolean isRun() { return isRun; } public void setRun(boolean isRun) { this.isRun = isRun; } public ChannelHandlerContext getCtx() { return ctx; } public void setCtx(ChannelHandlerContext ctx) { this.ctx = ctx; } @Override public void run() { this.isRun = true; try { Optional<Server> optional = IntfConf.getServerConf().getServerConf().stream().filter(item->{return item.getDataType().equals(DataType.Lqmdb) && item.getServerType().equals(ServerType.TCP_SERVER);}).findFirst(); if(!optional.isPresent()) { isRun = false;return;} Server server = optional.get(); while(this.isRun){ for(byte i=1;i<21 && this.isRun;i++){ //modbus------------------------------------------------------------- byte[] modbus = Public.hexString2bytes(Public.byte2hex_ex(i)+" 03 00 03 00 0C B4 4B"); byte[] crc16 = Public.crc16_A001(modbus); int sum=0; for(int j=0;j<modbus.length;j++){ sum+=(modbus[j] & 0xff); } for(int j=0;j<crc16.length;j++){ sum+=(crc16[j] & 0xff); } byte crcSumByte = ((byte) (sum & 0xff)); ByteBuf bu = ctx.alloc().buffer(); bu.writeBytes(modbus); bu.writeByte(crc16[1]); bu.writeByte(crc16[0]); bu.writeByte(crcSumByte); ctx.channel().writeAndFlush(bu); Thread.sleep(server.getDelaySendingTime()*1000); } } }catch(Exception e) { e.printStackTrace(); } } }
[ "Administrator@HY0473-PC" ]
Administrator@HY0473-PC
74da2e612fdec7fa332546c5290768abbff1780e
95d68f00389c99f880fdea196dff26640b82180c
/app/src/main/java/projectppb/com/Calculus_Inequations_Systems_two.java
60f9fc8d046c171e86ca91d3e7d901c623915381
[]
no_license
DheaOkySafitri-170411100006/Aplikasi-Math-Theory
c02e968a0380be933be5bff047bce8e979b7e62c
da5aa8b59e09c0f83993e605bfb61f760ea7eb66
refs/heads/master
2021-05-21T06:22:50.226812
2020-07-03T11:25:49
2020-07-03T11:25:49
256,417,116
0
0
null
null
null
null
UTF-8
Java
false
false
769
java
package projectppb.com; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import com.github.barteksc.pdfviewer.PDFView; public class Calculus_Inequations_Systems_two extends AppCompatActivity { PDFView pdfView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calculus__inequations__systems_two); pdfView= (PDFView) findViewById(R.id.pdfView1); pdfView.fromAsset("Calculus_Inequations_Systems_two.pdf") .load(); pdfView.zoomTo((float) 3.5); Toast.makeText(this, "Tunggu beberapa saat. \n Sedang memuat data. . .", Toast.LENGTH_SHORT).show(); } }
2a336b745a273595ad9ebf2ea80cb74783f7294d
da364ef8694bcb00f867c3edbe3986f908ad06d8
/cpw/mods/fml/common/asm/transformers/deobf/FMLRemappingAdapter.java
963607946b6098c62d71880dceb04b5e8ee1809a
[]
no_license
WesleyRen/minecraft-youthdigital
5928ca94f8eb2b3ec32cd792c081c889a0567188
6a5b064344c545de58fc7774002568d60c5f2c3c
refs/heads/master
2021-01-10T14:33:44.860609
2015-11-29T23:09:11
2015-11-29T23:09:11
47,078,845
2
0
null
null
null
null
UTF-8
Java
false
false
1,179
java
/* * Forge Mod Loader * Copyright (c) 2012-2013 cpw. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * cpw - implementation */ package cpw.mods.fml.common.asm.transformers.deobf; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.commons.Remapper; import org.objectweb.asm.commons.RemappingClassAdapter; public class FMLRemappingAdapter extends RemappingClassAdapter { public FMLRemappingAdapter(ClassVisitor cv) { super(cv, FMLDeobfuscatingRemapper.INSTANCE); } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { if (interfaces == null) { interfaces = new String[0]; } FMLDeobfuscatingRemapper.INSTANCE.mergeSuperMaps(name, superName, interfaces); super.visit(version, access, name, signature, superName, interfaces); } }
2f7de631af34491b45afe24c2324659201595dc3
64fba860c733450863772ec8b2511a36b15eb326
/src/main/java/com/smsmissedcall/entities/Destinataire.java
135706b8cb2e0a2a49dbf7482095152e01ee1e6f
[]
no_license
desireadje/SmsMissedCall-Spring-Boot
422994e65cc90f0db59b6cc4e2307b82b420679e
26a722947822b61355c5ce3a08af79956cee8d6c
refs/heads/master
2022-12-19T16:15:09.820875
2020-10-16T08:59:43
2020-10-16T08:59:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
354
java
package com.smsmissedcall.entities; public class Destinataire { // Attributs private String Dest; // Constructeurs public Destinataire() { super(); } public Destinataire(String dest) { super(); Dest = dest; } // Getters and Setters public String getDest() { return Dest; } public void setDest(String dest) { Dest = dest; } }
fc8ddcc4fc26c3b78ea23b295a66f1771a8c43e6
79c660d37cf720fdcf385ffe96b8dcac537a8bce
/Objectif5/src/jus/poc/prodcons/v/objectif3/Consommateur.java
e93e3fdfbe331b5ca93f9a1ce7c544b210f79675
[]
no_license
nicko466/ProjetSe
c1a0b5d1fef3a4aa816dcd9fed03520460404e32
4c07930ed925a80380b283b21ea2e2009558339c
refs/heads/master
2016-09-06T03:18:40.397941
2012-12-18T03:47:12
2012-12-18T03:47:12
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,522
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jus.poc.prodcons.v.objectif3; import jus.poc.prodcons.v.objectif5.MessageX; import java.util.logging.Level; import java.util.logging.Logger; import jus.poc.prodcons.*; /** * * @author rb-ka */ public class Consommateur extends Acteur implements _Consommateur { //Nombre de message lu par le consommateur private int nbMess = 0; //Le message que lit le consommateur private MessageX msg = null; /** * Conscructeur du consommateur * @param observateur * @param moyenneTempsDeTraitement * @param deviationTempsDeTraitement * @throws ControlException */ public Consommateur(Observateur observateur, int moyenneTempsDeTraitement, int deviationTempsDeTraitement) throws ControlException{ super(2, observateur, moyenneTempsDeTraitement, deviationTempsDeTraitement); this.deviationTempsDeTraitement=deviationTempsDeTraitement; this.moyenneTempsDeTraitement=moyenneTempsDeTraitement; } @Override public void run() { while(!TestProdCons.getStop()){ retirer(); consommer(); try{ Thread.sleep(Aleatoire.valeur(moyenneTempsDeTraitement, deviationTempsDeTraitement)*100); } catch(Exception e){} } } /** * Permet de retirer un message du tampon */ public void retirer(){ nbMess++; try { msg = (MessageX)TestProdCons.tampon.get(this); observateur.retraitMessage(this, msg); } catch (Exception ex) { Logger.getLogger(Consommateur.class.getName()).log(Level.SEVERE, null, ex); } } /** * Affiche le message que le consommateur à retirer du tampon */ public void consommer(){ try { observateur.consommationMessage(this, msg, Aleatoire.valeur(moyenneTempsDeTraitement, deviationTempsDeTraitement)*100); } catch (ControlException ex) { Logger.getLogger(Consommateur.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Consommateur : "+this.identification()+" à consommer le message n° " +nbMess+" contenant : \n\t\t"+msg+"\n"); TestProdCons.incrémenteNombreMessageConsommées(); } @Override public int nombreDeMessages() { return this.nbMess; } }
50576df2b0aefcf5758b8bfde89819513e3cb292
fded74c9fa333fac30dfaeafe7b3f7214af04468
/app/src/main/java/com/suda/openpayshortcut/activity/pay/MobikeScanActivity.java
c777726997bbd56caff4e5ed3baffb2d9f19fe03
[]
no_license
dlhxr/OpenPayShortcut
9a0b7b53bd6d5eff136799e1c61a9de643cede52
7dbf81ce35fc8e655b72fa288ab6018ac97f050e
refs/heads/master
2021-05-10T17:23:11.415620
2018-01-28T02:17:35
2018-01-28T02:17:35
118,607,963
0
0
null
2018-01-23T12:32:32
2018-01-23T12:32:31
null
UTF-8
Java
false
false
447
java
package com.suda.openpayshortcut.activity.pay; import com.suda.openpayshortcut.util.RootShell; /** * Created by dlhxr on 2018/01/27. */ public class MobikeScanActivity extends BasePayActivity { @Override public void openPay() { RootShell rootShell = RootShell.open(); rootShell.execute("am start -n com.mobike.mobikeapp/com.mobike.mobikeapp.activity.riding.QRCodeScannerActivity"); rootShell.close(); } }
7269e11efaa83c8bc3fb8bc51e732d99774f07c8
f6b90fae50ea0cd37c457994efadbd5560a5d663
/android/nut-dex2jar.src/com/google/android/gms/signin/internal/c.java
71a9850eb1f26eb17aef65ec19d8df333ee8be9f
[]
no_license
dykdykdyk/decompileTools
5925ae91f588fefa7c703925e4629c782174cd68
4de5c1a23f931008fa82b85046f733c1439f06cf
refs/heads/master
2020-01-27T09:56:48.099821
2016-09-14T02:47:11
2016-09-14T02:47:11
66,894,502
1
0
null
null
null
null
UTF-8
Java
false
false
1,016
java
package com.google.android.gms.signin.internal; import android.os.IInterface; import android.os.RemoteException; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.Status; public abstract interface c extends IInterface { public abstract void a(ConnectionResult paramConnectionResult, AuthAccountResult paramAuthAccountResult) throws RemoteException; public abstract void a(Status paramStatus) throws RemoteException; public abstract void a(Status paramStatus, GoogleSignInAccount paramGoogleSignInAccount) throws RemoteException; public abstract void a(SignInResponse paramSignInResponse) throws RemoteException; public abstract void b(Status paramStatus) throws RemoteException; } /* Location: C:\crazyd\work\ustone\odm2016031702\baidu\android\nut-dex2jar.jar * Qualified Name: com.google.android.gms.signin.internal.c * JD-Core Version: 0.6.2 */
91cefd0c0328ffa4064cd0b190d767a6b08d5ae7
a94619fdc8770da90d0d307da64f19e95bcbbfc7
/java/com/google/i18n/phonenumbers/repackaged/com/google/protobuf/InvalidProtocolBufferException.java
24e970c1c73b22898f01039c87f026b72e9c3d34
[]
no_license
BeCandid/CFR
b95cf21629ced30fac290a61ff51d443057a5919
ab5019fb6196b6c8f8e2a3fe18f557b89831d690
refs/heads/master
2021-01-12T05:52:09.792333
2016-12-24T10:04:51
2016-12-24T10:04:51
77,222,002
3
0
null
null
null
null
UTF-8
Java
false
false
274
java
/* * Decompiled with CFR 0_110. * * Could not load the following classes: * java.io.IOException */ package com.google.i18n.phonenumbers.repackaged.com.google.protobuf; import java.io.IOException; public class InvalidProtocolBufferException extends IOException { }
4c0c9a98b06303d5117f822bb62720e9297ec880
b7e206810d2365e82fcac0f2b57210f06665e4c2
/interlok-core/src/main/java/com/adaptris/core/RequestReplyProducerBase.java
d16f7807e8273e6e4cec7669b613d3b223e05d6a
[ "Apache-2.0" ]
permissive
adaptris/interlok
33b829fb1979f6bbcb230a2f2592c48d0aecf680
5eeb78cfa620fb16a9827be862180118e777afc5
refs/heads/develop
2023-09-01T19:52:09.830345
2023-08-28T10:51:49
2023-08-28T11:08:15
44,253,783
28
11
Apache-2.0
2023-09-13T17:15:43
2015-10-14T14:37:52
Java
UTF-8
Java
false
false
2,330
java
/* * Copyright 2015 Adaptris Ltd. * * 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.adaptris.core; import java.util.Optional; import org.apache.commons.lang3.BooleanUtils; import com.adaptris.annotation.AdvancedConfig; import com.adaptris.annotation.InputFieldDefault; import com.adaptris.core.util.ExceptionHelper; import com.adaptris.core.util.MessageHelper; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * Abstract Request Reply enabled producer that may be extended by concrete sub-classes. * */ @NoArgsConstructor public abstract class RequestReplyProducerBase extends AdaptrisMessageProducerImp { @AdvancedConfig @InputFieldDefault(value = "false") @Getter @Setter private Boolean ignoreReplyMetadata; /** * The default timeout for request messages when not supplied. * * @return the default timeout. */ protected abstract long defaultTimeout(); protected void copyReplyContents(AdaptrisMessage reply, AdaptrisMessage original) throws ProduceException { try { MessageHelper.copyPayload(reply, original); } catch (Exception e) { throw ExceptionHelper.wrapProduceException(e); } } protected AdaptrisMessage mergeReply(AdaptrisMessage reply, AdaptrisMessage msg) throws ProduceException { if (reply == msg) { return msg; } copyReplyContents(reply, msg); if (!shouldIgnoreReplyMetadata()) { reply.getMetadata().forEach((e) -> msg.addMetadata(e)); msg.getObjectHeaders().putAll(reply.getObjectHeaders()); } Optional.ofNullable(reply.getContentEncoding()).ifPresent((s) -> msg.setContentEncoding(s)); return msg; } private boolean shouldIgnoreReplyMetadata() { return BooleanUtils.toBooleanDefaultIfNull(getIgnoreReplyMetadata(), false); } }
238edbb6814ca0f88c809c8e9ba6c5187edf3482
f695ffad9aacddd7628ec41bb8250890a36734c8
/ecp-coreservice/ecp-coreservice-common/src/main/java/com/everwing/coreservice/common/wy/entity/product/MyShoppingCartCommonService.java
6c8e0e7739ee299ab86b33a1ec0f445dd9318ba8
[]
no_license
zouyuanfa/Everwing-Cloud-Platform
9dea7e324f9447250b1b033509f17f7c8a0921be
f195dfe95f0addde56221d5c1b066290ad7ba62f
refs/heads/master
2020-04-13T18:22:36.731469
2018-12-28T06:18:37
2018-12-28T06:18:37
163,372,146
0
4
null
null
null
null
UTF-8
Java
false
false
4,462
java
package com.everwing.coreservice.common.wy.entity.product;/** * Created by wust on 2018/12/7. */ import com.alibaba.fastjson.JSONObject; import com.everwing.coreservice.common.wy.entity.common.select.asset.AssetSelectList; import com.everwing.coreservice.common.wy.entity.common.select.customer.CustomerSelectList; import com.everwing.coreservice.common.wy.entity.common.select.vehicle.VehicleSelectList; /** * * Function:普通服务购物车 * Reason: * Date:2018/12/7 * @author [email protected] */ public class MyShoppingCartCommonService implements java.io.Serializable{ private static final long serialVersionUID = -5497968690786641155L; /** 产品类型 */ private String productType; /** 项目id */ private String projectId; /** 产品批号 */ private String batchNo; /** 产品编码 */ private String productCode; /** 购买数量 */ private Integer quantity; /** 开始计费时间 */ private String startTime; /** 购买到期时间 */ private String endTime; /** 关联客户:id */ private String customerId; /** 关联客户:名称 */ private String customerName; /** 关联客户 */ private CustomerSelectList customer; /** 关联资产 */ private AssetSelectList asset; /** 关联车辆 */ private VehicleSelectList vehicle; /** 单位 */ private String unit; /** 总价 */ private String totalPrice; /** 折扣 */ private String discountAmount; /** 产品JSON对象 */ private JSONObject productJSONObject; private String description; public String getProductType() { return productType; } public void setProductType(String productType) { this.productType = productType; } public String getProjectId() { return projectId; } public void setProjectId(String projectId) { this.projectId = projectId; } public String getBatchNo() { return batchNo; } public void setBatchNo(String batchNo) { this.batchNo = batchNo; } public String getProductCode() { return productCode; } public void setProductCode(String productCode) { this.productCode = productCode; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public String getCustomerId() { return customerId; } public void setCustomerId(String customerId) { this.customerId = customerId; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public CustomerSelectList getCustomer() { return customer; } public void setCustomer(CustomerSelectList customer) { this.customer = customer; } public AssetSelectList getAsset() { return asset; } public void setAsset(AssetSelectList asset) { this.asset = asset; } public VehicleSelectList getVehicle() { return vehicle; } public void setVehicle(VehicleSelectList vehicle) { this.vehicle = vehicle; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public String getTotalPrice() { return totalPrice; } public void setTotalPrice(String totalPrice) { this.totalPrice = totalPrice; } public String getDiscountAmount() { return discountAmount; } public void setDiscountAmount(String discountAmount) { this.discountAmount = discountAmount; } public JSONObject getProductJSONObject() { return productJSONObject; } public void setProductJSONObject(JSONObject productJSONObject) { this.productJSONObject = productJSONObject; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
12dcb06d2f6fed776f24855866ef6fee196cf4e1
722493f088837bf2dd3f1ea9c2b7ccc207638386
/src/pasa/cbentley/layouter/swing/demo/RunLayouterDemoSwingDelegate.java
6e48e8359bfcbcc7ce5fcfc90a3bea6ebbbbad14
[ "MIT" ]
permissive
cpbentley/pasa_cbentley_layouter_swing
ee543561159e245161ca20c95abee578bd451662
95a8044bdf5dcfcdd860aa9fa3b464cfd8e5bfd2
refs/heads/master
2023-02-08T16:44:38.658106
2023-02-06T12:05:57
2023-02-06T12:05:57
224,897,924
0
0
null
null
null
null
UTF-8
Java
false
false
8,684
java
/* * (c) 2018-2020 Charles-Philip Bentley * This code is licensed under MIT license (see LICENSE.txt for details) */ package pasa.cbentley.layouter.swing.demo; import java.awt.Color; import java.util.Random; import javax.swing.JButton; import javax.swing.JPanel; import pasa.cbentley.byteobjects.src4.core.ByteObject; import pasa.cbentley.core.src4.ctx.ConfigUSettable; import pasa.cbentley.core.src4.ctx.IConfigU; import pasa.cbentley.core.src4.ctx.UCtx; import pasa.cbentley.core.src4.logging.Dctx; import pasa.cbentley.layouter.src4.engine.Area2DConfigurator; import pasa.cbentley.layouter.src4.engine.LayoutDelegateAdapter; import pasa.cbentley.layouter.src4.engine.LayoutWillListenerAdapter; import pasa.cbentley.layouter.src4.interfaces.ILayoutDelegate; import pasa.cbentley.layouter.src4.interfaces.ILayoutable; import pasa.cbentley.layouter.src4.tech.ITechLayout; import pasa.cbentley.layouter.swing.engine.ConfiguratorForSwing; import pasa.cbentley.layouter.swing.engine.DragPozerListener; import pasa.cbentley.layouter.swing.engine.JPanelLayoutable; import pasa.cbentley.layouter.swing.engine.KeyListenerF4DebugStringable; import pasa.cbentley.layouter.swing.engine.LayoutableAdapterForJComponent; public class RunLayouterDemoSwingDelegate extends RunLayouterDemoSwingAbstract { public static void main(String[] args) { //configuration of the code contexts ConfigUSettable configU = new ConfigUSettable(); configU.ToStringSetUsingClassLinks(true); RunLayouterDemoSwingDelegate runner = new RunLayouterDemoSwingDelegate(configU); //start inside the swing runner framework runner.run(); } private LayoutableAdapterForJComponent panelBlue; private LayoutableAdapterForJComponent panelGreen; private LayoutableAdapterForJComponent panelOrange; private LayoutableAdapterForJComponent panelRed; private LayoutableAdapterForJComponent panelWhite; private LayoutableAdapterForJComponent panelYellow; private Random rnd; public RunLayouterDemoSwingDelegate(IConfigU configU) { super(configU); constructHelpers(); rnd = slc.getUCtx().getRandom(); } public void buildDemo(JPanelLayoutable panel) { ConfiguratorForSwing configurator = panel.getConfigurator(); ILayoutDelegate delegate = new LayoutDelegateAdapter(slc) { public int getDelegateSizeHeight(ByteObject sizer, ILayoutable layoutable) { if (layoutable == panelOrange) { int h = slc.getUCtx().getRandom().nextInt(300) + 10; return h; } else if (layoutable == panelGreen) { int currentH = layoutable.getSizeDrawnHeight(); int multi = 1; if (currentH > 300) { multi = -1; } int h = currentH + (multi * rnd.nextInt(300)) + 10; return h; } else { return rnd.nextInt(100) + 20; } } public int getDelegateSizeWidth(ByteObject sizer, ILayoutable layoutable) { if (layoutable == panelOrange) { int h = rnd.nextInt(300) + 10; return h; } else if (layoutable == panelGreen) { int currentWidth = layoutable.getSizeDrawnWidth(); int multi = 1; if (currentWidth > 300) { multi = -1; } int w = currentWidth + (multi * rnd.nextInt(300)) + 10; return w; } else if (layoutable == panelRed) { int currentWidth = layoutable.getSizeDrawnWidth(); int multi = 1; if (currentWidth > 300) { multi = -1; } if (currentWidth < 50) { currentWidth += 50; } int w = currentWidth + (multi * rnd.nextInt(20)); return w; } else { return rnd.nextInt(100) + 20; } } }; createOrange(panel, delegate); createBlue(panel, delegate); createGreen(panel, delegate); createRed(panel, delegate); //createYellow(panel); //createWhite(panel); //add button last, so it is drawn last JButton buttonMove = new JButton("Move Me!"); buttonMove.setName("buttonMoveMe"); LayoutableAdapterForJComponent buttonMoveLay = configurator.createLayoutableFromSwingPref(buttonMove); buttonMoveLay.getLay().layPoz_MidXToMid_OfParent(); buttonMoveLay.getLay().layPoz_MidYToMid_OfParent(); DragPozerListener listener = new DragPozerListener(slc, buttonMoveLay, panel); KeyListenerF4DebugStringable keyLis = new KeyListenerF4DebugStringable(slc, panel); buttonMove.addKeyListener(keyLis); buttonMove.addMouseListener(listener); buttonMove.addMouseMotionListener(listener); buttonMove.addMouseWheelListener(listener); //add listener for computations slc.toStringSetDebugBreaks(new LayoutWillListenerAdapter() { public void layoutWillComputePositions(ILayoutable layoutable) { if (layoutable == panelOrange) { isBreak = true; } } public void layoutWillComputePositionX(ILayoutable layoutable) { } public void layoutWillComputePositionY(ILayoutable layoutable) { } public void layoutWillComputeSizes(ILayoutable layoutable) { } public void layoutWillComputeSizeH(ILayoutable layoutable) { } public void layoutWillComputeSizeW(ILayoutable layoutable) { if (layoutable == panelOrange) { isBreak = true; } } }); } private void createBlue(JPanelLayoutable root, ILayoutDelegate delegate) { JPanel panel = new JPanel(); panel.setName("panelBlue"); panel.setBackground(Color.BLUE); panelBlue = root.addLayoutable(panel); Area2DConfigurator lay = panelBlue.getLay(); lay.layPoz_TopToTop_OfParent(); lay.layPoz_EndToEnd_Parent(); ByteObject sizer = slc.getSizerFactory().getSizerDelegate(delegate); lay.setSizerH(sizer); lay.setSizerW(sizer); } private void createGreen(JPanelLayoutable root, ILayoutDelegate delegate) { JPanel panel = new JPanel(); panel.setName("panelGreen"); panel.setBackground(Color.GREEN); panelGreen = root.addLayoutable(panel); panelGreen.getLay().layPoz_BotToBot_OfParent(); panelGreen.getLay().layPoz_EndToEnd_Parent(); ByteObject sizer = slc.getSizerFactory().getSizerDelegate(delegate); panelGreen.getLay().setSizerH(sizer); panelGreen.getLay().setSizerW(sizer); } private void createOrange(JPanelLayoutable root, ILayoutDelegate delegate) { JPanel panel = new JPanel(); panel.setName("panelOrange"); panel.setBackground(Color.ORANGE); //first added is on the bottom panelOrange = root.addLayoutable(panel); ByteObject pozerAtPixel0Lazy = slc.getPozerFactory().getPozerAtPixel0Lazy(); panelOrange.getLay().setPozerXStart(pozerAtPixel0Lazy); panelOrange.getLay().setPozerYTop(pozerAtPixel0Lazy); ByteObject sizer = slc.getSizerFactory().getSizerDelegate(delegate); panelOrange.getLay().setSizerH(sizer); panelOrange.getLay().setSizerW(sizer); } private void createRed(JPanelLayoutable root, ILayoutDelegate delegate) { JPanel panel = new JPanel(); panel.setName("panelRed"); panel.setBackground(Color.red); panelRed = root.addLayoutable(panel); Area2DConfigurator lay = panelRed.getLay(); lay.layPoz_StartToStart_OfParent(); lay.layPoz_BotToBot_OfParent(); ByteObject sizer = slc.getSizerFactory().getSizerDelegate(delegate); lay.setSizerH(sizer); lay.setSizerW(sizer); } private void createWhite(JPanelLayoutable root) { JPanel panel = new JPanel(); panel.setName("panelWhite"); panel.setBackground(Color.WHITE); panelWhite = root.addLayoutable(panel); } private void createYellow(JPanelLayoutable root) { JPanel panel = new JPanel(); panel.setName("panelYellow"); panel.setBackground(Color.YELLOW); panelYellow = root.addLayoutable(panel); } }
8e64539d45c975413024b4099348c2cffce24e08
1fadc1383e6bb942729aa0de08fde13c86ea2ca1
/test/transform/resource/after-ecj/YieldInTryBlock.java
95b3177a83139f4ee9838124c7c70d898ffd36bb
[ "MIT" ]
permissive
abailly/lombok-pg
3d0650a5c0f9fb6a520f295ca3b74a5955123bcf
fcb65d1f0b7f2d2efa4392862c7a662564aa8f80
refs/heads/master
2021-01-21T00:56:36.602574
2012-05-12T13:02:11
2012-05-12T13:02:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,889
java
import java.lang.Iterable; class YieldTryBlock { YieldTryBlock() { super(); } public @java.lang.SuppressWarnings("all") Iterable<String> test() { class $YielderTest implements java.util.Iterator<String>, java.lang.Iterable<String>, java.io.Closeable { private boolean b; private @java.lang.SuppressWarnings("unused") RuntimeException e; private java.lang.Throwable $yieldException1; private int $state1; private int $state; private boolean $hasNext; private boolean $nextDefined; private String $next; private $YielderTest() { super(); } public java.util.Iterator<String> iterator() { if (($state == 0)) { $state = 1; return this; } else return new $YielderTest(); } public boolean hasNext() { if ((! $nextDefined)) { $hasNext = getNext(); $nextDefined = true; } return $hasNext; } public String next() { if ((! hasNext())) { throw new java.util.NoSuchElementException(); } $nextDefined = false; return $next; } public void remove() { throw new java.lang.UnsupportedOperationException(); } public void close() { do switch ($state) { case 5 : ; $state1 = 6; $state = 5; continue ; default : ; $state = 6; return ; } while (getNext()); } private boolean getNext() { java.lang.Throwable $yieldException; while (true) { try { switch ($state) { case 0 : ; $state = 1; case 1 : ; b = true; case 2 : ; $yieldException1 = null; $state1 = 2; $state = 3; case 3 : ; if (b) { throw new RuntimeException(); } $next = "bar"; $state = 5; return true; case 4 : ; $next = "foo"; $state = 5; return true; case 5 : ; { b = (! b); } if (($yieldException1 != null)) { $yieldException = $yieldException1; break ; } $state = $state1; continue ; case 6 : ; default : ; return false; } } catch (final java.lang.Throwable $yieldExceptionCaught) { $yieldException = $yieldExceptionCaught; } switch ($state) { case 3 : ; if (($yieldException instanceof RuntimeException)) { e = (RuntimeException) $yieldException; $state = 4; continue ; } case 4 : ; $yieldException1 = $yieldException; $state = 5; continue ; default : ; $state = 6; java.util.ConcurrentModificationException $yieldExceptionUnhandled = new java.util.ConcurrentModificationException(); $yieldExceptionUnhandled.initCause($yieldException); throw $yieldExceptionUnhandled; } } } } return new $YielderTest(); } }
7211a42d7f20abcd69d99544b87eab583eabe084
ee7bee058de3b35d4cbffdc24e2c29d4a352ff99
/src/main/java/br/com/zupacademy/gian/mercadolivre/produto/CaracteristicasProdutoRepository.java
ac9fa137f259e58e9c0a3f1e9d24ae6b3e333a19
[ "Apache-2.0" ]
permissive
gianmsouza/orange-talents-06-template-ecommerce
9f8acecc57dd3ac92e74db363a7abfe82bf025e2
d9496d41dfb0100966144727199f6655e77433e5
refs/heads/master
2023-05-31T20:13:10.018010
2021-07-12T14:00:26
2021-07-12T14:00:26
383,154,499
0
0
Apache-2.0
2021-07-05T13:41:52
2021-07-05T13:41:51
null
UTF-8
Java
false
false
286
java
package br.com.zupacademy.gian.mercadolivre.produto; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface CaracteristicasProdutoRepository extends JpaRepository<CaracteristicasProduto, Long> { }
7deb58e39e141223bd65489436d9cef7b5c5a1c8
f56d9ca6325ab0288b6eb5405ae04cb5c8b13cb2
/app/src/main/java/com/divine/appwisata/PushNotif.java
d567dd35d867243f13a0f84e88155ee4d989edb5
[]
no_license
yahya18/LampungTrip
48d7bb983411a897826fe5c1de9b31aeda50266d
22fc91560438926dc57c1184f656a1bc1f891e3e
refs/heads/master
2020-05-16T05:46:53.999905
2019-06-17T14:15:06
2019-06-17T14:15:06
182,825,648
0
0
null
null
null
null
UTF-8
Java
false
false
5,531
java
package com.divine.appwisata; import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.net.Uri; import android.os.Bundle; import android.os.Build; import android.support.annotation.NonNull; import android.support.v4.app.NotificationManagerCompat; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.divine.appwisata.view.MainActivity; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.messaging.FirebaseMessaging; import java.nio.channels.Channel; import java.util.Locale; public class PushNotif extends AppCompatActivity { @Override protected void onCreate(Bundle saveInstanceState) { super.onCreate(saveInstanceState); setContentView(R.layout.activity_push_notif); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel Channel = new NotificationChannel("MyNotification", "MyNotification", NotificationManager.IMPORTANCE_DEFAULT); NotificationManager manager = getSystemService(NotificationManager.class); manager.createNotificationChannel(Channel); } FirebaseMessaging.getInstance().subscribeToTopic("general") .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { String msg = getString(R.string.msg_subscribed); if (!task.isSuccessful()) { msg = getString(R.string.msg_subscribe_failed); } Toast.makeText(PushNotif.this, msg, Toast.LENGTH_SHORT).show(); } }); } } /** private Button mButtonSubscribe; private Button mButtonLogToken; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_push_notif); //start handle data extra if(getIntent().getExtras()!=null){ for(String key : getIntent().getExtras().keySet()){ String value = getIntent().getExtras().getString(key); Log.d("TAG", "KEY : " + key + "Value : " + value); } } mButtonSubscribe = (Button) findViewById(R.id.subscribeButton); mButtonSubscribe.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FirebaseMessaging.getInstance().subscribeToTopic("news"); Log.d("TAG", "Subscribe to news topic"); } }); mButtonLogToken = (Button) findViewById(R.id.logTokenButton); mButtonLogToken.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d("TAG", "InstanceID Token : " + FirebaseInstanceId.getInstance().getToken()); } }); } } import android.annotation.SuppressLint; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v4.app.NotificationCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class PushNotif extends AppCompatActivity implements View.OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_push_notif); Button button=findViewById(R.id.button); button.setOnClickListener(this); } @RequiresApi(api = Build.VERSION_CODES.O) @Override public void onClick(View v) { switch (v.getId()) { case R.id.button: notificationDialog(); break; } } @RequiresApi(api = Build.VERSION_CODES.O) private void notificationDialog() { NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); String NOTIFICATION_CHANNEL_ID = "tesnotif_01"; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX); notificationManager.createNotificationChannel(notificationChannel); } NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID); notificationBuilder.setAutoCancel(true) .setDefaults(Notification.DEFAULT_ALL) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.mipmap.ic_logo_app) .setTicker("Tes notif") .setContentTitle("LampungTrip") .setContentText("Tempat Favorite Berhasil Ditambahkan"); notificationManager.notify(1, notificationBuilder.build()); } } */
6766f52af526ca440f8269ca195c60ee607a0c60
982057aa19cefacd93556d21973edbba3377012c
/creative-build-api-doc-service/src/main/java/com/sooncode/creative_build_api_doc_service/model/response/GetAllInterfacesResponseModel.java
f967fccede1c8b4cd070f784c30bf19795cf8a75
[]
no_license
hechenwe/creative-build-api-doc-service
1da5e4cb8961645ed0da782effa93855fd0e71a8
becd519b32e0edb4ecb8d00960b7f3d57ce585ef
refs/heads/master
2018-10-28T06:08:12.527154
2018-08-22T14:39:34
2018-08-22T14:39:34
119,822,382
0
0
null
null
null
null
UTF-8
Java
false
false
1,378
java
package com.sooncode.creative_build_api_doc_service.model.response; import java.util.List; import com.sooncode.creative_build_api_doc_service.entity.Interfac; import com.sooncode.creative_build_api_doc_service.entity.Parameter; import com.sooncode.creative_build_api_doc_service.entity.ParameterRetur; public class GetAllInterfacesResponseModel { private Interfac interfac; private List<Parameter> parameters; private List<ParameterRetur> parameterReturns; private List<ParameterConstraintModel> parameterConstraintModels; public Interfac getInterfac() { return interfac; } public void setInterfac(Interfac interfac) { this.interfac = interfac; } public List<Parameter> getParameters() { return parameters; } public void setParameters(List<Parameter> parameters) { this.parameters = parameters; } public List<ParameterRetur> getParameterReturns() { return parameterReturns; } public void setParameterReturns(List<ParameterRetur> parameterReturns) { this.parameterReturns = parameterReturns; } public List<ParameterConstraintModel> getParameterConstraintModels() { return parameterConstraintModels; } public void setParameterConstraintModels(List<ParameterConstraintModel> parameterConstraintModels) { this.parameterConstraintModels = parameterConstraintModels; } }
0c183114d0438847c3b679c6af80450da70c0cca
f6328857cc731a4fc7727e9fec4e3a3bb0758b58
/app/src/androidTest/java/com/atang/androidtodo/ApplicationTest.java
bd67aac894c53be0887fd4936f1bedde26289cdb
[ "Apache-2.0" ]
permissive
atang-trulia/ToDo
cfa21cdc8b11d20acd8f3980c91f80f5fc6b7ae6
2799ed691bec4ad3d840106f8cc88301d49a1327
refs/heads/master
2016-08-12T03:16:25.551662
2016-04-09T07:57:49
2016-04-09T07:57:49
54,533,849
0
0
null
null
null
null
UTF-8
Java
false
false
352
java
package com.atang.androidtodo; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
950d2df02615b3bc1c3c35798df15b6cb2a595cb
fb0d90d605ede40a574520e5d779c616821aa09e
/src/ProxyTeht/RealImage.java
2e2488343e15be204800639122f3f41601559add
[]
no_license
Ozuge/KouluSuunnittelumallit
722f6973007edc7e2ac8b0c0c098b2183825988d
d4ed29e6d3097be182296d5e4c25307647467921
refs/heads/master
2020-03-08T13:44:11.585497
2018-05-03T10:56:57
2018-05-03T10:56:57
126,799,515
0
0
null
null
null
null
UTF-8
Java
false
false
902
java
/* * 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 ProxyTeht; /** * * @author ottoj_000 */ public class RealImage implements Image{ private String filename = null; /** * Constructor * @param filename */ public RealImage(final String filename) { this.filename = filename; loadImageFromDisk(); } /** * Loads the image from the disk */ private void loadImageFromDisk() { System.out.println("Loading " + filename); } /** * Displays the image */ public void displayImage() { System.out.println("Displaying " + filename); } public void showData(){ System.out.println(filename); } }
0a35afb7da43b2b74e24cfcac5d73c42ab167203
46946342fed948e9f65e22328d14c8f13b857ae1
/mapsdk/src/main/java/com/unistrong/api/mapcore/IMapFragmentDelegate.java
871fb9ac447834cb4171a9d9f831b5283d64144f
[]
no_license
UersNOer/AllInLinkApp
a1805816198d12e9d491c8f8af1a58fcc091c4ff
1a75da52e53921060a934bdb653d29708cb1d87d
refs/heads/master
2023-07-09T22:48:05.180754
2021-08-13T06:59:17
2021-08-13T06:59:17
394,186,337
2
0
null
2021-08-13T06:59:18
2021-08-09T07:04:41
Java
UTF-8
Java
false
false
1,470
java
package com.unistrong.api.mapcore; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.os.RemoteException; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.unistrong.api.maps.UnistrongException; import com.unistrong.api.maps.MapOptions; public abstract interface IMapFragmentDelegate { public abstract IMapDelegate getMapDelegate() throws RemoteException, UnistrongException; public abstract void onInflate(Activity paramActivity, MapOptions mapOptions, Bundle paramBundle) throws RemoteException; public abstract void setContext(Context context); public abstract void setMapOptions(MapOptions mapOptions); public abstract void onCreate(Bundle paramBundle) throws RemoteException; public abstract View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle) throws RemoteException, UnistrongException; public abstract void onResume() throws RemoteException; public abstract void onPause() throws RemoteException; public abstract void onDestroyView() throws RemoteException; public abstract void onDestroy() throws RemoteException; public abstract void onLowMemory() throws RemoteException; public abstract void onSaveInstanceState(Bundle paramBundle) throws RemoteException; public abstract void setVisible(int visible); }
bf67e54c2e35d1571aabbf0cbf77ba23158f0c21
05b0e970c1f6d9225f0be81a1f46a60cff0fa540
/IdeaProjects/java200/chapter15/SearchString.java
4a6b651b9cc6ce4ce945f8527cd7de24344e70ee
[]
no_license
jonghui7179/java200
5ce46ff8f5e98ddc78f5bdbe734e16c2b2ebb20b
51e5966ce206e7de9bf247f8969628406b658fa2
refs/heads/master
2020-06-25T01:27:01.796524
2019-08-04T13:28:19
2019-08-04T13:28:19
199,121,323
0
0
null
null
null
null
UTF-8
Java
false
false
612
java
import java.util.Scanner; class SearchString { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); System.out.print("문자열 s1:"); String s1 = stdIn.next(); System.out.print("문자열 s2:"); String s2 = stdIn.next(); int idx = s1.indexOf(s2); if (idx==-1) System.out.println("s1안에 s2가 포함돼 있지 않습니다."); else { System.out.println(s1); for (int i=0;i<idx;i++) System.out.print(' '); System.out.println(s2); } } }
d7c825aecf439c83d62ca4747d7e17255f91bea8
1ae6b68e500d86d54c2d03b7d4629a6c591a1336
/src/aksha/connectiondetector/ConnectionDetector.java
0bf116e56c63296a85038d4dab1415ad1d6b4a65
[]
no_license
krishnapratap007/Mosaic
769dfd1b7eade3e192c7825c911368d725b1e729
dcaf4cab184a6411eebfb1ccd169d57f1a3ad7ed
refs/heads/master
2016-09-06T02:29:28.522984
2015-03-27T09:37:39
2015-03-27T09:37:39
32,975,804
0
0
null
null
null
null
UTF-8
Java
false
false
766
java
package aksha.connectiondetector; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class ConnectionDetector { private Context _context; public ConnectionDetector(Context context){ this._context = context; } public boolean isConnectingToInternet(){ ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) for (int i = 0; i < info.length; i++) if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } return false; } }
6dc557551180dccc43d7031ff6e1813f3991213c
96726e8528eaf3d93d58fb3f0267de8dba7799f9
/src/argouml-app/src/org/argouml/configuration/IConfigurationFactory.java
fc279791ea548b5028951c002366d1ddf01ba06c
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive" ]
permissive
marcusvnac/argouml-spl
c84d556a98e1a04f01fba3a921db6cb62e519085
bcae37308b13b7ee62da0867a77d21a0141a0f18
refs/heads/master
2021-01-12T20:55:55.500881
2015-06-11T19:41:28
2015-06-11T19:41:28
37,139,993
4
2
null
null
null
null
UTF-8
Java
false
false
2,041
java
// $Id: IConfigurationFactory.java 40 2010-04-03 19:25:46Z marcusvnac $ // Copyright (c) 2006-2007 The Regents of the University of California. All // Rights Reserved. Permission to use, copy, modify, and distribute this // software and its documentation without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph appear in all copies. This software program and // documentation are copyrighted by The Regents of the University of // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. package org.argouml.configuration; /** * Configuration Factory interface. * * @author Tom Morris */ public interface IConfigurationFactory { /** * Returns the customized configuration for the user. * * @return a concrete class which extends ConfigurationHandler and * can be used to access and manipulate the configuration. */ public abstract ConfigurationHandler getConfigurationHandler(); }
9156591c12dff92f8658fc1f1cc665f41eb4eebe
798e3563930a7f5098a790d86cba09a53a9030bd
/src/com/uas/erp/service/oa/VacationService.java
070449963310a5495950fd6d527dab4543aed93c
[]
no_license
dreamvalley/6.0.0
c5cabed6f34cab783df16de9ff6ddfc118b7c4fe
12ed81bf7a46a649711bcf654bf9bcafe70054c2
refs/heads/master
2022-02-17T02:31:57.439726
2018-07-25T02:52:27
2018-07-25T02:52:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,087
java
package com.uas.erp.service.oa; import java.util.Map; public interface VacationService { void saveVacation(String formStore, String caller); void updateVacationById(String formStore, String caller); void deleteVacation(int va_id, String caller); void auditVacation(int va_id, String caller); void resAuditVacation(int va_id, String caller); void submitVacation(int va_id, String caller); void resSubmitVacation(int va_id, String caller); void updateEmployeeHoliday(String caller); String checkHoliday(int va_id,String caller); void updateEmployeeHavedays(String condition); void auditAsk4Leave(int va_id, String caller); void resAuditAsk4Leave(int va_id, String caller); void confirmAsk4Leave(int id, String caller); Map<String, Object> sickCheck(int va_id, String caller); void cleanEmpdays(int id, String caller); void checkTime(Map<Object, Object> formStore); void resEndVacation(int id, String caller); void endVacation(int id, String caller); int checkDuplicateTime(String emcode,String start,String end); }
0ef7d04681219e9c25c77e3d733b2cc3fc576081
06b4e34f823e293e1751ed08d4245c0595e64fb5
/src/main/java/com/ecom/user/dto/ProductDTO.java
192db58298998b7a87ae8ea18cb90fa63ab911f0
[]
no_license
Adhishree22/UserMS
0fe0299a5f65ab150c903702de7419c3bfe4cdbb
97908c9dc0c666319776a6054897821a4f9fa81a
refs/heads/main
2023-07-18T18:42:25.261698
2021-09-12T14:18:52
2021-09-12T14:18:52
405,579,455
0
0
null
null
null
null
UTF-8
Java
false
false
2,452
java
package com.ecom.user.dto; public class ProductDTO { String prodId; String productName; Double price; Integer stock; String description; String image; String sellerId; String category; String subcategory; Double productrating; public String getProdId() { return prodId; } public void setProdId(String prodId) { this.prodId = prodId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public Integer getStock() { return stock; } public void setStock(Integer stock) { this.stock = stock; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getSellerId() { return sellerId; } public void setSellerId(String sellerId) { this.sellerId = sellerId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getSubcategory() { return subcategory; } public void setSubcategory(String subcategory) { this.subcategory = subcategory; } public Double getProductrating() { return productrating; } public void setProductrating(Double productrating) { this.productrating = productrating; } public ProductDTO() { super(); } @Override public String toString() { return "ProductDTO [prodId=" + prodId + ", productName=" + productName + ", price=" + price + ", stock=" + stock + ", description=" + description + ", image=" + image + ", sellerId=" + sellerId + ", category=" + category + ", subcategory=" + subcategory + ", productrating=" + productrating + "]"; } public ProductDTO(String prodId, String productName,Double price, Integer stock,String description ,String image, String sellerId, String category, String subcategory, Double productrating) { this(); this.prodId = prodId; this.productName = productName; this.price = price; this.stock = stock; this.description = description; this.image = image; this.sellerId = sellerId; this.category = category; this.subcategory = subcategory; this.productrating = productrating; } }
6d0a43dd8be936f22fef27eeaf009a241cf3aabe
a01b802cbcb99c9476286d7dfb40533ec684c8d8
/app/src/main/java/red/shaurya2k17/Sports/Cricket/Batsmen.java
21529dacbedba94866825570f17fc6f4c07a44c5
[]
no_license
anr007/Shaurya2K17
2383d90e802244f44bbc09513c3bebb1424ec636
65f5631e4d483dd81f1e9ee23872427f7458d1b1
refs/heads/master
2020-04-06T04:14:43.776051
2018-02-19T14:00:53
2018-02-19T14:00:53
83,027,557
0
1
null
null
null
null
UTF-8
Java
false
false
1,012
java
package red.shaurya2k17.Sports.Cricket; /** * Created by reddy on 27/2/17. */ public class Batsmen { String name; String runs; String fours; String sixes; String team; String balls; public String getBalls() { return balls; } public void setBalls(String balls) { this.balls = balls; } public String getRuns() { return runs; } public void setRuns(String runs) { this.runs = runs; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFours() { return fours; } public void setFours(String fours) { this.fours = fours; } public String getSixes() { return sixes; } public void setSixes(String sixes) { this.sixes = sixes; } public String getTeam() { return team; } public void setTeam(String team) { this.team = team; } }
93f01ebd8851ae973ceed25dc0cb668483fa4656
53831214cbde3df6fd733d6efbfcb36ec3ad4179
/app/src/test/java/br/com/greg/schedule/ExampleUnitTest.java
a6b98fa50481efa51cbeba1ed0739724d62e1bb8
[]
no_license
gregorydossantos/FirstApp
f15b65999346c680021f7426d5775ccd8761373c
e27aac828cfa829d0dee7766a91fb0c9514b8ead
refs/heads/master
2021-04-14T09:27:13.861242
2020-09-26T15:37:43
2020-09-26T15:37:43
249,222,684
0
0
null
null
null
null
UTF-8
Java
false
false
381
java
package br.com.greg.schedule; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
4dc99917231a3ed93bf5f2406cef97b32fbdd4dd
6f0fbae7f7a7759768f68d876a4161c85469efbc
/src/main/java/com/thrust/Action.java
9182a8bb7f8703ae83132628005dd8bf30779dcd
[]
no_license
DanielGarciaMandillo/java-thrust
eb3fdc827374a89f5e77c1eea588e100f98d544c
69e0ce298c3aa94c7b59c143e0977fd5b1ad1915
refs/heads/master
2021-01-10T17:58:19.118260
2016-03-30T12:43:48
2016-03-30T12:43:48
44,270,922
1
0
null
null
null
null
UTF-8
Java
false
false
390
java
package com.thrust; public final class Action { public static final Action CALL = new Action("call"); public static final Action CREATE = new Action("create"); private String _action; private Action(String action) { this._action = action; } public String getName() { return _action; } @Override public String toString() { return "Action [_action=" + _action + "]"; } }
d9a8e6de6550eda0e96f875a34745ce10c11d129
b17eeacdd32ef4d22815bf8a31b4bb2bd5e2cf57
/app/src/main/java/com/neatfox/mishutt/ui/fragment/TransactionCategoryFragment.java
171ec225cc922ab699576c8c47c75ec42217ea42
[]
no_license
Neatfox/mishutt
28a86603540cc1daf15785d041ffdfcc6a71e7c8
d3d13f1b6f01dadd03a35a810159a04c40da0656
refs/heads/master
2023-03-20T03:41:20.943067
2021-03-16T19:05:31
2021-03-16T19:05:31
332,720,390
0
0
null
null
null
null
UTF-8
Java
false
false
8,116
java
package com.neatfox.mishutt.ui.fragment; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.android.volley.AuthFailureError; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.RetryPolicy; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.google.android.material.snackbar.Snackbar; import com.neatfox.mishutt.R; import com.neatfox.mishutt.singleton.Singleton; import com.neatfox.mishutt.ui.adapter.TransactionCategoryAdapter; import com.neatfox.mishutt.ui.model.TransactionCategory; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Objects; import static com.neatfox.mishutt.Constants.api_transaction_category_list; public class TransactionCategoryFragment extends Fragment { NetworkInfo networkInfo; SharedPreferences sharedPreference; SharedPreferences.Editor editor; Activity activity; Context context; CoordinatorLayout layout; LinearLayout layout_category_headers; SwipeRefreshLayout swipeRefreshLayout; RecyclerView.LayoutManager layoutManager; RecyclerView recyclerView; TransactionCategoryAdapter adapter; ArrayList<TransactionCategory> transaction_category = new ArrayList<>(); TextView no_list; ProgressBar loading; public void noNetwork() { Snackbar.make(layout, R.string.no_internet, Snackbar.LENGTH_SHORT).show(); } public void snackBarError() { Snackbar.make(layout, R.string.something_went_wrong, Snackbar.LENGTH_SHORT).show(); } public TransactionCategoryFragment() { // Required empty public constructor } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_transaction_category, container, false); activity = getActivity(); context = getContext(); ConnectivityManager connMgr = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE); networkInfo = Objects.requireNonNull(connMgr).getActiveNetworkInfo(); sharedPreference = activity.getSharedPreferences("user_pref", 0); editor = sharedPreference.edit(); editor.apply(); layout = view.findViewById(R.id.layout); layout_category_headers = view.findViewById(R.id.layout_category_headers); swipeRefreshLayout = view.findViewById(R.id.swipeRefresh); layoutManager = new LinearLayoutManager(getContext()); recyclerView = view.findViewById(R.id.recyclerView); no_list = view.findViewById(R.id.tv_no_list); loading = view.findViewById(R.id.loading); layout_category_headers.setVisibility(View.GONE); loading.setVisibility(View.VISIBLE); if (networkInfo != null && networkInfo.isConnected()) { getTransactionCategories(); } else { noNetwork(); } swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { if (networkInfo != null && networkInfo.isConnected()) { getTransactionCategories(); } else { noNetwork(); } new Handler().postDelayed(new Runnable() { @Override public void run(){ swipeRefreshLayout.setRefreshing(false); } },1000); } }); return view; } private void getTransactionCategories(){ transaction_category = new ArrayList<>(); StringRequest request = new StringRequest(Request.Method.POST, api_transaction_category_list, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.i("Transaction Category>>>", "onResponse::::: " + response); JSONObject resObj; int status = 0; try { resObj = new JSONObject(response); status = resObj.getInt("status"); } catch (JSONException e) { e.printStackTrace(); } if (status == 1) { if (!transaction_category.isEmpty()) { transaction_category.clear(); } try { JSONObject jsonRootObject = new JSONObject(response); JSONArray jsonArray = jsonRootObject.getJSONArray("list"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); TransactionCategory transactionCategory = new TransactionCategory(); transactionCategory.setTransaction_category_id(jsonObject.optString("id")); transactionCategory.setCategory(jsonObject.optString("cname")); transactionCategory.setFrequency(jsonObject.optString("frequency")); transaction_category.add(transactionCategory); } recyclerView.setLayoutManager(layoutManager); adapter = new TransactionCategoryAdapter(transaction_category,context); recyclerView.setAdapter(adapter); } catch (JSONException e) { e.printStackTrace(); } loading.setVisibility(View.GONE); layout_category_headers.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.VISIBLE); no_list.setVisibility(View.GONE); } else { loading.setVisibility(View.GONE); layout_category_headers.setVisibility(View.GONE); recyclerView.setVisibility(View.GONE); no_list.setVisibility(View.VISIBLE); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { loading.setVisibility(View.GONE); layout_category_headers.setVisibility(View.GONE); recyclerView.setVisibility(View.GONE); snackBarError(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("uid", sharedPreference.getString("register_id", "")); return params; } }; int socketTimeout = 5000; //5 seconds - change to what you want RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); request.setRetryPolicy(policy); Singleton.getInstance(context).addToRequestQueue(request); } }
1a911cdac6f9c3dbad0ad5b4d60f62d283b17b23
a321cab7398276b3389377069ad7a5957f05520c
/OnlineSalonAppointment/src/main/java/com/cg/service/CustomerServiceImpl.java
b19885bfb70b8e882e613c4ffccc5773ac4d23fc
[]
no_license
Pranavi-Peddoju/OnlineSalonApplication-backend
aec654f534e0a7874a6e029cce0f2f82cf225f5a
f4b158583b995d7c62942511901e98b9648800ac
refs/heads/master
2023-01-24T06:08:07.164331
2020-12-08T18:56:31
2020-12-08T18:56:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,444
java
package com.cg.service; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.stereotype.Service; import com.cg.exception.DuplicateRecordException; import com.cg.exception.InvalidInputException; import com.cg.exception.NoSuchUserException; import com.cg.model.Address; import com.cg.model.Customer; import com.cg.repository.ICustomerRepository; @Service public class CustomerServiceImpl implements ICustomerService { private static final Logger log = LoggerFactory.getLogger(CustomerServiceImpl.class); // Tells the application context to inject an instance of ICustomerRepository @Autowired private ICustomerRepository repository; /** * addCustomer * <p> * This method adds the customer details into database if userName is unique. * Else Integrity Violation Exception is caught and duplicate record exception * is thrown * </p> * * @param : Customer * @throws : DuplicateRecordException if a record with same id exists * @return Customer - This returns the customer details */ @Override public Customer addCustomer(Customer customer) { try { log.info("Storing the customer record into database"); repository.save(customer); log.info("stored successfully"); return customer; } catch (DataIntegrityViolationException ex) { log.error("Exception Stack Trace" + ex.getMessage()); throw new DuplicateRecordException( "User with this user Name : " + customer.getUserName() + " Already Exists"); } } /** * updateCustomer * <p> * If userId is provided and is an existing record, Then updates the details * based on ID. Else if userId doesn't exist or if it is not Provided but if * user Name is provided and is an existing record then the details are updated * based on User Name. * </p> * * @param : Customer * @return Customer - This returns the customer details */ @Override public Customer updateCustomer(Customer customer) { Customer toUpdate; if (repository.existsById(customer.getUserId())) { log.info("Valid User Id is provided updating based on user Id : " + customer.getUserId()); toUpdate = repository.findById(customer.getUserId()).get(); } else { log.info("User Id might not be provide or Invalid."); toUpdate = getByUserName(customer.getUserName()); log.info("Updating the record to the same userID based on existing user Name"); customer.setUserId(toUpdate.getUserId()); } log.info("Updating the customer's address to the existing customers address Id"); Address toUpdateAddress = repository.findByAddress(toUpdate.getAddress().getAddressId()); log.info("Updating the Record of user with userId : " + toUpdate.getUserId()); customer.getAddress().setAddressId(toUpdateAddress.getAddressId()); return repository.save(customer); } /** * getCustomerById * <p> * This method will get the customer details based on customer's user Id * </p> * * @param : userId * @throws : NoSuchUserException if user with that id not found * InvalidInputException if id is not valid * @return Customer - This returns customer details **/ @Override public Customer getCustomerById(long userId) { if (userId == 0 || userId < 99999 || userId > 200000) { log.error("Invalid user Id provided. Throwing exception"); throw new InvalidInputException("The user Id must be 6 digits starting with 1"); } else if (repository.existsById(userId)) { log.info("Details exist. Getting the details By Id : " + userId); Customer get = repository.findById(userId).get(); return get; } else { log.error("No user found throwing exception"); throw new NoSuchUserException("No such user found"); } } /** * getAllCustomers * <p> * This method will get the all the customer details * </p> * * @return List<Customer> - This returns List of All customer details **/ @Override public List<Customer> getAllCustomers() { List<Customer> customers = repository.findAll(); if (!customers.isEmpty()) { log.info("Returning all customer details"); return customers; } else { log.error("List is empty. Throwing Exception"); throw new NoSuchUserException("Currently No Customer details"); } } /** * removeCustomer * <p> * This method deletes the customer details based on customer's user Id * </p> * * @param : userId * @return boolean - This returns true if successfully deleted **/ @Override public boolean removeCustomer(long userId) { Customer user = getCustomerById(userId); log.info("Deleted customer details with user Id : " + userId); repository.delete(user); return true; } /** * getByUserName * <p> * This method will get the customer details based on customer's user Name * </p> * * @param : userName * @throws : NoSuchUserException if user with that name not found * @return Customer - This returns customer details **/ public Customer getByUserName(String userName) { Customer get = repository.findByUserName(userName); if (get != null) { log.info("Getting customer details based on admins user name : " + userName); return get; } else { log.error("No customer details found with user name : " + userName + ". Throwing Exception"); throw new NoSuchUserException("No such user found"); } } }
bbd28736c80576931c6929d4ebeece5465c79656
f14190ad7eb70571c18a05cafd0d177ae23e0ee8
/zalo-bot/src/main/java/com/citi/winner21/page/AbstractPage.java
cd8700e8ecad52d063385ffa560d921b2008de19
[]
no_license
tinhthanh/wefinex
8a0b0cc60162a0609d8655f23ad5850299ee7bf6
180301960362c3139ad663bb304d0fa1b032bce0
refs/heads/main
2023-04-23T14:47:47.183309
2021-05-17T14:58:33
2021-05-17T14:58:33
347,596,199
0
0
null
null
null
null
UTF-8
Java
false
false
4,401
java
package com.citi.winner21.page; import com.citi.winner21.model.ProviderAccount; import com.citi.winner21.ultils.Constants; import org.openqa.selenium.By; import org.openqa.selenium.Cookie; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.concurrent.ThreadLocalRandom; import java.util.logging.Level; import java.util.logging.Logger; public abstract class AbstractPage { private static final Logger logger = Logger.getLogger(AbstractPage.class.getName()); protected static final String BASE_URL = "https://https://chat.zalo.me"; protected static final String USER_DETAILS_URL = BASE_URL + "/Account/UserDetails"; protected static final String RACE_MEETING_URL = BASE_URL + "/Race/RaceMeeting"; protected static final String RACE_RESULT_URL = BASE_URL + "/RaceResult"; protected static final String HOME_URL = BASE_URL + "/Home/ChangeSelectedCountry?country="; protected static final String HOME_INDEX_URL = BASE_URL + "/Home/Index"; protected static final String SESSION_ID = "ASP.NET_SessionId"; protected static final String ACCOUNT_NAME = "accountName"; protected WebDriver driver; protected ProviderAccount winner21Account; protected String pageUrl; public AbstractPage(WebDriver driver, ProviderAccount winner21Account, String pageUrl) { this.driver = driver; this.pageUrl = pageUrl; this.winner21Account = winner21Account; navigateToMe(); } private boolean navigateToMe() { try { this.driver.get(pageUrl); Thread.sleep(ThreadLocalRandom.current().nextInt(10_000, 15_000)); WebDriverWait wait = new WebDriverWait(driver, Constants.TIME_OUT); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(ACCOUNT_NAME))); if (pageUrl.equals(driver.getCurrentUrl())) { logger.log(Level.INFO, "AbstractPage -> navigate to {0} is success", pageUrl); return true; } } catch (Exception e) { logger.log(Level.WARNING, "LoginService -> navigate to {0} -> Exception: {1}", new Object[] {pageUrl, e}); } logger.log(Level.INFO, "AbstractPage -> navigate to {0} is fail", pageUrl); return false; } public boolean retryKeyAlive() { for (int i = 0; i < 10; i++) { if (checkKeyAlive()) { return true; } navigateToMe(); } return false; } private boolean checkKeyAlive() { try { driver.manage().deleteAllCookies(); Cookie cookie = new Cookie.Builder(SESSION_ID, winner21Account.getAuthKey()) .isHttpOnly(true) .isSecure(false) .path("/") .build(); driver.manage().addCookie(cookie); return checkCookieExpire(); } catch (Exception e) { logger.log(Level.WARNING, "AbstractPage -> checkAlive Fail -> account: {0} -> Exception: {1}", new Object[] {winner21Account.getAccountName(), e}); } return false; } public boolean checkCookieExpire() { try { driver.get(USER_DETAILS_URL); Thread.sleep(ThreadLocalRandom.current().nextInt(10_000, 15_000)); WebDriverWait wait = new WebDriverWait(driver, Constants.TIME_OUT); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(ACCOUNT_NAME))); if (USER_DETAILS_URL.equals(driver.getCurrentUrl())) { logger.log(Level.INFO, "AbstractPage -> checkAlive Success -> account: {0}", winner21Account.getAccountName()); return true; } } catch (Exception e) { logger.log(Level.WARNING, "AbstractPage -> checkAlive Fail -> account: {0} -> Exception: {1}", new Object[] {winner21Account.getAccountName(), e}); } return false; } public void changeCountry(String country) { this.pageUrl = HOME_URL + country; navigateToMe(); } protected Object executeJavascript(String javascript) { JavascriptExecutor jse = (JavascriptExecutor) this.driver; return jse.executeScript(javascript); } }
b1e6673f1fdc96b035b367215f64770b919392b8
d8071602269e5fee1451e7f156051fffeb0985b3
/src/Statki/Main.java
3aa50a81cc6a19bb33829f20f7cdb58d9cc3fa39
[]
no_license
M1lY/Statki
1398622bc38e58e696ca02c18b811886fbf95384
25f77efb609250261cc56ad976f4ac9cdc170ef4
refs/heads/master
2022-06-04T20:48:44.282038
2022-05-19T23:17:42
2022-05-19T23:17:42
149,002,227
2
0
null
2018-12-07T18:35:22
2018-09-16T14:13:21
Java
UTF-8
Java
false
false
614
java
package Statki; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("GUI.fxml")); primaryStage.setTitle("Statki"); primaryStage.setScene(new Scene(root, 678, 509)); primaryStage.setResizable(false); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
63e30ae44034fb89f68d3b8a75fb794a60fa3f9c
861bc361284fe6b86dffc948c36f2517afac3bf7
/src/test/java/com/dappermoose/litcal/days/LeapYearTest.java
d6aed9ad35feb6fa6f37195de71fa5d92b54baf4
[]
no_license
heitkergm/litcal
706d1872b658fb42824134088fd23a6cda21fdfc
b827df651f0d64e78637b1b8e2ba93dd10ea1f05
refs/heads/main
2023-08-31T20:56:20.059563
2023-08-25T17:30:48
2023-08-25T17:30:48
59,060,827
0
0
null
2021-06-08T19:14:54
2016-05-17T21:35:19
Java
UTF-8
Java
false
false
2,297
java
package com.dappermoose.litcal.days; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; /** * Test the LeapYear class. * @author matt */ public class LeapYearTest { /** * Dummy constructor. */ public LeapYearTest () { } /** * setup before class instantiation. */ @BeforeAll public static void setUpClass () { } /** * class tear down when done with all tests. */ @AfterAll public static void tearDownClass () { } /** * Setup before each test. */ @BeforeEach public void setUp () { } /** * Tear down after each test. */ @AfterEach public void tearDown () { } /** * Test of isLeapYear method, with 1900. */ @Test public void testIsLeapYear1900 () { System.out.println ("isLeapYear - 1900"); Assertions.assertFalse (LeapYear.isLeapYear (1900)); } /** * Test of isLeapYear method, with 2000. */ @Test public void testIsLeapYear2000 () { System.out.println ("isLeapYear - 2000"); Assertions.assertTrue (LeapYear.isLeapYear (2000)); } /** * Test of isLeapYear method, with 2016. */ @Test public void testIsLeapYear2016 () { System.out.println ("isLeapYear - 2016"); Assertions.assertTrue (LeapYear.isLeapYear (2016)); } /** * Test of isLeapYear method, with 2013. */ @Test public void testIsLeapYear2013 () { System.out.println ("isLeapYear - 2013"); Assertions.assertFalse (LeapYear.isLeapYear (2013)); } /** * Test of isLeapYear method, with 2014. */ @Test public void testIsLeapYear2014 () { System.out.println ("isLeapYear - 2014"); Assertions.assertFalse (LeapYear.isLeapYear (2014)); } /** * Test of isLeapYear method, with 2015. */ @Test public void testIsLeapYear2015 () { System.out.println ("isLeapYear - 2015"); Assertions.assertFalse (LeapYear.isLeapYear (2015)); } }
97e68ddab4554b700535881cd179a18c636389e0
1d8a31a5af06c89701ac613759d79943ac8fe1fc
/library/src/main/java/es/rafaco/inappdevtools/library/view/overlay/screens/sources/SourcesScreen.java
4d53f47cd167c919e6fe5fca3b5cc67131384d97
[ "BSD-3-Clause", "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
sankarvaiyapuri/InAppDevTools
95e1d54826f2ed2164d0761983e6ee093cd2e052
774e777fbd524410fa80b35953b0ce2e26c0f438
refs/heads/master
2023-04-09T09:54:13.642419
2021-02-12T17:42:22
2021-02-12T17:42:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
13,646
java
/* * This source file is part of InAppDevTools, which is available under * Apache License, Version 2.0 at https://github.com/rafaco/InAppDevTools * * Copyright 2018-2019 Rafael Acosta Alvarez * * 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 es.rafaco.inappdevtools.library.view.overlay.screens.sources; import android.os.AsyncTask; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.ViewGroup; //#ifdef ANDROIDX //@import androidx.recyclerview.widget.RecyclerView; //@import androidx.appcompat.widget.SearchView; //#else import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; //#endif import com.google.gson.Gson; import java.util.ArrayList; import java.util.List; import es.rafaco.inappdevtools.library.Iadt; import es.rafaco.inappdevtools.library.R; import es.rafaco.inappdevtools.library.IadtController; import es.rafaco.inappdevtools.library.logic.utils.ExternalIntentUtils; import es.rafaco.inappdevtools.library.view.components.items.LinkItemData; import es.rafaco.inappdevtools.library.logic.sources.SourceEntry; import es.rafaco.inappdevtools.library.logic.utils.ClipboardUtils; import es.rafaco.inappdevtools.library.view.components.FlexAdapter; import es.rafaco.inappdevtools.library.view.overlay.OverlayService; import es.rafaco.inappdevtools.library.view.overlay.ScreenManager; import es.rafaco.inappdevtools.library.view.overlay.screens.Screen; import es.rafaco.inappdevtools.library.view.utils.ToolbarSearchHelper; import es.rafaco.inappdevtools.library.view.utils.PathUtils; public class SourcesScreen extends Screen { private FlexAdapter adapter; private RecyclerView recyclerView; private ToolbarSearchHelper toolbarSearch; private String contentOverview; private AsyncTask<Object, String, List<Object>> currentTask; public SourcesScreen(ScreenManager manager) { super(manager); } @Override public String getTitle() { return "Sources"; } @Override public int getBodyLayoutId() { return R.layout.flexible_container; } @Override public int getToolbarLayoutId() { return R.menu.sources; } @Override protected void onCreate() { //Nothing needed } @Override protected void onStart(ViewGroup view) { List<Object> data = initData(); initAdapter(data); } @Override protected void onStop() { //Nothing needed } @Override protected void onDestroy() { //Nothing needed } public static String buildParams(String origin, String path){ SourceEntry paramObject = new SourceEntry(origin, path, true); Gson gson = new Gson(); return gson.toJson(paramObject); } public SourceEntry getParams(){ Gson gson = new Gson(); return gson.fromJson(getParam(), SourceEntry.class); } //region [ DATA AND ADAPTER ] private List<Object> initData() { SourceEntry params = getParams(); return getDataByEntry(params); } private void initAdapter(List<Object> data) { adapter = new FlexAdapter(FlexAdapter.Layout.GRID, 1, data); recyclerView = bodyView.findViewById(R.id.flexible); recyclerView.setAdapter(adapter); } private List<Object> getDataByEntry(SourceEntry filter) { String path = (filter!=null) ? filter.getName() : null; List<SourceEntry> filteredItems = IadtController.get().getSourcesManager().getChildItems(path); List<Object> data= new ArrayList<>(); addRootAndUp(filter, data); addSourceEntries(filter, data, filteredItems); buildContentOverview(filter, filteredItems); return data; } private List<Object> getDataBySearch(String filter) { List<Object> data= new ArrayList<>(); List<SourceEntry> filteredItems = IadtController.get().getSourcesManager().getSearchItems(filter); if (filter.length()< 2) { addShortSearchResult(data); return data; } else if (filteredItems.size()==0){ addEmptySearchResult(data); return data; } addSourceEntries(null, data, filteredItems); buildContentOverview(filter, filteredItems); return data; } private void updateFilter(SourceEntry entry) { if (entry == null) updateParams(null); else updateParams(buildParams("TODO", entry.getName())); if (currentTask != null){ currentTask.cancel(true); } currentTask = new AsyncTask<Object, String, List<Object>>(){ @Override protected List<Object> doInBackground(Object... objects) { SourceEntry entry = (SourceEntry)objects[0]; List<Object> filteredItems = getDataByEntry(entry); return filteredItems; } @Override protected void onPostExecute(final List<Object> filteredItems) { super.onPostExecute(filteredItems); if (!currentTask.isCancelled()){ adapter.replaceItems(filteredItems); } currentTask = null; } }; currentTask.execute(entry); } private void updateSearch(String text) { if (text == null) { updateFilter(getParams()); return; } if (currentTask != null){ currentTask.cancel(true); } currentTask = new AsyncTask<Object, String, List<Object>>(){ @Override protected List<Object> doInBackground(Object... objects) { String text = (String)objects[0]; List<Object> filteredItems = getDataBySearch(text); return filteredItems; } @Override protected void onPostExecute(final List<Object> filteredItems) { super.onPostExecute(filteredItems); if (!currentTask.isCancelled()){ adapter.replaceItems(filteredItems); } currentTask = null; } }; currentTask.execute(text); } //endregion //region [ FLEXIBLE ITEMS ] private List<Object> addShortSearchResult(List<Object> data) { data.add(new LinkItemData( "Type 2 characters at least...", R.string.gmd_pause, R.color.rally_white, new Runnable() { @Override public void run() { //TODO: close search view } } )); return data; } private List<Object> addEmptySearchResult(List<Object> data) { data.add(new LinkItemData( "No results found", R.string.gmd_stop, R.color.rally_white, new Runnable() { @Override public void run() { //TODO: close search view } } )); return data; } private List<Object> addRootAndUp(SourceEntry filter, List<Object> data) { if (filter != null) { // Not root data.add(new LinkItemData( "Go to root", R.string.gmd_home, R.color.rally_white, new Runnable() { @Override public void run() { SourcesScreen.this.goRoot(); } } )); if (filter.getDeepLevel() != 0){ data.add(new LinkItemData( "Up from " + PathUtils.removeLastSlash(filter.getName()), R.string.gmd_arrow_upward, R.color.rally_white, new Runnable() { @Override public void run() { SourcesScreen.this.goUp(); } } )); } } return data; } private List<Object> addSourceEntries(SourceEntry filter, List<Object> data, List<SourceEntry> filteredItems) { for (final SourceEntry entry : filteredItems) { String label = getLinkName(entry); if (filter!=null){ label = label.replace(filter.getName(), ""); } data.add(new LinkItemData(label, entry.isDirectory() ? R.string.gmd_folder_filled : R.string.gmd_insert_drive_file, entry.isDirectory() ? R.color.rally_yellow : R.color.rally_blue_med, entry.isDirectory() ? new Runnable() { @Override public void run() { SourcesScreen.this.updateFilter(entry); } } : new Runnable() { @Override public void run() { //Review this following line toolbarSearch.getSearchView().setIconified(true); SourcesScreen.this.openSource(entry); } })); } return data; } //endregion //region [ TOOL BAR ] @Override public boolean onCreateOptionsMenu(Menu menu) { toolbarSearch = new ToolbarSearchHelper(getToolbar(), R.id.action_search); toolbarSearch.setHint("Search file names..."); toolbarSearch.getSearchView().setIconifiedByDefault(false); toolbarSearch.setOnChangeListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { //codeViewer.findNext(true); return false; } @Override public boolean onQueryTextChange(String query) { if (!query.isEmpty()) { updateSearch(query); } else { updateSearch(null); } return true; } }); toolbarSearch.setOnCloseListener(new SearchView.OnCloseListener() { @Override public boolean onClose() { updateSearch(null); return false; } }); return true; } @Override public boolean onMenuItemClick(MenuItem item) { int selected = item.getItemId(); if (selected == R.id.action_share) { ExternalIntentUtils.shareText(getContentOverview()); } else if (selected == R.id.action_copy) { ClipboardUtils.save(getContext(), getContentOverview()); Iadt.buildMessage("Content overview copied to clipboard") .isInfo().fire(); } return super.onMenuItemClick(item); } //endregion private void openSource(SourceEntry entry) { String params = SourceDetailScreen.buildSourceParams(entry.getName()); OverlayService.performNavigation(SourceDetailScreen.class, params); } private void goRoot() { updateFilter(null); } private void goUp() { String upName = getSubtitle(); updateFilter(new SourceEntry("TODO", upName, true)); } private String getSubtitle() { if (getParams()==null || TextUtils.isEmpty(getParams().getName())){ return ""; } String currentName = PathUtils.removeLastSlash(getParams().getName()); return currentName.substring(0, currentName.lastIndexOf('/')+1); } private String getLinkName(SourceEntry entry) { if (TextUtils.isEmpty(entry.getName())){ return entry.getOrigin(); } return entry.isDirectory() ? PathUtils.removeLastSlash(entry.getName()) : entry.getFileName(); } private void buildContentOverview(Object filter, List<SourceEntry> filteredItems) { String result =""; if (filter instanceof String){ result += "Sources searching for " + filter + ":\n"; } else { //(filter instanceof String) SourceEntry entry = (SourceEntry) filter; String origin = (filter == null) ? "root folder" : PathUtils.getLastLevelName(entry.getName()); result += "Sources filtered at " + origin; if (filter != null) result += " (" + entry.getName() + ")"; result += ":\n"; } for (SourceEntry item : filteredItems){ result += " - " + (item.isDirectory() ? "Folder " : "File " ) + PathUtils.getLastLevelName(item.getName()); result += " (" + item.getName() + ")\n"; } contentOverview = result; } private String getContentOverview() { return contentOverview; } }
02c09b9e4ebcfb077a0c409adb097f308400d0aa
30ae3b28031aa7635a4cbe4fee72b64f392c6f41
/src/main/java/com/arbysoft/tabularasa/service/UserService.java
6d0af012f8949c297f1f40fdbffdf584cf2e67c8
[]
no_license
lukeredgen/TabulaRasa
2587b4060ed3f5f326db2f22e01ad875f2448d12
335b500f093544391a8eb82a645d5a289816c033
refs/heads/master
2021-01-20T12:20:59.753495
2017-02-21T07:23:37
2017-02-21T07:23:37
52,085,402
0
0
null
null
null
null
UTF-8
Java
false
false
8,969
java
package com.arbysoft.tabularasa.service; import com.arbysoft.tabularasa.domain.Authority; import com.arbysoft.tabularasa.domain.User; import com.arbysoft.tabularasa.repository.AuthorityRepository; import com.arbysoft.tabularasa.repository.UserRepository; import com.arbysoft.tabularasa.security.AuthoritiesConstants; import com.arbysoft.tabularasa.security.SecurityUtils; import com.arbysoft.tabularasa.service.util.RandomUtil; import com.arbysoft.tabularasa.service.dto.UserDTO; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.ZonedDateTime; import java.util.*; /** * Service class for managing users. */ @Service @Transactional public class UserService { private final Logger log = LoggerFactory.getLogger(UserService.class); private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; private final SocialService socialService; private final AuthorityRepository authorityRepository; public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, SocialService socialService, AuthorityRepository authorityRepository) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; this.socialService = socialService; this.authorityRepository = authorityRepository; } public Optional<User> activateRegistration(String key) { log.debug("Activating user for activation key {}", key); return userRepository.findOneByActivationKey(key) .map(user -> { // activate given user for the registration key. user.setActivated(true); user.setActivationKey(null); log.debug("Activated user: {}", user); return user; }); } public Optional<User> completePasswordReset(String newPassword, String key) { log.debug("Reset user password for reset key {}", key); return userRepository.findOneByResetKey(key) .filter(user -> { ZonedDateTime oneDayAgo = ZonedDateTime.now().minusHours(24); return user.getResetDate().isAfter(oneDayAgo); }) .map(user -> { user.setPassword(passwordEncoder.encode(newPassword)); user.setResetKey(null); user.setResetDate(null); return user; }); } public Optional<User> requestPasswordReset(String mail) { return userRepository.findOneByEmail(mail) .filter(User::getActivated) .map(user -> { user.setResetKey(RandomUtil.generateResetKey()); user.setResetDate(ZonedDateTime.now()); return user; }); } public User createUser(String login, String password, String firstName, String lastName, String email, String imageUrl, String langKey) { User newUser = new User(); Authority authority = authorityRepository.findOne(AuthoritiesConstants.USER); Set<Authority> authorities = new HashSet<>(); String encryptedPassword = passwordEncoder.encode(password); newUser.setLogin(login); // new user gets initially a generated password newUser.setPassword(encryptedPassword); newUser.setFirstName(firstName); newUser.setLastName(lastName); newUser.setEmail(email); newUser.setImageUrl(imageUrl); newUser.setLangKey(langKey); // new user is not active newUser.setActivated(false); // new user gets registration key newUser.setActivationKey(RandomUtil.generateActivationKey()); authorities.add(authority); newUser.setAuthorities(authorities); userRepository.save(newUser); log.debug("Created Information for User: {}", newUser); return newUser; } public User createUser(UserDTO userDTO) { User user = new User(); user.setLogin(userDTO.getLogin()); user.setFirstName(userDTO.getFirstName()); user.setLastName(userDTO.getLastName()); user.setEmail(userDTO.getEmail()); user.setImageUrl(userDTO.getImageUrl()); if (userDTO.getLangKey() == null) { user.setLangKey("en"); // default language } else { user.setLangKey(userDTO.getLangKey()); } if (userDTO.getAuthorities() != null) { Set<Authority> authorities = new HashSet<>(); userDTO.getAuthorities().forEach( authority -> authorities.add(authorityRepository.findOne(authority)) ); user.setAuthorities(authorities); } String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword()); user.setPassword(encryptedPassword); user.setResetKey(RandomUtil.generateResetKey()); user.setResetDate(ZonedDateTime.now()); user.setActivated(true); userRepository.save(user); log.debug("Created Information for User: {}", user); return user; } /** * Update basic information (first name, last name, email, language) for the current user. */ public void updateUser(String firstName, String lastName, String email, String langKey) { userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(user -> { user.setFirstName(firstName); user.setLastName(lastName); user.setEmail(email); user.setLangKey(langKey); log.debug("Changed Information for User: {}", user); }); } /** * Update all information for a specific user, and return the modified user. */ public Optional<UserDTO> updateUser(UserDTO userDTO) { return Optional.of(userRepository .findOne(userDTO.getId())) .map(user -> { user.setLogin(userDTO.getLogin()); user.setFirstName(userDTO.getFirstName()); user.setLastName(userDTO.getLastName()); user.setEmail(userDTO.getEmail()); user.setImageUrl(userDTO.getImageUrl()); user.setActivated(userDTO.isActivated()); user.setLangKey(userDTO.getLangKey()); Set<Authority> managedAuthorities = user.getAuthorities(); managedAuthorities.clear(); userDTO.getAuthorities().stream() .map(authorityRepository::findOne) .forEach(managedAuthorities::add); log.debug("Changed Information for User: {}", user); return user; }) .map(UserDTO::new); } public void deleteUser(String login) { userRepository.findOneByLogin(login).ifPresent(user -> { socialService.deleteUserSocialConnection(user.getLogin()); userRepository.delete(user); log.debug("Deleted User: {}", user); }); } public void changePassword(String password) { userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(user -> { String encryptedPassword = passwordEncoder.encode(password); user.setPassword(encryptedPassword); log.debug("Changed password for User: {}", user); }); } @Transactional(readOnly = true) public Page<UserDTO> getAllManagedUsers(Pageable pageable) { return userRepository.findAll(pageable).map(UserDTO::new); } @Transactional(readOnly = true) public Optional<User> getUserWithAuthoritiesByLogin(String login) { return userRepository.findOneWithAuthoritiesByLogin(login); } @Transactional(readOnly = true) public User getUserWithAuthorities(Long id) { return userRepository.findOneWithAuthoritiesById(id); } @Transactional(readOnly = true) public User getUserWithAuthorities() { return userRepository.findOneWithAuthoritiesByLogin(SecurityUtils.getCurrentUserLogin()).orElse(null); } /** * Not activated users should be automatically deleted after 3 days. * <p> * This is scheduled to get fired everyday, at 01:00 (am). * </p> */ @Scheduled(cron = "0 0 1 * * ?") public void removeNotActivatedUsers() { ZonedDateTime now = ZonedDateTime.now(); List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minusDays(3)); for (User user : users) { log.debug("Deleting not activated user {}", user.getLogin()); userRepository.delete(user); } } }
c0c2c1ac79956cbdb051f6696401bc4acf78424d
58397bd631727f66f2873a97fbf9464f5de7aa7b
/Arraylist.java
f6dd5721e76c4f3e6bb9859312eedc076c6fb18d
[]
no_license
arti1302/DataStructures
f16b930da743a71dc77d95ab7fb1778ed2d38ecd
7911582c77227f53949e6f740f610fc3c1ff5ba0
refs/heads/master
2020-08-16T23:52:00.184501
2019-10-16T14:50:18
2019-10-16T14:50:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
768
java
import java.util.*; public class arraylist { public static void main(String args[]) { // create an array list ArrayList al = new ArrayList(); System.out.println("Initial size of al: " + al.size()); // add elements to the array list al.add("C"); al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); al.add(1, "A2"); System.out.println("Size of al after additions: " + al.size()); // display the array list System.out.println("Contents of al: " + al); // Remove elements from the array list al.remove("F"); al.remove(2); System.out.println("Size of al after deletions: " + al.size()); System.out.println("Contents of al: " + al); } }
5313858481f0fe2a8ca60d9f6602de49205fee61
adda6ab3c024e089cbf6d582cb8a9c26c981343e
/src/main/java/edu/uga/qrator/logic/manage/RoleManager.java
cf178d12ff935e204e3551870bb9289f4c52cf19
[]
no_license
ReneRanzinger/qrator
3d1569201bd91453d11e3c93c3286c85bc665450
571cfb93823527075323b6d19a5149ad7b53180b
refs/heads/master
2021-01-18T19:58:43.712354
2014-09-03T19:52:39
2014-09-03T19:52:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,625
java
/* * Copyright (C) 2014 Matthew Eavenson <matthew.eavenson at gmail.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. */ package edu.uga.qrator.logic.manage; import edu.uga.qrator.obj.relation.QRelationFactory; import edu.uga.qrator.obj.entity.QEntityFactory; import persist.query.filter.Filter; import java.sql.Connection; import edu.uga.qrator.obj.relation.impl.QRelationFactoryImpl; import edu.uga.qrator.obj.relation.QUserHasRoleQRole; import edu.uga.qrator.obj.entity.QRole; import edu.uga.qrator.obj.entity.QUser; import edu.uga.qrator.obj.entity.impl.QEntityFactoryImpl; import java.util.Iterator; /** * @author Matthew * * */ public class RoleManager{ private final QEntityFactory efac; private final QRelationFactory afac; public RoleManager(Connection conn){ efac = QEntityFactoryImpl.getFactory(conn); afac = QRelationFactoryImpl.getFactory(conn); } public Iterator<QRole> list(Filter<QRole> filter){ return efac.findRoles(filter); } public Iterator<QRole> list(){ return list(null); } public QRole create(String name, QUser creator){ return efac.createQRole(name, creator); } public QRole get( String name ){ Filter<QRole> filter = new Filter<QRole>(QRole.class) .eq("name", name); Iterator<QRole> roles = list(filter); if(roles.hasNext()) return roles.next(); return null; } public QRole get(long id){ Filter<QRole> filter = new Filter<QRole>(QRole.class).eq("sid", id+""); Iterator<QRole> roles = efac.findRoles(filter); if(roles.hasNext()) return roles.next(); else return null; } public void update(QRole role){ efac.updateQRole(role); } public void remove(QRole role){ efac.removeQRole(role); } }
[ "[email protected]@75b8def6-aaa5-685d-599d-15db22d5dcdd" ]
[email protected]@75b8def6-aaa5-685d-599d-15db22d5dcdd
9d2eeab162404b657553b9050bda1575a7831757
46f20893315884fa467f9ff89303d9ea2f5dd17b
/src/main/java/com/jeecg/p3/spinwin/service/WxActSpinwinPrizesService.java
53debf9f3465d639c3fd710053ece5cccc58a5d7
[]
no_license
Portg/lesson9-weixin
d30f78b68e846c4d413af0c8ac89e74cb0368b90
e67a22d9f60ebf1db2a46a866d64eab1fd4251ce
refs/heads/master
2021-01-01T05:08:23.845540
2016-04-18T07:03:45
2016-04-18T07:03:45
56,483,863
2
1
null
null
null
null
UTF-8
Java
false
false
1,062
java
package com.jeecg.p3.spinwin.service; import java.util.List; import org.jeecgframework.p3.core.utils.common.PageList; import org.jeecgframework.p3.core.utils.common.PageQuery; import com.jeecg.p3.spinwin.entity.WxActSpinwinPrizes; /** * 描述:</b>WxActSpinwinPrizesService<br> * @author:junfeng.zhou * @since:2016年03月03日 10时04分01秒 星期四 * @version:1.0 */ public interface WxActSpinwinPrizesService { public void doAdd(WxActSpinwinPrizes wxActSpinwinPrizes); public void doEdit(WxActSpinwinPrizes wxActSpinwinPrizes); public void doDelete(String id); public WxActSpinwinPrizes queryById(String id); public PageList<WxActSpinwinPrizes> queryPageList(PageQuery<WxActSpinwinPrizes> pageQuery); public List<WxActSpinwinPrizes> queryByActId(String actid); public List<WxActSpinwinPrizes> queryRemainAwardsByActId(String actid); public List<WxActSpinwinPrizes> queryByAwardIdAndActId(String awardid,String actId); public List<WxActSpinwinPrizes> queryPrizes(String jwid); public Boolean validUsed(String id); }
4e46966d8ff1a7b7a257b544ecd58f7d39e7d9de
eb4933ad36687033513164ed6f8ec433f74c61f2
/src/main/java/com/karthik/ctrl/StoryFeedController.java
57794dcccb79c586f70f7ae01b5ba18d40956ce5
[]
no_license
karthikeyan19/TalentHive_Services
78526637c91488c930b5e477733499c0583af91f
76d6cfb2efd358b91464623822db85097f3bf842
refs/heads/master
2021-01-22T10:28:56.835736
2017-06-26T08:03:21
2017-06-26T08:03:21
92,646,185
0
0
null
null
null
null
UTF-8
Java
false
false
70
java
package com.karthik.ctrl; public class StoryFeedController { }
5e1153992982b6b451d7f631f824eeedb322b4d6
d14aa2d96c6115bfe2fcfe95de842e1dd3f69f77
/src/main/java/com/example/demo/dto/PaymentInfos.java
c94b9a868408711248a14ed24fa46181ed61ec71
[]
no_license
yassirez-znafry/hotels
7dd33dcb9db86a4258e7e0774b2da4179f12156c
b9b56aab3fe86e024275f81838771528e0381fd0
refs/heads/master
2023-06-03T21:01:55.018835
2021-06-24T23:06:44
2021-06-24T23:06:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
429
java
package com.example.demo.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.sql.Date; import java.sql.Timestamp; @Data @AllArgsConstructor @NoArgsConstructor public class PaymentInfos { private Long id; private Long sum; private Boolean withCash; private Long accountNumber; private Long rentId; private Long userId; private Date paymentDate; }