blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
a01bb634b610e070cb39f8b5c26d9f191995ba7d
32,530,082,326,509
5946a26b4e8abd018fedd018920e970590f09ee3
/src/main/java/de/bloodworkxgaming/groovysandboxedlauncher/events/IGSLEvent.java
4733b0f492e5860f90f4749e6578f46221087c05
[]
no_license
BloodWorkXGaming/GroovySandboxedLauncher
https://github.com/BloodWorkXGaming/GroovySandboxedLauncher
499663c5e115c0e8a5b83a8278c305b92fee1a11
487d4080a5ab58bf4f79d2a17f40297bb8491df5
refs/heads/master
2021-09-08T18:06:10.804000
2018-03-11T17:47:00
2018-03-11T17:47:00
103,070,175
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.bloodworkxgaming.groovysandboxedlauncher.events; public interface IGSLEvent<R> { void handleEvent(R eventObject); }
UTF-8
Java
132
java
IGSLEvent.java
Java
[]
null
[]
package de.bloodworkxgaming.groovysandboxedlauncher.events; public interface IGSLEvent<R> { void handleEvent(R eventObject); }
132
0.80303
0.80303
5
25.4
22.419634
59
false
false
0
0
0
0
0
0
0.4
false
false
14
37da06716c06fe5aeb456865921b9943baeabda5
11,450,382,852,565
e8f3487665df42ea9fc5ab6bac4dcb57b98f514b
/src/main/java/com/palehorsestudios/alone/gui/IntroController.java
338613ac6844c71cce38ecbd68f17620f5708906
[]
no_license
Pale-Horse-Studios/alone
https://github.com/Pale-Horse-Studios/alone
a7f0042ac09068706463f95d4173ee2d686e79f7
103595f2a13df86c37188f9389f0b32c1cb4382b
refs/heads/master
2022-12-21T19:33:20.510000
2020-09-10T16:28:20
2020-09-10T16:28:20
290,299,393
0
3
null
false
2020-09-18T17:03:25
2020-08-25T19:00:59
2020-09-10T16:28:24
2020-09-18T17:02:47
12,096
0
3
0
Java
false
false
package com.palehorsestudios.alone.gui; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.TextArea; public class IntroController { @FXML private Button startGame; @FXML private TextArea intro; public IntroController() {} public Button getStartGame() { return startGame; } public TextArea getIntro() { return intro; } }
UTF-8
Java
386
java
IntroController.java
Java
[]
null
[]
package com.palehorsestudios.alone.gui; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.TextArea; public class IntroController { @FXML private Button startGame; @FXML private TextArea intro; public IntroController() {} public Button getStartGame() { return startGame; } public TextArea getIntro() { return intro; } }
386
0.738342
0.738342
21
17.380953
15.135818
39
false
false
0
0
0
0
0
0
0.380952
false
false
14
bf1ec365933cb7b3461d7d0236cd8f954b8fc74e
13,924,283,983,293
5477f6e9a023da9ddc2b7e90d7073dfddaf27f59
/src/main/java/com/siwoo/designpattern/proxy/remote/RemoteMain.java
43b25b9aa01e757fd32ee4070e7cdc2c0e9a8cc4
[]
no_license
Siwoo-Kim/design-pattern
https://github.com/Siwoo-Kim/design-pattern
c58f8f0626191ae4e5c99772b485f4913331badd
43dd2710d03ab2273141d6f2daf32b1ca5c6d5a6
refs/heads/master
2020-04-22T11:51:32.297000
2019-04-19T18:29:08
2019-04-19T18:29:08
170,355,221
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.siwoo.designpattern.proxy.remote; import com.siwoo.designpattern.state.GumballMachine; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; /** * Created by sm123tt@gmail.com on 2019-04-13 * Project : design-pattern * Github : http://github.com/Siwoo-Kim */ public class RemoteMain { public static void main(String[] args) throws Exception { args = getArgs(); int count = Integer.parseInt(args[1]); GumballMachine machine = new GumballMachine(args[0], count); MyRemoteImpl server = new MyRemoteImpl(); Registry registry = LocateRegistry.createRegistry(1099); registry.rebind("remoteHello", server); registry.rebind("gumballMachine", machine); } private static String[] getArgs() { return new String[]{"Seattle", "100"}; } }
UTF-8
Java
896
java
RemoteMain.java
Java
[ { "context": "rmi.server.UnicastRemoteObject;\n\n/**\n * Created by sm123tt@gmail.com on 2019-04-13\n * Project : design-pattern\n * Gith", "end": 257, "score": 0.9999029636383057, "start": 240, "tag": "EMAIL", "value": "sm123tt@gmail.com" }, { "context": "ct : design-pattern\n * Github : http://github.com/Siwoo-Kim\n */\n\npublic class RemoteMain {\n\n public static", "end": 339, "score": 0.9995288848876953, "start": 330, "tag": "USERNAME", "value": "Siwoo-Kim" } ]
null
[]
package com.siwoo.designpattern.proxy.remote; import com.siwoo.designpattern.state.GumballMachine; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; /** * Created by <EMAIL> on 2019-04-13 * Project : design-pattern * Github : http://github.com/Siwoo-Kim */ public class RemoteMain { public static void main(String[] args) throws Exception { args = getArgs(); int count = Integer.parseInt(args[1]); GumballMachine machine = new GumballMachine(args[0], count); MyRemoteImpl server = new MyRemoteImpl(); Registry registry = LocateRegistry.createRegistry(1099); registry.rebind("remoteHello", server); registry.rebind("gumballMachine", machine); } private static String[] getArgs() { return new String[]{"Seattle", "100"}; } }
886
0.690848
0.668527
33
26.151516
23.201517
68
false
false
0
0
0
0
0
0
0.515152
false
false
14
bb85740329097d9763107f0e62dd72fae91e6bf8
8,048,768,770,603
2cb1d57d4a694e42c20b1919487b2505afec91ea
/base/src/main/java/com/xiaochen/emvp/base/ui/BaseFragment.java
4e63db158042fcfc3980955d2ffd7d97551f7e67
[]
no_license
hujian222/easy_mvp
https://github.com/hujian222/easy_mvp
e96a7c79f35c300eb633b2461553589401d1b2e0
dc6aa67934f05ac7df032ad54f6b2cc4875256db
refs/heads/master
2022-04-09T17:05:26.631000
2020-03-28T04:59:27
2020-03-28T04:59:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xiaochen.emvp.base.ui; import android.content.Context; import android.view.View; import androidx.fragment.app.Fragment; import com.xiaochen.emvp.base.utils.LogUtil; //子类应该直接继承抽象父类fragment public class BaseFragment extends Fragment implements View.OnClickListener { protected Context mContext; protected final String TAG = this.getClass().getSimpleName(); @Override public void onAttach(Context context) { super.onAttach(context); this.mContext = context; } /** * 初始化控件 */ protected void initView() { } /** * 加载数据 */ protected void initData() { } /** * 点击事件处理 */ protected void initListener() { } @Override public void onClick(View v) { } @Override public void onResume() { super.onResume(); LogUtil.e(TAG, "onResume"); } }
UTF-8
Java
943
java
BaseFragment.java
Java
[]
null
[]
package com.xiaochen.emvp.base.ui; import android.content.Context; import android.view.View; import androidx.fragment.app.Fragment; import com.xiaochen.emvp.base.utils.LogUtil; //子类应该直接继承抽象父类fragment public class BaseFragment extends Fragment implements View.OnClickListener { protected Context mContext; protected final String TAG = this.getClass().getSimpleName(); @Override public void onAttach(Context context) { super.onAttach(context); this.mContext = context; } /** * 初始化控件 */ protected void initView() { } /** * 加载数据 */ protected void initData() { } /** * 点击事件处理 */ protected void initListener() { } @Override public void onClick(View v) { } @Override public void onResume() { super.onResume(); LogUtil.e(TAG, "onResume"); } }
943
0.623172
0.623172
50
16.780001
17.687611
76
false
false
0
0
0
0
0
0
0.24
false
false
14
9bff2e5f70590f4a24c027ead470c076c3fa919d
32,083,405,704,722
b5acfc936f0a8c5fc929d645c3f3de4694f044ae
/praxis.live.pxr/src/net/neilcsmith/praxis/live/pxr/PXRBuilder.java
69798b57ec06cc40427514aa3ead77eea047c92d
[]
no_license
luislasonbra/praxis-live
https://github.com/luislasonbra/praxis-live
7d6352cba51953c7e346d30810a0cbe8ad975877
289e32898fddb814e5a929f59c528fdad2cfb348
refs/heads/master
2021-08-31T14:53:12.249000
2017-12-21T17:51:17
2017-12-21T17:51:17
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2014 Neil C Smith. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3 only, as * published by the Free Software Foundation. * * This code 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 * version 3 for more details. * * You should have received a copy of the GNU General Public License version 3 * along with this work; if not, see http://www.gnu.org/licenses/ * * * Please visit http://neilcsmith.net if you need additional information or * have any questions. */ package net.neilcsmith.praxis.live.pxr; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import net.neilcsmith.praxis.core.ArgumentFormatException; import net.neilcsmith.praxis.core.CallArguments; import net.neilcsmith.praxis.core.ComponentAddress; import net.neilcsmith.praxis.core.ComponentType; import net.neilcsmith.praxis.core.info.ComponentInfo; import net.neilcsmith.praxis.live.components.api.Components; import net.neilcsmith.praxis.live.core.api.Callback; import net.neilcsmith.praxis.live.model.Connection; import net.neilcsmith.praxis.live.model.ProxyException; import net.neilcsmith.praxis.live.project.api.PraxisProject; import net.neilcsmith.praxis.live.properties.PraxisProperty; import net.neilcsmith.praxis.live.pxr.PXRParser.AttributeElement; import net.neilcsmith.praxis.live.pxr.PXRParser.ComponentElement; import net.neilcsmith.praxis.live.pxr.PXRParser.ConnectionElement; import net.neilcsmith.praxis.live.pxr.PXRParser.Element; import net.neilcsmith.praxis.live.pxr.PXRParser.PropertyElement; import net.neilcsmith.praxis.live.pxr.PXRParser.RootElement; import org.openide.util.Exceptions; /** * * @author Neil C Smith (http://neilcsmith.net) */ class PXRBuilder { private final static Logger LOG = Logger.getLogger(PXRBuilder.class.getName()); private final PraxisProject project; private final PXRDataObject source; private final RootElement root; private final List<String> warnings; private Iterator<Element> iterator; private Callback processCallback; private PXRRootProxy rootProxy; private boolean processed; private boolean registerRoot; PXRBuilder(PraxisProject project, PXRDataObject source, RootElement root, List<String> warnings) { this.project = project; this.source = source; this.root = root; registerRoot = true; this.warnings = warnings; } PXRBuilder(PXRRootProxy rootProxy, RootElement root, List<String> warnings) { this.project = null; this.source = null; this.rootProxy = rootProxy; this.root = root; registerRoot = false; this.warnings = warnings; } void process(Callback callback) { if (callback == null) { throw new NullPointerException(); } this.processCallback = callback; if (Components.getRewriteDeprecated()) { ElementRewriter rewriter = new ElementRewriter(root, warnings); rewriter.process(); } buildElementIterator(); process(); } private void process() { while (iterator.hasNext()) { if (!process(iterator.next())) { //break; return; } } if (!processed && !iterator.hasNext()) { processed = true; if (registerRoot) { PXRRootRegistry.getDefault().register(rootProxy); } processCallback.onReturn(CallArguments.EMPTY); } } private boolean process(Element element) { if (element instanceof PropertyElement) { return processProperty((PropertyElement) element); } else if (element instanceof AttributeElement) { return processAttribute((AttributeElement) element); } else if (element instanceof ConnectionElement) { return processConnection((ConnectionElement) element); } else if (element instanceof RootElement) { return processRoot((RootElement) element); } else if (element instanceof ComponentElement) { return processComponent((ComponentElement) element); } processCallback.onError(CallArguments.EMPTY); return false; } private void processError(CallArguments args) { processed = true; processCallback.onError(args); } private void warn(String msg) { if (warnings == null) { return; } warnings.add(msg); } private boolean processProperty(final PropertyElement prop) { LOG.log(Level.FINE, "Processing Property Element : {0}", prop.property); final PXRComponentProxy cmp = findComponent(prop.component.address); if (cmp == null) { propertyError(prop, CallArguments.EMPTY); return true; } PraxisProperty<?> p = cmp.getProperty(prop.property); if (p instanceof BoundArgumentProperty) { try { ((BoundArgumentProperty) p).setValue(prop.args[0], new Callback() { @Override public void onReturn(CallArguments args) { if (cmp.isDynamic()) { try { cmp.call("info", CallArguments.EMPTY, new Callback() { @Override public void onReturn(CallArguments args) { try { cmp.refreshInfo(ComponentInfo.coerce(args.get(0))); } catch (ArgumentFormatException ex) { Exceptions.printStackTrace(ex); } process(); } @Override public void onError(CallArguments args) { process(); } }); return; } catch (ProxyException ex) { Exceptions.printStackTrace(ex); } } else { process(); } } @Override public void onError(CallArguments args) { propertyError(prop, args); process(); } }); return false; } catch (Exception ex) { LOG.warning("Couldn't set property " + prop.property); } } propertyError(prop, CallArguments.EMPTY); return true; } private void propertyError(PropertyElement prop, CallArguments args) { String err = "Couldn't set property " + prop.component.address + "." + prop.property; warn(err); } private boolean processAttribute(AttributeElement attr) { PXRComponentProxy cmp = findComponent(attr.component.address); if (cmp != null) { cmp.setAttr(attr.key, attr.value); } return true; } private boolean processConnection(final ConnectionElement con) { LOG.fine("Processing Connection Element : " + con.port1 + " -> " + con.port2); try { PXRComponentProxy parent = findComponent(con.container.address); if (parent instanceof PXRContainerProxy) { ((PXRContainerProxy) parent).connect( new Connection(con.component1, con.port1, con.component2, con.port2), new Callback() { @Override public void onReturn(CallArguments args) { process(); } @Override public void onError(CallArguments args) { connectionError(con, args); process(); } }); return false; } } catch (Exception ex) { Exceptions.printStackTrace(ex); } connectionError(con, CallArguments.EMPTY); return true; } private void connectionError(ConnectionElement connection, CallArguments args) { String p1 = connection.container.address + "/" + connection.component1 + "!" + connection.port1; String p2 = connection.container.address + "/" + connection.component2 + "!" + connection.port2; String err = "Couldn't create connection " + p1 + " -> " + p2; warn(err); } private boolean processRoot(RootElement root) { if (rootProxy != null) { LOG.log(Level.FINE, "Root already exists - ignoring Root Element : {0}, Type : {1}", new Object[]{root.address, root.type}); return true; } LOG.log(Level.FINE, "Processing Root Element : {0}, Type : {1}", new Object[]{root.address, root.type}); try { final ComponentAddress ad = root.address; final ComponentType type = root.type; PXRHelper.getDefault().createComponentAndGetInfo(ad, type, new Callback() { @Override public void onReturn(CallArguments args) { try { rootProxy = new PXRRootProxy( project, source, ad.getRootID(), type, ComponentInfo.coerce(args.get(0))); process(); } catch (Exception ex) { Exceptions.printStackTrace(ex); onError(args); } } @Override public void onError(CallArguments args) { processError(args); } }); } catch (Exception ex) { Exceptions.printStackTrace(ex); processError(CallArguments.EMPTY); } return false; } private boolean processComponent(final ComponentElement cmp) { LOG.log(Level.FINE, "Processing Component Element : {0}, Type : {1}", new Object[]{cmp.address, cmp.type}); try { ComponentAddress address = cmp.address; final PXRComponentProxy parent = findComponent(address.getParentAddress()); if (parent instanceof PXRContainerProxy) { String id = address.getComponentID(address.getDepth() - 1); ((PXRContainerProxy) parent).addChild(id, cmp.type, new Callback() { @Override public void onReturn(CallArguments args) { if (parent.isDynamic()) { try { parent.call("info", CallArguments.EMPTY, new Callback() { @Override public void onReturn(CallArguments args) { try { parent.refreshInfo(ComponentInfo.coerce(args.get(0))); } catch (ArgumentFormatException ex) { Exceptions.printStackTrace(ex); } process(); } @Override public void onError(CallArguments args) { process(); } }); return; } catch (ProxyException ex) { Exceptions.printStackTrace(ex); } } else { process(); } } @Override public void onError(CallArguments args) { componentError(cmp, args); process(); } }); return false; } } catch (Exception ex) { Exceptions.printStackTrace(ex); } componentError(cmp, CallArguments.EMPTY); return true; } private void componentError(ComponentElement cmp, CallArguments args) { String err = "Couldn't create component " + cmp.address; warn(err); } private PXRComponentProxy findComponent(ComponentAddress address) { if (rootProxy == null) { return null; } if (address.getDepth() == 1 && rootProxy.getAddress().equals(address)) { return rootProxy; } else if (!rootProxy.getAddress().getRootID().equals(address.getRootID())) { return null; } PXRComponentProxy cmp = rootProxy; for (int i = 1; i < address.getDepth(); i++) { if (cmp instanceof PXRContainerProxy) { cmp = ((PXRContainerProxy) cmp).getChild(address.getComponentID(i)); } else { return null; } } return cmp; } private synchronized void buildElementIterator() { if (iterator != null) { throw new IllegalStateException(); } List<Element> elements = new LinkedList<Element>(); addComponentElements(root, elements); iterator = elements.iterator(); } private void addComponentElements(ComponentElement component, List<Element> elements) { elements.add(component); elements.addAll(Arrays.asList(component.attributes)); elements.addAll(Arrays.asList(component.properties)); for (ComponentElement child : component.children) { addComponentElements(child, elements); } elements.addAll(Arrays.asList(component.connections)); } }
UTF-8
Java
14,875
java
PXRBuilder.java
Java
[ { "context": "RIGHT NOTICES OR THIS HEADER.\n *\n * Copyright 2014 Neil C Smith.\n *\n * This code is free software; you can redist", "end": 96, "score": 0.99986732006073, "start": 84, "tag": "NAME", "value": "Neil C Smith" }, { "context": "rt org.openide.util.Exceptions;\n\n/**\n *\n * @author Neil C Smith (http://neilcsmith.net)\n */\nclass PXRBuilder {\n\n ", "end": 2070, "score": 0.9996463060379028, "start": 2058, "tag": "NAME", "value": "Neil C Smith" } ]
null
[]
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2014 <NAME>. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3 only, as * published by the Free Software Foundation. * * This code 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 * version 3 for more details. * * You should have received a copy of the GNU General Public License version 3 * along with this work; if not, see http://www.gnu.org/licenses/ * * * Please visit http://neilcsmith.net if you need additional information or * have any questions. */ package net.neilcsmith.praxis.live.pxr; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import net.neilcsmith.praxis.core.ArgumentFormatException; import net.neilcsmith.praxis.core.CallArguments; import net.neilcsmith.praxis.core.ComponentAddress; import net.neilcsmith.praxis.core.ComponentType; import net.neilcsmith.praxis.core.info.ComponentInfo; import net.neilcsmith.praxis.live.components.api.Components; import net.neilcsmith.praxis.live.core.api.Callback; import net.neilcsmith.praxis.live.model.Connection; import net.neilcsmith.praxis.live.model.ProxyException; import net.neilcsmith.praxis.live.project.api.PraxisProject; import net.neilcsmith.praxis.live.properties.PraxisProperty; import net.neilcsmith.praxis.live.pxr.PXRParser.AttributeElement; import net.neilcsmith.praxis.live.pxr.PXRParser.ComponentElement; import net.neilcsmith.praxis.live.pxr.PXRParser.ConnectionElement; import net.neilcsmith.praxis.live.pxr.PXRParser.Element; import net.neilcsmith.praxis.live.pxr.PXRParser.PropertyElement; import net.neilcsmith.praxis.live.pxr.PXRParser.RootElement; import org.openide.util.Exceptions; /** * * @author <NAME> (http://neilcsmith.net) */ class PXRBuilder { private final static Logger LOG = Logger.getLogger(PXRBuilder.class.getName()); private final PraxisProject project; private final PXRDataObject source; private final RootElement root; private final List<String> warnings; private Iterator<Element> iterator; private Callback processCallback; private PXRRootProxy rootProxy; private boolean processed; private boolean registerRoot; PXRBuilder(PraxisProject project, PXRDataObject source, RootElement root, List<String> warnings) { this.project = project; this.source = source; this.root = root; registerRoot = true; this.warnings = warnings; } PXRBuilder(PXRRootProxy rootProxy, RootElement root, List<String> warnings) { this.project = null; this.source = null; this.rootProxy = rootProxy; this.root = root; registerRoot = false; this.warnings = warnings; } void process(Callback callback) { if (callback == null) { throw new NullPointerException(); } this.processCallback = callback; if (Components.getRewriteDeprecated()) { ElementRewriter rewriter = new ElementRewriter(root, warnings); rewriter.process(); } buildElementIterator(); process(); } private void process() { while (iterator.hasNext()) { if (!process(iterator.next())) { //break; return; } } if (!processed && !iterator.hasNext()) { processed = true; if (registerRoot) { PXRRootRegistry.getDefault().register(rootProxy); } processCallback.onReturn(CallArguments.EMPTY); } } private boolean process(Element element) { if (element instanceof PropertyElement) { return processProperty((PropertyElement) element); } else if (element instanceof AttributeElement) { return processAttribute((AttributeElement) element); } else if (element instanceof ConnectionElement) { return processConnection((ConnectionElement) element); } else if (element instanceof RootElement) { return processRoot((RootElement) element); } else if (element instanceof ComponentElement) { return processComponent((ComponentElement) element); } processCallback.onError(CallArguments.EMPTY); return false; } private void processError(CallArguments args) { processed = true; processCallback.onError(args); } private void warn(String msg) { if (warnings == null) { return; } warnings.add(msg); } private boolean processProperty(final PropertyElement prop) { LOG.log(Level.FINE, "Processing Property Element : {0}", prop.property); final PXRComponentProxy cmp = findComponent(prop.component.address); if (cmp == null) { propertyError(prop, CallArguments.EMPTY); return true; } PraxisProperty<?> p = cmp.getProperty(prop.property); if (p instanceof BoundArgumentProperty) { try { ((BoundArgumentProperty) p).setValue(prop.args[0], new Callback() { @Override public void onReturn(CallArguments args) { if (cmp.isDynamic()) { try { cmp.call("info", CallArguments.EMPTY, new Callback() { @Override public void onReturn(CallArguments args) { try { cmp.refreshInfo(ComponentInfo.coerce(args.get(0))); } catch (ArgumentFormatException ex) { Exceptions.printStackTrace(ex); } process(); } @Override public void onError(CallArguments args) { process(); } }); return; } catch (ProxyException ex) { Exceptions.printStackTrace(ex); } } else { process(); } } @Override public void onError(CallArguments args) { propertyError(prop, args); process(); } }); return false; } catch (Exception ex) { LOG.warning("Couldn't set property " + prop.property); } } propertyError(prop, CallArguments.EMPTY); return true; } private void propertyError(PropertyElement prop, CallArguments args) { String err = "Couldn't set property " + prop.component.address + "." + prop.property; warn(err); } private boolean processAttribute(AttributeElement attr) { PXRComponentProxy cmp = findComponent(attr.component.address); if (cmp != null) { cmp.setAttr(attr.key, attr.value); } return true; } private boolean processConnection(final ConnectionElement con) { LOG.fine("Processing Connection Element : " + con.port1 + " -> " + con.port2); try { PXRComponentProxy parent = findComponent(con.container.address); if (parent instanceof PXRContainerProxy) { ((PXRContainerProxy) parent).connect( new Connection(con.component1, con.port1, con.component2, con.port2), new Callback() { @Override public void onReturn(CallArguments args) { process(); } @Override public void onError(CallArguments args) { connectionError(con, args); process(); } }); return false; } } catch (Exception ex) { Exceptions.printStackTrace(ex); } connectionError(con, CallArguments.EMPTY); return true; } private void connectionError(ConnectionElement connection, CallArguments args) { String p1 = connection.container.address + "/" + connection.component1 + "!" + connection.port1; String p2 = connection.container.address + "/" + connection.component2 + "!" + connection.port2; String err = "Couldn't create connection " + p1 + " -> " + p2; warn(err); } private boolean processRoot(RootElement root) { if (rootProxy != null) { LOG.log(Level.FINE, "Root already exists - ignoring Root Element : {0}, Type : {1}", new Object[]{root.address, root.type}); return true; } LOG.log(Level.FINE, "Processing Root Element : {0}, Type : {1}", new Object[]{root.address, root.type}); try { final ComponentAddress ad = root.address; final ComponentType type = root.type; PXRHelper.getDefault().createComponentAndGetInfo(ad, type, new Callback() { @Override public void onReturn(CallArguments args) { try { rootProxy = new PXRRootProxy( project, source, ad.getRootID(), type, ComponentInfo.coerce(args.get(0))); process(); } catch (Exception ex) { Exceptions.printStackTrace(ex); onError(args); } } @Override public void onError(CallArguments args) { processError(args); } }); } catch (Exception ex) { Exceptions.printStackTrace(ex); processError(CallArguments.EMPTY); } return false; } private boolean processComponent(final ComponentElement cmp) { LOG.log(Level.FINE, "Processing Component Element : {0}, Type : {1}", new Object[]{cmp.address, cmp.type}); try { ComponentAddress address = cmp.address; final PXRComponentProxy parent = findComponent(address.getParentAddress()); if (parent instanceof PXRContainerProxy) { String id = address.getComponentID(address.getDepth() - 1); ((PXRContainerProxy) parent).addChild(id, cmp.type, new Callback() { @Override public void onReturn(CallArguments args) { if (parent.isDynamic()) { try { parent.call("info", CallArguments.EMPTY, new Callback() { @Override public void onReturn(CallArguments args) { try { parent.refreshInfo(ComponentInfo.coerce(args.get(0))); } catch (ArgumentFormatException ex) { Exceptions.printStackTrace(ex); } process(); } @Override public void onError(CallArguments args) { process(); } }); return; } catch (ProxyException ex) { Exceptions.printStackTrace(ex); } } else { process(); } } @Override public void onError(CallArguments args) { componentError(cmp, args); process(); } }); return false; } } catch (Exception ex) { Exceptions.printStackTrace(ex); } componentError(cmp, CallArguments.EMPTY); return true; } private void componentError(ComponentElement cmp, CallArguments args) { String err = "Couldn't create component " + cmp.address; warn(err); } private PXRComponentProxy findComponent(ComponentAddress address) { if (rootProxy == null) { return null; } if (address.getDepth() == 1 && rootProxy.getAddress().equals(address)) { return rootProxy; } else if (!rootProxy.getAddress().getRootID().equals(address.getRootID())) { return null; } PXRComponentProxy cmp = rootProxy; for (int i = 1; i < address.getDepth(); i++) { if (cmp instanceof PXRContainerProxy) { cmp = ((PXRContainerProxy) cmp).getChild(address.getComponentID(i)); } else { return null; } } return cmp; } private synchronized void buildElementIterator() { if (iterator != null) { throw new IllegalStateException(); } List<Element> elements = new LinkedList<Element>(); addComponentElements(root, elements); iterator = elements.iterator(); } private void addComponentElements(ComponentElement component, List<Element> elements) { elements.add(component); elements.addAll(Arrays.asList(component.attributes)); elements.addAll(Arrays.asList(component.properties)); for (ComponentElement child : component.children) { addComponentElements(child, elements); } elements.addAll(Arrays.asList(component.connections)); } }
14,863
0.529546
0.527193
390
37.141026
25.543388
115
false
false
0
0
0
0
0
0
0.55641
false
false
14
813770f31026a8efd50676cef44d23d2d84acc93
12,051,678,261,053
28d0eba18d185aeae17c9af9b96715864ce4f01b
/OnlineExam/src/main/java/com/i2i/model/Question.java
6db65c5d3eada8f134492a5180b8485eba92381a
[]
no_license
suriyacs/OnlineExamUsingAppfuse
https://github.com/suriyacs/OnlineExamUsingAppfuse
65c744b0884a3a1e041ab3950451085b17babb3f
3cfc685d287c6151292ee3199cd4ed7c348c80c6
refs/heads/master
2021-01-13T09:07:45.478000
2016-12-22T05:31:25
2016-12-22T05:31:25
68,922,329
0
0
null
false
2016-12-22T09:19:38
2016-09-22T13:09:17
2016-12-22T05:14:21
2016-12-22T09:18:09
12,056
0
0
1
Java
null
null
package com.i2i.model; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.LazyCollection; import org.hibernate.annotations.LazyCollectionOption; import com.i2i.model.Choice; import com.i2i.model.QuestionType; import com.i2i.model.Exam; /** * <p> * Question pojo for creating instance of Question type and store list of * choices along with set of exams. * </p> * * @author TechAssess * @created 2016-08-27 */ @Entity @Table(name = "Question") public class Question { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "question_id") int questionId; @Column(name = "question") String questionName; @LazyCollection(LazyCollectionOption.FALSE) @ManyToOne(cascade = CascadeType.PERSIST) @JoinColumn(name = "type_id") QuestionType typeId; @LazyCollection(LazyCollectionOption.FALSE) @OneToMany(cascade = CascadeType.PERSIST) @JoinColumn(name = "question_id") List<Choice> choices = new ArrayList<Choice>(); @LazyCollection(LazyCollectionOption.FALSE) @ManyToMany(cascade = CascadeType.ALL, mappedBy = "questions") Set<Exam> exams = new HashSet<Exam>(); public Question() { } public Question(String questionName) { this.questionName = questionName; } public void setQuestionId(int questionId) { this.questionId = questionId; } public int getQuestionId() { return this.questionId; } public void setQuestionName(String questionName) { this.questionName = questionName; } public String getQuestionName() { return this.questionName; } public QuestionType getTypeId() { return this.typeId; } public void setTypeId(QuestionType typeId) { this.typeId = typeId; } public void setChoices(List<Choice> choice) { this.choices = choice; } @LazyCollection(LazyCollectionOption.FALSE) @ManyToMany(mappedBy = "questions") public void setExams(Set<Exam> exam) { this.exams.addAll(exam); } public Set<Exam> getExams() { return exams; } public List<Choice> getChoices() { return this.choices; } public void add(Choice choice) { this.choices.add(choice); } }
UTF-8
Java
2,733
java
Question.java
Java
[ { "context": "es along with set of exams.\n * </p>\n * \n * @author TechAssess\n * @created 2016-08-27\n */\n@Entity\n@Table(name = ", "end": 870, "score": 0.9996762275695801, "start": 860, "tag": "USERNAME", "value": "TechAssess" } ]
null
[]
package com.i2i.model; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.LazyCollection; import org.hibernate.annotations.LazyCollectionOption; import com.i2i.model.Choice; import com.i2i.model.QuestionType; import com.i2i.model.Exam; /** * <p> * Question pojo for creating instance of Question type and store list of * choices along with set of exams. * </p> * * @author TechAssess * @created 2016-08-27 */ @Entity @Table(name = "Question") public class Question { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "question_id") int questionId; @Column(name = "question") String questionName; @LazyCollection(LazyCollectionOption.FALSE) @ManyToOne(cascade = CascadeType.PERSIST) @JoinColumn(name = "type_id") QuestionType typeId; @LazyCollection(LazyCollectionOption.FALSE) @OneToMany(cascade = CascadeType.PERSIST) @JoinColumn(name = "question_id") List<Choice> choices = new ArrayList<Choice>(); @LazyCollection(LazyCollectionOption.FALSE) @ManyToMany(cascade = CascadeType.ALL, mappedBy = "questions") Set<Exam> exams = new HashSet<Exam>(); public Question() { } public Question(String questionName) { this.questionName = questionName; } public void setQuestionId(int questionId) { this.questionId = questionId; } public int getQuestionId() { return this.questionId; } public void setQuestionName(String questionName) { this.questionName = questionName; } public String getQuestionName() { return this.questionName; } public QuestionType getTypeId() { return this.typeId; } public void setTypeId(QuestionType typeId) { this.typeId = typeId; } public void setChoices(List<Choice> choice) { this.choices = choice; } @LazyCollection(LazyCollectionOption.FALSE) @ManyToMany(mappedBy = "questions") public void setExams(Set<Exam> exam) { this.exams.addAll(exam); } public Set<Exam> getExams() { return exams; } public List<Choice> getChoices() { return this.choices; } public void add(Choice choice) { this.choices.add(choice); } }
2,733
0.697402
0.693011
115
22.765217
18.492928
73
false
false
0
0
0
0
0
0
0.33913
false
false
14
ac624b3a61e7dbcfd790435e9d60939343c84c32
15,977,278,405,335
7d1df492699a1d2e5e1ab0fdb91e92ef1c3b41b8
/distr_manage/src/com/xwtech/uomp/base/service/memcache/impl/CacheTypeManageServiceImpl.java
14ae7b655344a5ee4ec159e31697ea420e4fb977
[]
no_license
5391667/xwtec
https://github.com/5391667/xwtec
ab492d6eeb4c00a2fac74ba0adc965932a4e4c5f
ca6c4f0011d5b1dbbfaa19468e5b5989c308496d
refs/heads/master
2020-05-31T16:06:18.102000
2014-04-30T08:39:05
2014-04-30T08:39:05
190,374,043
0
0
null
true
2019-06-05T10:21:40
2019-06-05T10:21:40
2019-06-05T04:58:14
2014-04-30T09:16:06
106,364
0
0
0
null
false
false
package com.xwtech.uomp.base.service.memcache.impl; import com.xwtech.uomp.base.dao.automated.CacheTypeManageMapper; import com.xwtech.uomp.base.pojo.memcache.CacheServiceManageBean; import com.xwtech.uomp.base.pojo.memcache.CacheTypeManageBean; import com.xwtech.uomp.base.service.memcache.ICacheTypeManageService; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; /** * @author huangfeilong * @ClassName: CacheTypeManageServiceImpl * @Description: 缓存类型服务实现类 * @date Mar 6, 2013 8:08:39 PM */ @Service("cacheTypeManageService") public class CacheTypeManageServiceImpl implements ICacheTypeManageService { protected static final Logger log = Logger.getLogger(CacheTypeManageServiceImpl.class); @Autowired private CacheTypeManageMapper cacheTypeManageMapper; /* * <p>Title: queryCacheTypeManageInfoList</p> * <p>Description: 查询所有缓存类型信息</p> * @param cacheTypeInfo * @return * @see com.xwtech.uomp.base.service.ICacheTypeManageService#queryCacheTypeManageInfoList(com.xwtech.uomp.base.pojo.memcache.CacheTypeManageBean) */ public List<CacheTypeManageBean> queryCacheTypeManageInfoList(CacheTypeManageBean cacheTypeInfo) { return cacheTypeManageMapper.queryCacheTypeManageInfoList(cacheTypeInfo); } /* * <p>Title: queryCacheTypeInfoById</p> * <p>Description: 根据id查询所有缓存类型信息</p> * @param typeNum * @return * @see com.xwtech.uomp.base.service.ICacheTypeManageService#queryCacheTypeInfoById(java.lang.String) */ public CacheTypeManageBean queryCacheTypeInfoById(String typeNum) { return cacheTypeManageMapper.queryCacheTypeInfoById(typeNum); } /* * <p>Title: addCacheTypeInfo</p> * <p>Description: 添加缓存类型信息</p> * @param cacheTypeInfo * @see com.xwtech.uomp.base.service.ICacheTypeManageService#addCacheTypeInfo(com.xwtech.uomp.base.pojo.memcache.CacheTypeManageBean) */ public void addCacheTypeInfo(CacheTypeManageBean cacheTypeInfo) { cacheTypeManageMapper.addCacheTypeInfo(cacheTypeInfo); } /* * <p>Title: modCacheTypeInfo</p> * <p>Description: 修改缓存类型信息</p> * @param cacheTypeInfo * @see com.xwtech.uomp.base.service.ICacheTypeManageService#modCacheTypeInfo(com.xwtech.uomp.base.pojo.memcache.CacheTypeManageBean) */ public void modCacheTypeInfo(CacheTypeManageBean cacheTypeInfo) { cacheTypeManageMapper.modCacheTypeInfo(cacheTypeInfo); } /* * <p>Title: delCacheTypeInfo</p> * <p>Description: 删除缓存类型信息</p> * @param typeNum * @see com.xwtech.uomp.base.service.ICacheTypeManageService#delCacheTypeInfo(java.lang.String) */ public void delCacheTypeInfo(String typeNum) { cacheTypeManageMapper.delCacheTypeInfo(typeNum); } /* * <p>Title: queryCacheService</p> * <p>Description: 根据typeNum 查询出具体点的缓存</p> * @param map * @return * @see com.xwtech.uomp.base.service.ICacheTypeManageService#queryCacheService(java.util.Map) */ public List<CacheServiceManageBean> queryCacheService(Map<String, Object> map) { return cacheTypeManageMapper.queryCacheService(map); } }
UTF-8
Java
3,432
java
CacheTypeManageServiceImpl.java
Java
[ { "context": "a.util.List;\nimport java.util.Map;\n\n/**\n * @author huangfeilong\n * @ClassName: CacheTypeManageServiceImpl\n * @Des", "end": 533, "score": 0.99956876039505, "start": 521, "tag": "USERNAME", "value": "huangfeilong" } ]
null
[]
package com.xwtech.uomp.base.service.memcache.impl; import com.xwtech.uomp.base.dao.automated.CacheTypeManageMapper; import com.xwtech.uomp.base.pojo.memcache.CacheServiceManageBean; import com.xwtech.uomp.base.pojo.memcache.CacheTypeManageBean; import com.xwtech.uomp.base.service.memcache.ICacheTypeManageService; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; /** * @author huangfeilong * @ClassName: CacheTypeManageServiceImpl * @Description: 缓存类型服务实现类 * @date Mar 6, 2013 8:08:39 PM */ @Service("cacheTypeManageService") public class CacheTypeManageServiceImpl implements ICacheTypeManageService { protected static final Logger log = Logger.getLogger(CacheTypeManageServiceImpl.class); @Autowired private CacheTypeManageMapper cacheTypeManageMapper; /* * <p>Title: queryCacheTypeManageInfoList</p> * <p>Description: 查询所有缓存类型信息</p> * @param cacheTypeInfo * @return * @see com.xwtech.uomp.base.service.ICacheTypeManageService#queryCacheTypeManageInfoList(com.xwtech.uomp.base.pojo.memcache.CacheTypeManageBean) */ public List<CacheTypeManageBean> queryCacheTypeManageInfoList(CacheTypeManageBean cacheTypeInfo) { return cacheTypeManageMapper.queryCacheTypeManageInfoList(cacheTypeInfo); } /* * <p>Title: queryCacheTypeInfoById</p> * <p>Description: 根据id查询所有缓存类型信息</p> * @param typeNum * @return * @see com.xwtech.uomp.base.service.ICacheTypeManageService#queryCacheTypeInfoById(java.lang.String) */ public CacheTypeManageBean queryCacheTypeInfoById(String typeNum) { return cacheTypeManageMapper.queryCacheTypeInfoById(typeNum); } /* * <p>Title: addCacheTypeInfo</p> * <p>Description: 添加缓存类型信息</p> * @param cacheTypeInfo * @see com.xwtech.uomp.base.service.ICacheTypeManageService#addCacheTypeInfo(com.xwtech.uomp.base.pojo.memcache.CacheTypeManageBean) */ public void addCacheTypeInfo(CacheTypeManageBean cacheTypeInfo) { cacheTypeManageMapper.addCacheTypeInfo(cacheTypeInfo); } /* * <p>Title: modCacheTypeInfo</p> * <p>Description: 修改缓存类型信息</p> * @param cacheTypeInfo * @see com.xwtech.uomp.base.service.ICacheTypeManageService#modCacheTypeInfo(com.xwtech.uomp.base.pojo.memcache.CacheTypeManageBean) */ public void modCacheTypeInfo(CacheTypeManageBean cacheTypeInfo) { cacheTypeManageMapper.modCacheTypeInfo(cacheTypeInfo); } /* * <p>Title: delCacheTypeInfo</p> * <p>Description: 删除缓存类型信息</p> * @param typeNum * @see com.xwtech.uomp.base.service.ICacheTypeManageService#delCacheTypeInfo(java.lang.String) */ public void delCacheTypeInfo(String typeNum) { cacheTypeManageMapper.delCacheTypeInfo(typeNum); } /* * <p>Title: queryCacheService</p> * <p>Description: 根据typeNum 查询出具体点的缓存</p> * @param map * @return * @see com.xwtech.uomp.base.service.ICacheTypeManageService#queryCacheService(java.util.Map) */ public List<CacheServiceManageBean> queryCacheService(Map<String, Object> map) { return cacheTypeManageMapper.queryCacheService(map); } }
3,432
0.739697
0.736364
89
36.078651
34.742462
149
false
false
0
0
0
0
0
0
0.224719
false
false
14
85f07fe5d33803ea9ca12e26f421017ef503f5a8
18,451,179,514,422
8bf71590ae10fc31802492bc2e2d010fbe8efdf2
/app/src/main/java/com/francescocervone/foursquare/model/Photo.java
e48d15c6ed729625f4798b44d1b80881d53d12ed
[]
no_license
francescocervone/Foursquare
https://github.com/francescocervone/Foursquare
3612e7922409289fffc087348c90efa89aa2b29b
78f717750ae9106e5d3a7d9b396f7603734f9670
refs/heads/master
2017-02-22T01:17:52.580000
2016-05-14T15:26:35
2016-05-14T15:26:35
58,613,789
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.francescocervone.foursquare.model; import com.google.gson.annotations.SerializedName; import org.parceler.Parcel; @Parcel(Parcel.Serialization.BEAN) public class Photo { @SerializedName("prefix") private String mPrefix; @SerializedName("suffix") private String mSuffix; @SerializedName("width") private int mWidth; @SerializedName("height") private int mHeight; public Photo() { } public String getPrefix() { return mPrefix; } public void setPrefix(String prefix) { mPrefix = prefix; } public String getSuffix() { return mSuffix; } public void setSuffix(String suffix) { mSuffix = suffix; } public int getWidth() { return mWidth; } public void setWidth(int width) { mWidth = width; } public int getHeight() { return mHeight; } public void setHeight(int height) { mHeight = height; } }
UTF-8
Java
979
java
Photo.java
Java
[ { "context": "package com.francescocervone.foursquare.model;\n\nimport com.google.gson.annotat", "end": 28, "score": 0.9591703414916992, "start": 12, "tag": "USERNAME", "value": "francescocervone" } ]
null
[]
package com.francescocervone.foursquare.model; import com.google.gson.annotations.SerializedName; import org.parceler.Parcel; @Parcel(Parcel.Serialization.BEAN) public class Photo { @SerializedName("prefix") private String mPrefix; @SerializedName("suffix") private String mSuffix; @SerializedName("width") private int mWidth; @SerializedName("height") private int mHeight; public Photo() { } public String getPrefix() { return mPrefix; } public void setPrefix(String prefix) { mPrefix = prefix; } public String getSuffix() { return mSuffix; } public void setSuffix(String suffix) { mSuffix = suffix; } public int getWidth() { return mWidth; } public void setWidth(int width) { mWidth = width; } public int getHeight() { return mHeight; } public void setHeight(int height) { mHeight = height; } }
979
0.623085
0.623085
54
17.129629
14.832455
50
false
false
0
0
0
0
0
0
0.277778
false
false
14
60c8132df1a61130870059375a97a7b8aa3028ea
29,222,957,504,520
62e63ac98c7b6f31c9e277dff9acbff0d7dafc2e
/src/main/java/com/atanava/parser/Application.java
2f51ca5af78e4c05f869572c7059509d92a41ea6
[]
no_license
atanava/ali-parser
https://github.com/atanava/ali-parser
4b2457edf664dedfc3bf76ba4d295dcb74ef30b6
405c66b5efeeca69cb6f25437972248af90c8810
refs/heads/master
2023-04-18T02:44:58.856000
2021-04-22T05:50:31
2021-04-22T05:52:53
360,408,693
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.atanava.parser; import com.fasterxml.jackson.databind.node.ArrayNode; import java.io.*; import java.util.Date; import java.util.Properties; public class Application { public static void main(String[] args) { try (InputStream input = new FileInputStream("src/main/resources/app.properties")) { Date start = new Date(); Properties props = new Properties(); props.load(input); String url = props.getProperty("url"); String output = props.getProperty("output"); Reader<String, ArrayNode> reader = new UrlToJsonReader(); Writer<ArrayNode, Boolean> writer = new JsonToCsvWriter(output); boolean success = writer.write(reader.read(url)); Date end = new Date(); System.out.printf("Parsed successful = %b.\nParsing time = %d millis.\nSee result in file: %s", success, (end.getTime() - start.getTime()), output); } catch (IOException e) { e.printStackTrace(); } } }
UTF-8
Java
1,065
java
Application.java
Java
[]
null
[]
package com.atanava.parser; import com.fasterxml.jackson.databind.node.ArrayNode; import java.io.*; import java.util.Date; import java.util.Properties; public class Application { public static void main(String[] args) { try (InputStream input = new FileInputStream("src/main/resources/app.properties")) { Date start = new Date(); Properties props = new Properties(); props.load(input); String url = props.getProperty("url"); String output = props.getProperty("output"); Reader<String, ArrayNode> reader = new UrlToJsonReader(); Writer<ArrayNode, Boolean> writer = new JsonToCsvWriter(output); boolean success = writer.write(reader.read(url)); Date end = new Date(); System.out.printf("Parsed successful = %b.\nParsing time = %d millis.\nSee result in file: %s", success, (end.getTime() - start.getTime()), output); } catch (IOException e) { e.printStackTrace(); } } }
1,065
0.606573
0.606573
37
27.783783
29.414223
107
false
false
0
0
0
0
0
0
0.567568
false
false
14
55915854b7c295c4dd8228b7125fdeb3cf847b6c
15,891,379,032,909
0f3026a96d45cdd58a84070e943c3994c1173dfa
/jybase-web/src/main/java/com/jingyou/jybase/web/controller/sys/RoleController.java
35aea69208909097e5bf9ca246acdfcb1673b38f
[]
no_license
ztoone/jbase
https://github.com/ztoone/jbase
cf3c1afd9625ba2915efa012028feaa3d41dddbe
60c5a94e28b02d4e32ad8a4bda0df4ab9d651d8f
refs/heads/master
2020-03-30T01:05:51.383000
2018-09-27T12:49:37
2018-09-27T12:49:38
150,559,149
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jingyou.jybase.web.controller.sys; import com.jingyou.jybase.framework.annotation.AuditLog; import com.jingyou.jybase.framework.annotation.LogType; import com.jingyou.jybase.framework.core.bean.sys.RoleBean; import com.jingyou.jybase.framework.core.bean.sys.RoleResBean; import com.jingyou.jybase.framework.core.bean.sys.UserBean; import com.jingyou.jybase.framework.core.tree.PermissionTree; import com.jingyou.jybase.framework.hibernate.query.Page; import com.jingyou.jybase.framework.hibernate.query.Conditions; import com.jingyou.jybase.service.sys.RoleResService; import com.jingyou.jybase.service.sys.RoleService; import com.jingyou.jybase.web.controller.base.BaseController; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Administrator on 2016/5/12. */ @Controller @RequestMapping(value = "/role") @AuditLog(log="角色管理",type = LogType.操作) public class RoleController extends BaseController { @Autowired private RoleService roleService; @Autowired private RoleResService roleResService; @RequestMapping("/index") public String index() { return "sys/role/list"; } @RequestMapping("/list") @ResponseBody public Map<String, Object> getRoleList(Conditions cond,Page page) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("rows", roleService.pageQuery(cond,page)); paramMap.put("total", page.getTotalCount()); return paramMap; } @RequestMapping("/listall") @ResponseBody public List<RoleBean> getParamAllList() { return roleService.findAll(); } @RequestMapping("/save") @ResponseBody @AuditLog(log="新增角色",type = LogType.操作) public JSONObject add(RoleBean role) { JSONObject obj = new JSONObject(); obj.element("status", roleService.save(role)); return obj; } @RequestMapping("/del") @ResponseBody @AuditLog(log="删除角色",type = LogType.操作) public JSONObject del(@RequestParam String[] ids) { JSONObject obj = new JSONObject(); for(String id : ids){ RoleBean temp = roleService.findByPK(id); if(temp.getType().equals("系统角色")){ obj.element("status",false); obj.element("msg","系统角色不能删除!"); return obj; } List<UserBean> users = roleService.getUsers(id); if(users != null && users.size() > 0){ obj.element("status",false); obj.element("msg","角色已赋予给用户,删除失败!"); return obj; } } obj.element("status", roleService.deleteByIds(ids)); return obj; } @RequestMapping("/toEdit/{id}") public String toEdit(Model model, @PathVariable String id) { RoleBean role = roleService.findByPK(id); model.addAttribute("role", role); return "sys//role/edit"; } @RequestMapping("/update") @ResponseBody @AuditLog(log="编辑角色",type = LogType.操作) public JSONObject update(RoleBean role) { JSONObject obj = new JSONObject(); obj.element("status", roleService.update(role)); return obj; } @RequestMapping("/check") @ResponseBody public JSONObject check(@RequestParam String value){ JSONObject obj = new JSONObject(); obj.element("status",roleService.check(value)); return obj; } @RequestMapping("/perssiontree") @ResponseBody public List<PermissionTree> resourceTree(){ PermissionTree root = roleService.getRootNode(); return root.getChildren(); } @RequestMapping("/assignres") @ResponseBody @AuditLog(log="角色分配资源",type = LogType.操作) public JSONObject assignResource(@RequestParam String roleResJson,@RequestParam String[] delIds){ JSONObject obj = new JSONObject(); JSONArray array = JSONArray.fromObject(roleResJson); List<RoleResBean> roleResList = (List<RoleResBean> )JSONArray.toCollection(array,RoleResBean.class); obj.element("status",roleResService.assignResource(roleResList,delIds)); return obj; } @RequestMapping("/getSelRes/{roleId}") @ResponseBody public List<RoleResBean> getSelRes(@PathVariable String roleId) { return roleResService.getListByRoleId(roleId); } }
UTF-8
Java
4,921
java
RoleController.java
Java
[]
null
[]
package com.jingyou.jybase.web.controller.sys; import com.jingyou.jybase.framework.annotation.AuditLog; import com.jingyou.jybase.framework.annotation.LogType; import com.jingyou.jybase.framework.core.bean.sys.RoleBean; import com.jingyou.jybase.framework.core.bean.sys.RoleResBean; import com.jingyou.jybase.framework.core.bean.sys.UserBean; import com.jingyou.jybase.framework.core.tree.PermissionTree; import com.jingyou.jybase.framework.hibernate.query.Page; import com.jingyou.jybase.framework.hibernate.query.Conditions; import com.jingyou.jybase.service.sys.RoleResService; import com.jingyou.jybase.service.sys.RoleService; import com.jingyou.jybase.web.controller.base.BaseController; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by Administrator on 2016/5/12. */ @Controller @RequestMapping(value = "/role") @AuditLog(log="角色管理",type = LogType.操作) public class RoleController extends BaseController { @Autowired private RoleService roleService; @Autowired private RoleResService roleResService; @RequestMapping("/index") public String index() { return "sys/role/list"; } @RequestMapping("/list") @ResponseBody public Map<String, Object> getRoleList(Conditions cond,Page page) { Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("rows", roleService.pageQuery(cond,page)); paramMap.put("total", page.getTotalCount()); return paramMap; } @RequestMapping("/listall") @ResponseBody public List<RoleBean> getParamAllList() { return roleService.findAll(); } @RequestMapping("/save") @ResponseBody @AuditLog(log="新增角色",type = LogType.操作) public JSONObject add(RoleBean role) { JSONObject obj = new JSONObject(); obj.element("status", roleService.save(role)); return obj; } @RequestMapping("/del") @ResponseBody @AuditLog(log="删除角色",type = LogType.操作) public JSONObject del(@RequestParam String[] ids) { JSONObject obj = new JSONObject(); for(String id : ids){ RoleBean temp = roleService.findByPK(id); if(temp.getType().equals("系统角色")){ obj.element("status",false); obj.element("msg","系统角色不能删除!"); return obj; } List<UserBean> users = roleService.getUsers(id); if(users != null && users.size() > 0){ obj.element("status",false); obj.element("msg","角色已赋予给用户,删除失败!"); return obj; } } obj.element("status", roleService.deleteByIds(ids)); return obj; } @RequestMapping("/toEdit/{id}") public String toEdit(Model model, @PathVariable String id) { RoleBean role = roleService.findByPK(id); model.addAttribute("role", role); return "sys//role/edit"; } @RequestMapping("/update") @ResponseBody @AuditLog(log="编辑角色",type = LogType.操作) public JSONObject update(RoleBean role) { JSONObject obj = new JSONObject(); obj.element("status", roleService.update(role)); return obj; } @RequestMapping("/check") @ResponseBody public JSONObject check(@RequestParam String value){ JSONObject obj = new JSONObject(); obj.element("status",roleService.check(value)); return obj; } @RequestMapping("/perssiontree") @ResponseBody public List<PermissionTree> resourceTree(){ PermissionTree root = roleService.getRootNode(); return root.getChildren(); } @RequestMapping("/assignres") @ResponseBody @AuditLog(log="角色分配资源",type = LogType.操作) public JSONObject assignResource(@RequestParam String roleResJson,@RequestParam String[] delIds){ JSONObject obj = new JSONObject(); JSONArray array = JSONArray.fromObject(roleResJson); List<RoleResBean> roleResList = (List<RoleResBean> )JSONArray.toCollection(array,RoleResBean.class); obj.element("status",roleResService.assignResource(roleResList,delIds)); return obj; } @RequestMapping("/getSelRes/{roleId}") @ResponseBody public List<RoleResBean> getSelRes(@PathVariable String roleId) { return roleResService.getListByRoleId(roleId); } }
4,921
0.683302
0.681639
139
33.597122
22.890015
108
false
false
0
0
0
0
0
0
0.647482
false
false
14
67615e1b77bae245d08258165adda3f00c211a40
31,860,067,413,024
cab4e5746951b32f354e2227150846f0960ba0aa
/ruoyi-media-dev/ruoyi-media-dev/ruoyi-system/src/main/java/com/ruoyi/media/domain/Actor.java
b21381f33d427c87ea0755455ce143fffbfc4b81
[ "MIT" ]
permissive
bellmit/shiping
https://github.com/bellmit/shiping
150d8dbe91c0e84e9cfd156348893ee5705ff333
3159cb828362d8565896b30a7caa41624e201d10
refs/heads/master
2023-07-19T11:21:18.358000
2021-09-08T16:50:47
2021-09-08T16:50:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ruoyi.media.domain; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.core.domain.BaseEntity; /** * 演员对象 wm_actor * * @author thh * @date 2021-05-16 */ @Data @TableName("wm_actor") public class Actor extends BaseEntity { /** 主键 */ @TableId(type = IdType.AUTO) private Long actorId; /** 姓名 */ @Excel(name = "姓名") private String name; /** 头像 */ @Excel(name = "头像") private String avatar; /** 简述 */ @Excel(name = "简述") private String description; /** 奖项 */ @Excel(name = "奖项") private String awards; /** 标签 */ @Excel(name = "标签 ") private String label; }
UTF-8
Java
1,008
java
Actor.java
Java
[ { "context": "in.BaseEntity;\n\n/**\n * 演员对象 wm_actor\n *\n * @author thh\n * @date 2021-05-16\n */\n@Data\n@TableName(\"wm_acto", "end": 451, "score": 0.9996324777603149, "start": 448, "tag": "USERNAME", "value": "thh" } ]
null
[]
package com.ruoyi.media.domain; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.core.domain.BaseEntity; /** * 演员对象 wm_actor * * @author thh * @date 2021-05-16 */ @Data @TableName("wm_actor") public class Actor extends BaseEntity { /** 主键 */ @TableId(type = IdType.AUTO) private Long actorId; /** 姓名 */ @Excel(name = "姓名") private String name; /** 头像 */ @Excel(name = "头像") private String avatar; /** 简述 */ @Excel(name = "简述") private String description; /** 奖项 */ @Excel(name = "奖项") private String awards; /** 标签 */ @Excel(name = "标签 ") private String label; }
1,008
0.666318
0.655858
47
19.340425
16.761501
56
false
false
0
0
0
0
0
0
0.319149
false
false
14
3be365854629b09596320424ac98070bdbb4def3
32,057,635,907,782
62351ccc14f206e016fc75674b66c81f5658151a
/ILife/src/lin/kreb/ilife/AppApplication.java
4bedd898cc35b36860802436afcbbd295b1a7226
[]
no_license
LindenKrebs/ILife
https://github.com/LindenKrebs/ILife
26a6dae1920271ce96bf4fc6c44c632ca63c3a1c
a6110e3d798071ae4daa8e972eaf617b327ff4b7
refs/heads/master
2016-09-15T17:49:47.557000
2013-11-18T09:02:06
2013-11-18T09:02:06
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lin.kreb.ilife; import java.util.List; import lin.kreb.modle.CitiesModle; import lin.kreb.modle.ConditionItem; import android.app.Application; public class AppApplication extends Application{ List<CitiesModle> citiesModle = null; ConditionItem conditionItem = null; public List<CitiesModle> getCitiesModle() { return citiesModle; } public void setCitiesModle(List<CitiesModle> citiesModle2) { this.citiesModle = citiesModle2; } public ConditionItem getConditionItem() { return conditionItem; } public void setConditionItem(ConditionItem conditionItem) { this.conditionItem = conditionItem; } }
UTF-8
Java
653
java
AppApplication.java
Java
[]
null
[]
package lin.kreb.ilife; import java.util.List; import lin.kreb.modle.CitiesModle; import lin.kreb.modle.ConditionItem; import android.app.Application; public class AppApplication extends Application{ List<CitiesModle> citiesModle = null; ConditionItem conditionItem = null; public List<CitiesModle> getCitiesModle() { return citiesModle; } public void setCitiesModle(List<CitiesModle> citiesModle2) { this.citiesModle = citiesModle2; } public ConditionItem getConditionItem() { return conditionItem; } public void setConditionItem(ConditionItem conditionItem) { this.conditionItem = conditionItem; } }
653
0.754977
0.751914
26
23.115385
19.791853
61
false
false
0
0
0
0
0
0
1.153846
false
false
14
1399bd8e25f3c4e63eee1dbe129f4f1f71a1fe36
33,526,514,722,373
ca019cd787714c2999689d45ef8e1bb8ab271277
/src/main/java/com/trinhquycong/service/UserService.java
f9090b307af7e1abe6b75213b91bd7c90b891fee
[]
no_license
Congtrinhh/shoes-store-spring-boot
https://github.com/Congtrinhh/shoes-store-spring-boot
6a0981e9ba65fa33fe0c9f533c27c1809a841199
3b6aea9f1465c939d720ae670fda490c7d2d19fa
refs/heads/master
2023-08-28T03:29:06.351000
2021-11-01T12:52:48
2021-11-01T12:52:48
422,140,118
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.trinhquycong.service; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.PersistenceException; import javax.servlet.http.HttpServletRequest; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import com.trinhquycong.component.Utilities; import com.trinhquycong.dto.UserSearchModel; import com.trinhquycong.entity.District; import com.trinhquycong.entity.Province; import com.trinhquycong.entity.Role; import com.trinhquycong.entity.User; import com.trinhquycong.entity.Ward; @Service public class UserService extends BaseService<User> { @Autowired private CheckoutService checkoutService; @Override protected Class<User> clazz() { return User.class; } /** * dang nhap * @param userName * @return */ public User loadUserByUsername(String userName) throws UsernameNotFoundException { String sql = "select * from user u where u.username = '" + userName + "'"; List<User> users = this.runTransactQuerySQL(sql, 0, null).getData(); if(users == null || users.size() <= 0) { throw new UsernameNotFoundException("Tên tài khoản hoặc mật khẩu không chính xác"); } User user = users.get(0); if (user.getStatus()==false) { throw new UsernameNotFoundException("Tài khoản chưa được kích hoạt"); } return user; } /** * đăng ký */ public String getEncodedPassword(String plainPassword) { return new BCryptPasswordEncoder(10).encode(plainPassword); } @Transactional public User updateUser(User user, HttpServletRequest request) throws PersistenceException { User userFromDB = this.getById(user.getId()); // handle address if (wantToChangeAddress(request)) { String specificAddress = request.getParameter("specific-address"); Integer wardId = Utilities.parseInteger(request.getParameter("ward")); Ward ward = checkoutService.getWardById(wardId); District district = checkoutService.getDistrictById(ward.getDistrictId()); Province province= checkoutService.getProvinceById(ward.getProvinceId()); String finalAddress = specificAddress + ", " + ward.getName() + ", " + district.getName() + ", " + province.getName(); user.setAddress(finalAddress); } else { user.setAddress(userFromDB.getAddress()); } // handle password if (wantToChangePassword(request)) { String currentPassword = request.getParameter("current-password"); String newPassword = request.getParameter("new-password"); BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder(10); String hashedPassword = userFromDB.getPassword(); // password nhập từ bàn phím có giống trong DB boolean match = bcrypt.matches(currentPassword, hashedPassword); if (match) { String newHashedPassword = bcrypt.encode(newPassword); user.setPassword(newHashedPassword); } else { user.setPassword(userFromDB.getPassword()); request.setAttribute("errorMessage", "Mật khẩu cũ không chính xác"); } } else { user.setPassword(userFromDB.getPassword()); } user.setRoles(userFromDB.getRoles()); user.setCreatedDate(userFromDB.getCreatedDate()); user.setUpdatedDate(new Date()); user.setStatus(userFromDB.getStatus()); return this.saveOrUpdate(user); } @Transactional public User createUser(User user, Role userRole) throws PersistenceException { String hashedPassword = this.getEncodedPassword(user.getPassword()); user.setPassword(hashedPassword); user.setCreatedDate(new Date()); user.addRole(userRole); return this.saveOrUpdate(user); } @Transactional public User updateUserForAdmin(User user, Role role) throws PersistenceException { User userFromDB = this.getById(user.getId()); // khởi tạo encoder BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder(10); // băm password và set String newHashedPassword = bcrypt.encode(user.getPassword()); user.setPassword(newHashedPassword); // vì có khả năng tham số role là null if (role!=null) { java.util.Set<Role> roles = new HashSet<>(); roles.add(role); user.setRoles(roles); } else { user.setRoles(userFromDB.getRoles()); } user.setCreatedDate(userFromDB.getCreatedDate()); user.setUpdatedDate(new Date()); return this.saveOrUpdate(user); } /** * ----------------SEARCH---------------- * @param searchModel * @return */ public PagerData<User> search(UserSearchModel searchModel){ // vì ta cần lấy cả dữ liệu từ bảng ROLE VÀ USER_ROLE String sql = "select * from user u join user_role ur on u.id=ur.user_id join role r on r.id=ur.role_id where 1=1"; if (searchModel != null) { // theo username if (searchModel.getUsername()!=null) { sql += " and u.username like '%" + searchModel.getUsername() + "%'"; } // theo email if (searchModel.getEmail()!=null) { sql += " and u.email like '%" + searchModel.getEmail()+ "%'"; } // tìm theo role: admin/manager/customer if (Utilities.notEmptyString(searchModel.getRoleName())) { sql += " and r.name='" + searchModel.getRoleName() + "'"; } // theo status if (searchModel.getStatus()!=null) { if(searchModel.getStatus().equals(true)) { sql += " and u.status=true"; }else { sql += " and u.status=false"; } } } return runTransactQuerySQL(sql, searchModel == null ? 0 : searchModel.getPage(), searchModel == null ? null : searchModel.getSop()); } public boolean wantToChangeAddress(HttpServletRequest request) { String specificAddress = request.getParameter("specific-address"); String wardIdStr = request.getParameter("ward"); if ( (wardIdStr!=null && wardIdStr.length()>0) && (specificAddress!=null && specificAddress.length()>0) ) { return true; } return false; } public boolean wantToChangePassword(HttpServletRequest request) { String currentPassword = request.getParameter("current-password"); String newPassword = request.getParameter("new-password"); String newPasswordConfirm = request.getParameter("confirmed-password"); if (currentPassword==null || currentPassword.length()==0) { return false; } if (newPassword==null || newPassword.length()==0) { return false; } if (newPasswordConfirm==null || newPasswordConfirm.length()==0) { return false; } return true; } @Transactional public void deactivateById(Integer id) { User user = super.getById(id); user.setStatus(false); super.saveOrUpdate(user); } public Role getFirstRole(Set<Role> roles) { Role role = null; for (Role r : roles) { role = r; break; } return role; } /** * CRUD manager */ }
UTF-8
Java
6,994
java
UserService.java
Java
[ { "context": "yptPasswordEncoder(10);\n\t\t\tString hashedPassword = userFromDB.getPassword();\n\t\t\t// password nhập từ bàn phím có giống trong", "end": 2858, "score": 0.98542720079422, "start": 2836, "tag": "PASSWORD", "value": "userFromDB.getPassword" }, { "context": "t.encode(newPassword);\n\t\t\t\tuser.setPassword(newHashedPassword);\n\t\t\t} else {\n\t\t\t\tuser.setPassword(userFromDB.get", "end": 3097, "score": 0.734632134437561, "start": 3086, "tag": "PASSWORD", "value": "hedPassword" }, { "context": "HashedPassword);\n\t\t\t} else {\n\t\t\t\tuser.setPassword(userFromDB.getPassword());\n\t\t\t\trequest.setAttribute(\"errorMessage\", \"Mật", "end": 3155, "score": 0.936224102973938, "start": 3133, "tag": "PASSWORD", "value": "userFromDB.getPassword" }, { "context": "\");\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tuser.setPassword(userFromDB.getPassword());\n\t\t}\n\t\t\n\t\tuser.setRoles(userFromDB.getRoles())", "end": 3293, "score": 0.6024165749549866, "start": 3279, "tag": "PASSWORD", "value": "DB.getPassword" }, { "context": "s PersistenceException {\n\t\tString hashedPassword = this.getEncodedPassword(user.getPassword());\n\t\t\n\t\tuser", "end": 3646, "score": 0.6546467542648315, "start": 3642, "tag": "PASSWORD", "value": "this" }, { "context": "ssword(user.getPassword());\n\t\t\n\t\tuser.setPassword(hashedPassword);\n\t\tuser.setCreatedDate(new Date());\n\t\tuser.addRo", "end": 3723, "score": 0.7645488977432251, "start": 3709, "tag": "PASSWORD", "value": "hashedPassword" } ]
null
[]
package com.trinhquycong.service; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.PersistenceException; import javax.servlet.http.HttpServletRequest; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import com.trinhquycong.component.Utilities; import com.trinhquycong.dto.UserSearchModel; import com.trinhquycong.entity.District; import com.trinhquycong.entity.Province; import com.trinhquycong.entity.Role; import com.trinhquycong.entity.User; import com.trinhquycong.entity.Ward; @Service public class UserService extends BaseService<User> { @Autowired private CheckoutService checkoutService; @Override protected Class<User> clazz() { return User.class; } /** * dang nhap * @param userName * @return */ public User loadUserByUsername(String userName) throws UsernameNotFoundException { String sql = "select * from user u where u.username = '" + userName + "'"; List<User> users = this.runTransactQuerySQL(sql, 0, null).getData(); if(users == null || users.size() <= 0) { throw new UsernameNotFoundException("Tên tài khoản hoặc mật khẩu không chính xác"); } User user = users.get(0); if (user.getStatus()==false) { throw new UsernameNotFoundException("Tài khoản chưa được kích hoạt"); } return user; } /** * đăng ký */ public String getEncodedPassword(String plainPassword) { return new BCryptPasswordEncoder(10).encode(plainPassword); } @Transactional public User updateUser(User user, HttpServletRequest request) throws PersistenceException { User userFromDB = this.getById(user.getId()); // handle address if (wantToChangeAddress(request)) { String specificAddress = request.getParameter("specific-address"); Integer wardId = Utilities.parseInteger(request.getParameter("ward")); Ward ward = checkoutService.getWardById(wardId); District district = checkoutService.getDistrictById(ward.getDistrictId()); Province province= checkoutService.getProvinceById(ward.getProvinceId()); String finalAddress = specificAddress + ", " + ward.getName() + ", " + district.getName() + ", " + province.getName(); user.setAddress(finalAddress); } else { user.setAddress(userFromDB.getAddress()); } // handle password if (wantToChangePassword(request)) { String currentPassword = request.getParameter("current-password"); String newPassword = request.getParameter("new-password"); BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder(10); String hashedPassword = <PASSWORD>(); // password nhập từ bàn phím có giống trong DB boolean match = bcrypt.matches(currentPassword, hashedPassword); if (match) { String newHashedPassword = bcrypt.encode(newPassword); user.setPassword(newHas<PASSWORD>); } else { user.setPassword(<PASSWORD>()); request.setAttribute("errorMessage", "Mật khẩu cũ không chính xác"); } } else { user.setPassword(userFrom<PASSWORD>()); } user.setRoles(userFromDB.getRoles()); user.setCreatedDate(userFromDB.getCreatedDate()); user.setUpdatedDate(new Date()); user.setStatus(userFromDB.getStatus()); return this.saveOrUpdate(user); } @Transactional public User createUser(User user, Role userRole) throws PersistenceException { String hashedPassword = <PASSWORD>.getEncodedPassword(user.getPassword()); user.setPassword(<PASSWORD>); user.setCreatedDate(new Date()); user.addRole(userRole); return this.saveOrUpdate(user); } @Transactional public User updateUserForAdmin(User user, Role role) throws PersistenceException { User userFromDB = this.getById(user.getId()); // khởi tạo encoder BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder(10); // băm password và set String newHashedPassword = bcrypt.encode(user.getPassword()); user.setPassword(newHashedPassword); // vì có khả năng tham số role là null if (role!=null) { java.util.Set<Role> roles = new HashSet<>(); roles.add(role); user.setRoles(roles); } else { user.setRoles(userFromDB.getRoles()); } user.setCreatedDate(userFromDB.getCreatedDate()); user.setUpdatedDate(new Date()); return this.saveOrUpdate(user); } /** * ----------------SEARCH---------------- * @param searchModel * @return */ public PagerData<User> search(UserSearchModel searchModel){ // vì ta cần lấy cả dữ liệu từ bảng ROLE VÀ USER_ROLE String sql = "select * from user u join user_role ur on u.id=ur.user_id join role r on r.id=ur.role_id where 1=1"; if (searchModel != null) { // theo username if (searchModel.getUsername()!=null) { sql += " and u.username like '%" + searchModel.getUsername() + "%'"; } // theo email if (searchModel.getEmail()!=null) { sql += " and u.email like '%" + searchModel.getEmail()+ "%'"; } // tìm theo role: admin/manager/customer if (Utilities.notEmptyString(searchModel.getRoleName())) { sql += " and r.name='" + searchModel.getRoleName() + "'"; } // theo status if (searchModel.getStatus()!=null) { if(searchModel.getStatus().equals(true)) { sql += " and u.status=true"; }else { sql += " and u.status=false"; } } } return runTransactQuerySQL(sql, searchModel == null ? 0 : searchModel.getPage(), searchModel == null ? null : searchModel.getSop()); } public boolean wantToChangeAddress(HttpServletRequest request) { String specificAddress = request.getParameter("specific-address"); String wardIdStr = request.getParameter("ward"); if ( (wardIdStr!=null && wardIdStr.length()>0) && (specificAddress!=null && specificAddress.length()>0) ) { return true; } return false; } public boolean wantToChangePassword(HttpServletRequest request) { String currentPassword = request.getParameter("current-password"); String newPassword = request.getParameter("new-password"); String newPasswordConfirm = request.getParameter("confirmed-password"); if (currentPassword==null || currentPassword.length()==0) { return false; } if (newPassword==null || newPassword.length()==0) { return false; } if (newPasswordConfirm==null || newPasswordConfirm.length()==0) { return false; } return true; } @Transactional public void deactivateById(Integer id) { User user = super.getById(id); user.setStatus(false); super.saveOrUpdate(user); } public Role getFirstRole(Set<Role> roles) { Role role = null; for (Role r : roles) { role = r; break; } return role; } /** * CRUD manager */ }
6,967
0.703425
0.700968
251
26.565737
26.816156
121
false
false
0
0
0
0
0
0
2.286853
false
false
14
79aa7f4b749c9d91811e59707f94a78c7257acc7
20,289,425,522,659
9049eabb2562cd3e854781dea6bd0a5e395812d3
/sources/com/google/android/gms/ads/cache/policy/C0223f.java
c173f66f2a2d71c893c156fbc2dd025264922550
[]
no_license
Romern/gms_decompiled
https://github.com/Romern/gms_decompiled
4c75449feab97321da23ecbaac054c2303150076
a9c245404f65b8af456b7b3440f48d49313600ba
refs/heads/master
2022-07-17T23:22:00.441000
2020-05-17T18:26:16
2020-05-17T18:26:16
264,227,100
2
5
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.google.android.gms.ads.cache.policy; import com.google.android.gms.ads.cache.C0201g; import com.google.android.gms.ads.cache.C0217p; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /* renamed from: com.google.android.gms.ads.cache.policy.f */ /* compiled from: :com.google.android.gms@201515033@20.15.15 (120300-306758586) */ public final class C0223f { /* renamed from: a */ public final Set f7923a; public C0223f(Set set) { this.f7923a = set; } /* renamed from: a */ public static Map m5088a(List list) { C1223np npVar = new C1223np(); if (list != null) { Iterator it = list.iterator(); while (it.hasNext()) { C0217p pVar = (C0217p) it.next(); npVar.put(new C0201g(pVar).f7853a, pVar); } } return npVar; } }
UTF-8
Java
909
java
C0223f.java
Java
[]
null
[]
package com.google.android.gms.ads.cache.policy; import com.google.android.gms.ads.cache.C0201g; import com.google.android.gms.ads.cache.C0217p; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /* renamed from: com.google.android.gms.ads.cache.policy.f */ /* compiled from: :com.google.android.gms@201515033@20.15.15 (120300-306758586) */ public final class C0223f { /* renamed from: a */ public final Set f7923a; public C0223f(Set set) { this.f7923a = set; } /* renamed from: a */ public static Map m5088a(List list) { C1223np npVar = new C1223np(); if (list != null) { Iterator it = list.iterator(); while (it.hasNext()) { C0217p pVar = (C0217p) it.next(); npVar.put(new C0201g(pVar).f7853a, pVar); } } return npVar; } }
909
0.611661
0.521452
33
26.545454
20.108932
82
true
false
0
0
0
0
0
0
0.454545
false
false
14
44deebd86a84a81c1b7216c9f9fc4a435dbbcf4a
13,726,715,498,201
8e8ecc3abf0a832ddace24404f08aa212bdec1c2
/core/core/src/main/java/org/visallo/core/util/LoggingThread.java
cc914a71337e043d17ce6218714757ae8f14f40a
[ "Apache-2.0" ]
permissive
YANG-DB/visallo-2
https://github.com/YANG-DB/visallo-2
0008b689294aadb2bd6b1886a41f52b9cfc9e9c2
3b1831d0889d8ce82474d862b26a98f67e8f5b06
refs/heads/master
2021-05-26T04:17:22.789000
2020-05-21T21:04:23
2020-05-21T21:04:23
254,049,378
1
0
Apache-2.0
true
2020-04-08T09:55:27
2020-04-08T09:55:26
2018-04-01T23:58:46
2018-03-08T02:26:32
13,002
0
0
0
null
false
false
package org.visallo.core.util; import java.io.*; import static org.vertexium.util.CloseableUtils.closeQuietly; /** * This class is designed to log {@link Process} output on a thread. */ public class LoggingThread extends Thread { private InputStream inputStream; private OutputStream outputStream; private StringBuffer contentBuffer; private String prefix; private PrintWriter writer; private VisalloLogger logger; public LoggingThread(InputStream inputStream, VisalloLogger logger, String prefix) { this(inputStream, null, logger, null, prefix); } /** * Creates a new stream helper and immediately starts capturing output from * the given stream. Output will be captured to the given buffer and also * redirected to the provided output stream. * * @param inputStream the input stream to read from * @param redirect a stream to also redirect the captured output to * @param logger the logger to append to * @param contentBuffer the buffer to write the captured output to */ public LoggingThread(InputStream inputStream, OutputStream redirect, VisalloLogger logger, StringBuffer contentBuffer, String prefix) { this.inputStream = inputStream; this.outputStream = redirect; this.logger = logger; this.contentBuffer = contentBuffer; this.prefix = prefix; } @Override public void run() { BufferedReader reader = null; InputStreamReader isreader = null; try { if (outputStream != null) { writer = new PrintWriter(outputStream); } isreader = new InputStreamReader(inputStream); reader = new BufferedReader(isreader); String line; while ((line = reader.readLine()) != null) { if (prefix != null) { line = prefix + line; } append(line); log(line); } if (writer != null) writer.flush(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { closeQuietly(reader); closeQuietly(isreader); closeQuietly(writer); } } /** * This method will write any output from the stream to the the content buffer * and the logger. * * @param output the stream output */ protected void append(String output) { // Process stream redirects if (writer != null) { writer.println(output); } // Fill the content buffer, if one has been assigned if (contentBuffer != null) { contentBuffer.append(output.trim()); contentBuffer.append('\n'); } // Append output to logger? } /** * If a logger has been specified, the output is written to the logger using * the defined log level. * * @param output the stream output */ protected void log(String output) { if (logger != null) { logger.info("%s", output); } } }
UTF-8
Java
3,285
java
LoggingThread.java
Java
[]
null
[]
package org.visallo.core.util; import java.io.*; import static org.vertexium.util.CloseableUtils.closeQuietly; /** * This class is designed to log {@link Process} output on a thread. */ public class LoggingThread extends Thread { private InputStream inputStream; private OutputStream outputStream; private StringBuffer contentBuffer; private String prefix; private PrintWriter writer; private VisalloLogger logger; public LoggingThread(InputStream inputStream, VisalloLogger logger, String prefix) { this(inputStream, null, logger, null, prefix); } /** * Creates a new stream helper and immediately starts capturing output from * the given stream. Output will be captured to the given buffer and also * redirected to the provided output stream. * * @param inputStream the input stream to read from * @param redirect a stream to also redirect the captured output to * @param logger the logger to append to * @param contentBuffer the buffer to write the captured output to */ public LoggingThread(InputStream inputStream, OutputStream redirect, VisalloLogger logger, StringBuffer contentBuffer, String prefix) { this.inputStream = inputStream; this.outputStream = redirect; this.logger = logger; this.contentBuffer = contentBuffer; this.prefix = prefix; } @Override public void run() { BufferedReader reader = null; InputStreamReader isreader = null; try { if (outputStream != null) { writer = new PrintWriter(outputStream); } isreader = new InputStreamReader(inputStream); reader = new BufferedReader(isreader); String line; while ((line = reader.readLine()) != null) { if (prefix != null) { line = prefix + line; } append(line); log(line); } if (writer != null) writer.flush(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { closeQuietly(reader); closeQuietly(isreader); closeQuietly(writer); } } /** * This method will write any output from the stream to the the content buffer * and the logger. * * @param output the stream output */ protected void append(String output) { // Process stream redirects if (writer != null) { writer.println(output); } // Fill the content buffer, if one has been assigned if (contentBuffer != null) { contentBuffer.append(output.trim()); contentBuffer.append('\n'); } // Append output to logger? } /** * If a logger has been specified, the output is written to the logger using * the defined log level. * * @param output the stream output */ protected void log(String output) { if (logger != null) { logger.info("%s", output); } } }
3,285
0.571385
0.571385
102
30.205883
23.273455
91
false
false
0
0
0
0
0
0
0.45098
false
false
14
dbb082bf7294a228949220052322c2dabfd427cc
32,392,643,369,303
9ab7d77fa84381497a0a4b9caa4b6570ce0f5b14
/engage-cs/oogt/src/edu/lhup/ai/tictactoe/EmptyPiece.java
f0ddb50e25eee090083210ce71aafe7ed0b21ae2
[]
no_license
tringuyenvn94/engage-cs
https://github.com/tringuyenvn94/engage-cs
cf7fa59c63b2f27dbe9d6c8db897ebaaadf445dd
d41c64f766347118024bc0e3c52070c83076af7d
refs/heads/master
2016-08-05T19:21:29.164000
2010-11-10T16:39:42
2010-11-10T16:39:42
34,009,898
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.lhup.ai.tictactoe; import edu.lhup.ai.*; /** * Represents a location on the {@link Board tic-tac-toe} board that contains * no piece at all. * * <p> * This software is for educational purposes only. * @author Mark Cohen */ class EmptyPiece implements IPiece { EmptyPiece() {} public String toString() { return "."; } }
UTF-8
Java
384
java
EmptyPiece.java
Java
[ { "context": "ware is for educational purposes only.\r\n * @author Mark Cohen \r\n */\r\nclass EmptyPiece implements IPiece\r\n{\r\n\tEm", "end": 260, "score": 0.9997820854187012, "start": 250, "tag": "NAME", "value": "Mark Cohen" } ]
null
[]
package edu.lhup.ai.tictactoe; import edu.lhup.ai.*; /** * Represents a location on the {@link Board tic-tac-toe} board that contains * no piece at all. * * <p> * This software is for educational purposes only. * @author <NAME> */ class EmptyPiece implements IPiece { EmptyPiece() {} public String toString() { return "."; } }
380
0.609375
0.609375
21
16.285715
19.056665
78
false
false
0
0
0
0
0
0
0.857143
false
false
14
873c021374619f07920432064aa6adc9df11e0e0
1,288,490,210,256
351c8ca0700eb024b109883072015716738dbffe
/src/atnf/atoms/util/Angle.java
330d30ca335e2cba24a3be721004adb8452506fe
[]
no_license
davidbrodrick/open-monica
https://github.com/davidbrodrick/open-monica
f222dbea82827fe7e0cc8650e0785577a746745d
cd738bf16013b5daee6f2088c4ef8fcef1ff5a66
refs/heads/master
2021-07-02T23:35:46.343000
2021-05-21T07:06:51
2021-05-21T07:06:51
34,646,195
6
9
null
false
2016-07-26T02:12:28
2015-04-27T04:36:48
2016-07-08T11:07:21
2016-07-26T02:12:28
21,638
1
3
7
Java
null
null
// Copyright (C)1997 CSIRO Australia Telescope National Facility // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This library 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 Library General Public License for more details. // // A copy of the GNU Library General Public License is available at: // http://wwwatoms.atnf.csiro.au/doc/gnu/GLGPL.htm // or, write to the Free Software Foundation, Inc., 59 Temple Place, // Suite 330, Boston, MA 02111-1307 USA package atnf.atoms.util; import java.io.*; import java.text.*; /** * Class representing an angle. * * <p>The string representation for an <code>Angle</code> object is * represented by an object of type <code>Angle.Format</code>. * When reading these strings, * it is possible to automatically distinguish * between these formats and obtain the correct internal value.</p> * * <p>Objects of this class are immutable. * Whenever an operation is requested on an object, * a new object with the result is returned and the original object * is not changed.</p> * * @author David G Loone * * @version $Id: Angle.java,v 1.39 2005/07/08 04:47:09 bro764 Exp $ * * @see AngleDisplay */ public class Angle implements Cloneable, Immutable, Serializable { /** * The RCS id. */ final public static String RCSID = "$Id: Angle.java,v 1.39 2005/07/08 04:47:09 bro764 Exp $"; /** * Serialised version id. */ static final long serialVersionUID = -2309745966047874429L; /** * The hours format. */ final private static NumberFormat theirHrFmt = new DecimalFormat("00"); /** * The minutes format. */ final private static NumberFormat theirMinFmt = new DecimalFormat("00"); /** * The seconds format. */ final private static NumberFormat theirSecFmt = new DecimalFormat("00"); /** * String formats. * * Objects of this class represent the different string formats * that an <code>Angle</code> value can take. */ final public static class Format extends Enum { /** * Represents the ordinal value of <code>DMS</code>. */ final public static int DMS_ORD = 1; /** * Indicates degrees/minutes/seconds using UNICODE characters. * This form always specifies degrees, minutes and seconds * components. * The degrees field is a signed integer, followed by a \u00B0. * The minutes field is an unsigned integer, * followed by a '. * The seconds field is a unsigned integer, * followed by a ". * This is optionally follwed by a decimal fractional part of the * seconds. * The minutes field and the integer component of the seconds field * are always two characters wide, * with leading zeros where necessary. * Example formats are: * <ul> * <li>XX\u00B0X'XX"</li> * <li>-XX\u00B0XX'XX".XXX</li> * <li>+XX\u00B0X'XX".X</li> * </ul> */ final public static Format DMS = new Format(DMS_ORD,"DMS"); /** * Represents the ordinal value of <code>DMS_ASCII</code>. */ final public static int DMS_ASCII_ORD = 2; /** * Indicates degrees/minutes/seconds using only ASCII characters. * This form is very similar to <code>DEGREES</code> except that * the degree and minutes fields are seperated by * the '^' character. It is supplied for systems that do not * support UNICODE. On input the 'd' character is acceptable in place * of the '^' character. * Example formats are: * <ul> * <li>XX^XX'XX"</li> * <li>-XX^XX'XX".XXX</li> * <li>+XX^XX'XX".X</li> * </ul> */ final public static Format DMS_ASCII = new Format(DMS_ASCII_ORD,"DMS_ASCII"); /** * Represents the ordinal value of <code>DEGREES</code>. */ final public static int DEGREES_ORD = 3; /** * Indicates decimal degrees using UNICODE characters. * This is a signed floating number, * followed by a \u00B0 character. * Example formats are: * <ul> * <li>XX.XXXX\u00B0</li> * <li>-XX\u00B0</li> * </ul> */ final public static Format DEGREES = new Format(DEGREES_ORD,"DEGREES"); /** * Indicates the ordinal value of <code>HMS</code>. */ final public static int HMS_ORD = 4; /** * Indicates hours/minutes/seconds. * Each of the hours, minutes and seconds fields are * seperated by a colon. * The hours, minutes and the integer part of the seconds fields * are in a two character field, * filled with leading zeros if necessary. * Example formats are: * <ul> * <li>XX:XX:XX.X</li> * <li>-XX:XX:XX</li> * </ul> */ final public static Format HMS = new Format(HMS_ORD,"HMS"); /** * Indicates the ordinal value of <code>RADIANS</code>. */ final public static int RADIANS_ORD = 5; /** * Indicates radians (decimal). * This is a signed floating number. * Example formats include: * <ul> * <li>XX.XXXX</li> * <li>-XX</li> * </ul> */ final public static Format RADIANS = new Format(RADIANS_ORD,"RADIANS"); /** * The default format. */ final public static Format DEFAULT_FORMAT = DMS; /** * Default constructor to prevent instantiation by outsiders. */ private Format() { super(); } /** * Constructor. * * @param ord * The ordinal value of the format. * * @param message * The string message for the format. */ private Format( int ord, String message ) { super(ord,message); } } /** * The number of minutes in a degree. */ private static final double MINS_PER_DEG = 60.0; /** * The number of minutes in an hour. */ private static final double MINS_PER_HOUR = 60.0; /** * The number of seconds in a minute. */ private static final double SECS_PER_MIN = 60.0; /** * The number of degrees in a radian. */ private static final double DEGS_PER_RAD = 360.0 / (2.0 * Math.PI); /** * The number of radians in a degree. */ private static final double RADS_PER_DEG = (2.0 * Math.PI) / 360.0; /** * The number of hours in a radian. */ private static final double HOURS_PER_RAD = 24.0 / (2.0 * Math.PI); /** * The number of radians in an hour. */ private static final double RADS_PER_HOUR = (2.0 * Math.PI) / 24.0; /** * An angle of 0 degrees. */ public static final double A0 = 0.0; /** * An angle of 90 degrees. */ public static final double A90 = Math.PI / 2.0; /** * An angle of 180 degrees. */ public static final double A180 = Math.PI; /** * An angle of 270 degrees. */ public static final double A270 = Math.PI * 3.0 / 2.0; /** * An angle of 360 degrees. */ public static final double A360 = Math.PI * 2.0; /** * The current default output format. */ private static Format theirDefaultFormat = Format.DEFAULT_FORMAT; /** * The value of the angle (in radians). */ protected double itsValue; /** * Make a new object with a value of zero. */ public static Angle factory() { return new Angle(); } /** * Make a new object with a value of zero. */ public Angle() { // Set the value to zero. itsValue = 0; } /** * Make a new object from a double. * * @param value * The angle value (in radians). */ public static Angle factory( double value ) { return new Angle(value); } /** * Make a new object from a double. * * @param value * The angle value (in radians). */ private Angle( double value ) { // Set the value to that indicated. itsValue = value; } /** * Make a new object from a double in either radians or degrees. * * @param value * The angle value * (in units specified by <code>units</code>). * * @param units * The units of <code>value</code>. * This must be equal to either <code>DEGREES</code> * <code>RADIANS</code>. * * @exception IllegalArgumentException * Thrown when <code>units</code> is not equal to either * <code>DEGREES</code> or <code>RADIANS</code>. */ public static Angle factory( double value, Format units ) throws IllegalArgumentException { return new Angle(value,units); } /** * Make a new object from a double in either radians or degrees. * * @param value * The angle value * (in units specified by <code>units</code>). * * @param units * The units of <code>value</code>. * This must be equal to either <code>DEGREES</code> * <code>RADIANS</code>. * * @exception IllegalArgumentException * Thrown when <code>units</code> is not equal to either * <code>DEGREES</code> or <code>RADIANS</code>. */ private Angle( double value, Format units ) throws IllegalArgumentException { if(units.ord() == Format.DEGREES.ord()) { itsValue = value * RADS_PER_DEG; } else if(units.ord() == Format.RADIANS.ord()) { itsValue = value; } else { throw new IllegalArgumentException("bad format: " + units); } } /** * Make a new object from an existing * <code>Angle</code> object. * * @param a * Another <code>Angle</code> object to copy the value from. * Must not be <code>null</code>. */ public static Angle factory( Angle a ) { return new Angle(a); } /** * Make a new object from an existing * <code>Angle</code> object. * * @param a * Another <code>Angle</code> object to copy the value from. * Must not be <code>null</code>. */ private Angle( Angle a ) { // Set the value that indicated. itsValue = a.itsValue; } /** * Make a new object from a string representation. * * <p> * The string can be any one of the valid string representations of * an angle. * The particular format is automatically determined * and the string is parsed accordingly. * * <p> * The allowed formats are generalised somewhat from the formats * that are printed. * The following shows some valid combinations: * <blockquote> * <table cellpadding=4 border=1> * <tr> * <td align=center><font size=+1><code><b>-2.48</b></code></font></td> * <td>radians</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>3:5:27.32</b></code></font></td> * <td>hours/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>-3:5:27.32</b></code></font></td> * <td>hours/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>3:5:27</b></code></font></td> * <td>hours/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B02'34"</b></code></font></td> * <td>degrees/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B0</b></code></font></td> * <td>degrees</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B0.38</b></code></font></td> * <td>degrees</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B02'.38</b></code></font></td> * <td>degrees/minutes</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B02'45"</b></code></font></td> * <td>degrees/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>-48\u00B02'45".38</b></code></font></td> * <td>degrees/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>2'.38</b></code></font></td> * <td>minutes</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>2'45".38</b></code></td> * <td>minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>45"</b></code></td> * <td>seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>45".39</b></code></td> * <td>seconds</td> * </tr> * </table> * </blockquote> * * @param str * A <code>String</code> representation of an * <code>Angle</code> object. * Whitespace at the beginning or end of the string is ignored. * Must not be equal to <code>null</code>. * * @exception NumberFormatException * Thrown when a <code>String</code> is not a valid string * format of an angle. */ public static Angle factory( String str ) throws NumberFormatException { return new Angle(str); } /** * Make a new object from a string representation. * * <p> * The string can be any one of the valid string representations of * an angle. * The particular format is automatically determined * and the string is parsed accordingly. * * <p> * The allowed formats are generalised somewhat from the formats * that are printed. * The following shows some valid combinations: * <blockquote> * <table cellpadding=4 border=1> * <tr> * <td align=center><font size=+1><code><b>-2.48</b></code></font></td> * <td>radians</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>3:5:27.32</b></code></font></td> * <td>hours/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>-3:5:27.32</b></code></font></td> * <td>hours/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>3:5:27</b></code></font></td> * <td>hours/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B02'34"</b></code></font></td> * <td>degrees/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B0</b></code></font></td> * <td>degrees</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B0.38</b></code></font></td> * <td>degrees</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B02'.38</b></code></font></td> * <td>degrees/minutes</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B02'45"</b></code></font></td> * <td>degrees/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>-48\u00B02'45".38</b></code></font></td> * <td>degrees/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>2'.38</b></code></font></td> * <td>minutes</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>2'45".38</b></code></td> * <td>minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>45"</b></code></td> * <td>seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>45".39</b></code></td> * <td>seconds</td> * </tr> * </table> * </blockquote> * * @param str * A <code>String</code> representation of an * <code>Angle</code> object. * Whitespace at the beginning or end of the string is ignored. * Must not be equal to <code>null</code>. * * @exception NumberFormatException * Thrown when a <code>String</code> is not a valid string * format of an angle. */ private Angle( String str ) throws NumberFormatException { // If the string contains a 'd' characer, replace it with // '^' characters. if(str.indexOf("d") != -1) { // The chars of the string. char[] chars = str.toCharArray(); // Iterate over the char array. for(int i = 0; i < chars.length; i++) { if(chars[i] == 'd') { chars[i] = '^'; } } // Re-create the string. str = new String(chars); } parse(str); } /** * Clone the object. * * @return * A new object identical to this one. */ public Object clone() { // The class is immutable. Just return this. return this; } /** * Test for equivalence. * * @param o * The object to test for equivlence against. * * @return * Returns <code>true</code> if <code>o</code> is equivalent to * this object, * <code>false</code> otherwise. */ public boolean equiv( Object o ) { // The value to return. boolean isEquiv = false; // Local version of o. Angle o1; // Prerequisites. if((o != null) && (o.getClass() == getClass())) { o1 = (Angle)o; // Is equiv if same object. if(equals(o1)) { isEquiv = true; } else { // Test the attributes. isEquiv = (o1.itsValue == itsValue); } } return isEquiv; } /** * Set the default string format for the class. * * @param fmt * The new default string format for the class. */ public static void setTheirDefaultFormat( Format fmt ) { theirDefaultFormat = (Format)fmt.clone(); } /** * Get the default string format for the class. * * @return * The current default string format for the class. */ public static Format getTheirDefaultFormat() { return (Format)theirDefaultFormat.clone(); } /** * Test for proximity with another angle. * * @param a * The angle to test against. * Must not be equal to <code>null</code>. * * @param prox * The proximity to test for. * Must not be equal to <code>null</code>. * * @return * The value <code>true</code> if this angle is within * <code>prox</code> (on either side) of <code>a</code>. */ public boolean isNear( Angle a, Angle prox ) { // Test for prox < 0. if(prox.itsValue < 0) { throw new IllegalArgumentException("prox = " + prox); } return (Math.abs(itsValue - a.itsValue) <= prox.itsValue); } /** * Test for this angle less than another. * * @param a * The angle to test against. * Must not be equal to <code>null</code>. * * @return * The value <code>true</code> if this object * is less than <code>a</code>. */ public boolean isLT( Angle a ) { return (itsValue < a.itsValue); } /** * Test for this angle less than or equal to another. * * @param a * The angle to test against. * Must not be equal to <code>null</code>. * * @return * The value <code>true</code> if this object * is less than or equal to <code>a</code>. */ public boolean isLTE( Angle a ) { return (itsValue <= a.itsValue); } /** * Test for this angle greater than another. * * @param a * The angle to test against. * Must not be equal to <code>null</code>. * * @return * The value <code>true</code> if this object * is greater than <code>a</code>. */ public boolean isGT( Angle a ) { return (itsValue > a.itsValue); } /** * Test for this angle greater than or equal to another. * * @param a * The angle to test against. * Must not be equal to <code>null</code>. * * @return * The value <code>true</code> if this object * is greater than or equal to <code>a</code>. */ public boolean isGTE( Angle a ) { return (itsValue >= a.itsValue); } /** * Test for not-a-number. * * @return * Boolean <code>true</code> if this angle is not-a-number, * <code>false</code> otherwise. */ public boolean isNaN() { // Make a Double object, and call the NaN method. return (new Double(itsValue)).isNaN(); } /** * Test for infinity. * * @return * Boolean <code>true</code> if this angle is infinite, * <code>false</code> otherwise. */ public boolean isInfinite() { // Make a Double object, and call the isInfinite method. return (new Double(itsValue)).isInfinite(); } /** * Returns the value of this angle. * * @return * A double value. */ public double getValue() { // Return the value of this angle. return itsValue; } /** * Returns the value of this angle in degrees. * * @return * A double value (in degrees). */ public double getValueDeg() { // Return the value of this angle in degrees. return (itsValue * DEGS_PER_RAD); } /** * Returns a string representation of this angle in the default * string format and with the default and with one decimal place. * * @return * A <code>String</code> object of this Angle. */ public String toString() { return toString(getTheirDefaultFormat(),1); } /** * Returns a string representation of this angle in the default * format with the given number of decimal places. * * @param digits * The number of decimal places in the string. * Must not be less than zero. */ public String toString( int digits ) { return toString(getTheirDefaultFormat(),digits); } /** * Returns a string representation of this angle in any given * string format and one decimal place. * * @param format * Detemrines which string format will be generated. * A value of <code>null</code> indicates the default format. * * @return * A <code>String</code> object of this Angle. */ public String toString( Format format ) { if(format == null) { format = getTheirDefaultFormat(); } return toString(format,1); } /** * Returns a string representation of this angle in any given * string format, and to an indicated number of digits. * * @param format * Determines which string representation will be generated. * A value of <code>null</code> indicates the default format. * * @param digits * The number of siginificant digits. * The application of this parameter varies slightly with the * string format requested. * It will apply to whichever field is a floating point number. * In the case of <code>DMS</code>, * <code>DMS_ASCII</code> and <code>HMS</code>, * it will apply to the seconds field. * In the case of <code>DEGREES</code> and <code>RADIANS</code>, * it will apply to the degrees and radians fields respectively * (the only numerical field in the number). * Must not be less than zero. * * @return * A <code>String</code> object representing this angle, * formatted according to <code>format</code>. */ public String toString( Format format, int digits ) { // The string to build the result into. String res = null; // The value in its object wrapper. Double itsValueObj = new Double(itsValue); if(format == null) { format = getTheirDefaultFormat(); } // Need to check for the value -0.0, since this is not changed // by the Math.abs function. if(itsValueObj.toString().equals("-0.0")) { itsValue = -itsValue; } // Check for some special cases. if(itsValueObj.isNaN()) { res = new String("NaN"); } else if(itsValueObj.isInfinite()) { res = new String("Infinity"); } else { // Build a result according to the format requested. switch(format.ord()) { case Format.DMS_ORD: res = toStringDMS(digits,'\u00B0'); break; case Format.DMS_ASCII_ORD: res = toStringDMS(digits,'^'); break; case Format.HMS_ORD: res = toStringHMS(digits); break; case Format.DEGREES_ORD: // Make the string. res = toStringDegrees(digits); break; case Format.RADIANS_ORD: res = toStringRadians(digits); break; default: assert false; break; } } return res; } /** * Negate the value of this angle. * The result is returned in a new object. * * @return * A reference to the new object. */ public Angle negate() { return new Angle(-itsValue); } /** * Add a value to this angle. * The result is returned in a new object. * * @param valInc * The value to add to this angle. * * @return * A reference to the new object. */ public Angle add( double valInc ) { return new Angle(itsValue + valInc); } /** * Adds a value to this angle. * The result is returned in a new object. * * @param valInc * The value to add to this angle. * Must not be equal to <code>null</code>. * * @return * A reference to the new object. */ public Angle add( Angle valInc ) { return new Angle(itsValue + valInc.itsValue); } /** * Multiplies this angle by a scalar. * The value is returned in a new object. * * @param valMul * The value to multiply this value by. * * @return * A reference to the new object. */ public Angle multiply( double valMul ) { return new Angle(itsValue * valMul); } /** * Decimates this angle. * The result is returned in a new object. * * The resulting angle is guaranteed to be in the range * 0&nbsp;<=&nbsp;angle&nbsp;<&nbsp;360\u00B0. * * @return * A reference to this object. */ public Angle decimate() { // The new value. double newValue; // Figure out modulo 2PI. newValue = itsValue % (2.0 * Math.PI); // Could still be negative. Correct this. if(newValue < 0.0) { newValue = newValue + (2 * Math.PI); } return new Angle(newValue); } /** * Calculate the absolute value of this angle. * The result is returned in a new object. * * @return * A reference to this object. */ public Angle abs() { // Calculate the absolute value of the value. return new Angle(Math.abs(itsValue)); } /** * Calculate the trigonometric sine of this angle. * * @return * The sine of this angle. */ public double sin() { // Take the trigonometric sine of the value. return (Math.sin(itsValue)); } /** * Calculate the trigonometric cosine of this angle. * * @return * The cosine of this angle. */ public double cos() { // Take the trigonometric cosine of the value. return (Math.cos(itsValue)); } /** * Calculate the trigonometric tangent of this angle. * * @return * The tangent of this angle. */ public double tan() { // Take the trigonometric tangent of the value. return (Math.tan(itsValue)); } /** * Calculate the trigonometric arcsine of a number, and return an * angle with its value. * * @param x * The value to take the arcsine of. * * @return * A reference to a new angle whose value is the trigonometric * arcsine of x. */ public static Angle asin( double x ) { // Make a new Angle of the correct value. return (new Angle(Math.asin(x))); } /** * Calculate the trigonometric arccosine of a number, and return an * angle with its value. * * @param x * The value to take the arccosine of. * * @return * A reference to a new angle whose value is the trigonometric * arccosine of x. */ public static Angle acos( double x ) { // Make a new Angle of the correct value. return (new Angle(Math.acos(x))); } /** * Calculate the trigonometric arctangent of a number, and return an * angle with its value. * * @param x * The value to take the arctangent of. * * @return * A reference to a new angle whose value is the trigonometric * arccosine of x. */ public static Angle atan( double x ) { // Make a new Angle of the correct value. return (new Angle(Math.atan(x))); } /** * Make a string of the object in DMS format. * * @param digits * The number of digits for the floating part. * Must not be less than zero. * * @param degsSep * The degrees seperator. * This is the character that is placed after the degrees field. * * @return * The string represented in DMS. */ private String toStringDMS( int digits, char degsSep ) { // The string to return. String res; // Scratch value. double x; // The degrees field. long degs; // The minutes field. long mins; // The seconds field. long secs; // The seconds fraction field. double secsFrac; // String version of the seconds fraction field. String secsFracStr = null; // The formatter for the seconds fraction field. DecimalFormat secFmt; // Make the number formatter for the seconds fraction field. secFmt = new DecimalFormat("." + repeatChars('0',digits)); // Convert the value to degrees (and take its absolute value). x = Math.abs(itsValue * DEGS_PER_RAD); degs = (long)x; // Calculate the minutes field. x = (x * MINS_PER_DEG) % MINS_PER_DEG; mins = (long)x; // Calculate the seconds field. x = (x * SECS_PER_MIN) % SECS_PER_MIN; secs = (long)x; // Calculate the seconds fraction field. secsFrac = x % 1.0; // If the requested number of decimal places is zero, we may need // to round up. if((digits == 0) && (secsFrac >=0.5)) { secs++; if(secs >= 60) { secs = secs - 60; mins++; if(mins >= 60) { mins = mins - 60; degs++; } } } // If the requested number of decimal places is non-zero, we may // still need to round up. This will be the case when the seconds // fraction string has been rounded up and looks like "1.xx". if(digits != 0) { secsFracStr = secFmt.format(secsFrac); if(secsFracStr.charAt(0) == '1') { // Change the seconds fraction string back to zero. secsFracStr = secFmt.format(0.0); // Round up. secs++; if(secs >= 60) { secs = secs - 60; mins++; if(mins >= 60) { mins = mins - 60; degs++; } } } } // Construct the return string. res = ((itsValue < 0) ? "-" : "") + degs + degsSep + theirMinFmt.format(mins) + "\'" + theirSecFmt.format(secs) + "\""; if(digits != 0) { res = res + secsFracStr; } return res; } /** * Make a string of the object in HMS format. * * @param digits * The number of digits for the floating part. * Must not be less than zero. * * @return * The string representation of the object in HMS format. */ private String toStringHMS( int digits ) { // The string to return. String res; // Scratch value. double x; // The number of hours. long hrs; // The number of minutes. long mins; // The number of seconds. long secs; // The seconds fraction field. double secsFrac; // String version the seconds fraction field. String secsFracStr = null; // The formatter for the seconds fraction field. NumberFormat secFmt; // Make the number formatter for the seconds fraction field. secFmt = new DecimalFormat("." + repeatChars('0',digits)); // Convert the value to hours (and take its absolute value). x = Math.abs(itsValue * HOURS_PER_RAD); hrs = (long)x; // Calculate the minutes field. x = (x * MINS_PER_HOUR) % MINS_PER_HOUR; mins = (long)x; // Calculate the seconds field. x = (x * SECS_PER_MIN) % SECS_PER_MIN; secs = (long)x; // Calculate the seconds fraction field. secsFrac = x % 1.0; // If the requested number of decimal places is zero, we may need // to round up. if((digits == 0) && (secsFrac >=0.5)) { secs++; if(secs >= 60) { secs = secs - 60; mins++; if(mins >= 60) { mins = mins - 60; hrs++; } } } // If the requested number of decimal places is non-zero, we may // still need to round up. This will be the case when the seconds // fraction string has been rounded up and looks like "1.xx". if(digits != 0) { secsFracStr = secFmt.format(secsFrac); if(secsFracStr.charAt(0) == '1') { // Change the seconds fraction string back to zero. secsFracStr = secFmt.format(0.0); // Round up. secs++; if(secs >= 60) { secs = secs - 60; mins++; if(mins >= 60) { mins = mins - 60; hrs++; } } } } // Construct the return string. res = ((itsValue < 0) ? "-" : "") + theirHrFmt.format(hrs) + ":" + theirMinFmt.format(mins) + ":" + theirSecFmt.format(secs); if(digits != 0) { res = res + secsFracStr; } return res; } /** * Make a string of the object in DEGREES format. * * @param digits * The number of digits for the floating part. * Must not be less than zero. * * @return * The string represented in DEGREES format. */ private String toStringDegrees( int digits ) { // The string to return. String res; // The format specifier. NumberFormat fmt; // Make the format specifier for the fraction part. if(digits == 0) { fmt = new DecimalFormat("0"); } else { fmt = new DecimalFormat("0." + repeatChars('0',digits)); } // Convert it to a string. res = fmt.format(itsValue * DEGS_PER_RAD); if(digits == 0) { // Append a degrees sign. res = res + "\u00B0"; } else { // Replace the decimal point with degrees sign and decimal point. res = res.substring(0,res.indexOf('.')) + "\u00B0." + res.substring(res.indexOf('.') + 1); } return res; } /** * Make a string of the object in RADIANS format. * * @param digits * The number of digits for the floating part. * Must not be less than zero. * * @return * The object in RADIANS format. */ private String toStringRadians( int digits ) { // The format specifier. NumberFormat fmt; // Make the format specifier. if(digits == 0) { fmt = new DecimalFormat("#0"); } else { fmt = new DecimalFormat("#0." + repeatChars('0',digits)); } return fmt.format(itsValue); } /** * Parse a string. * * @param str * The string to parse. * * @exception NumberFormatException * Thrown when the string could not be converted. */ private void parse( String str ) { // Apply some heuristics to see which format the string is in. // As we find each, try to parse the string according to the // candidate format. // Trim whitespace from the string. str = str.trim(); try { // See if the string can be parsed as radians. itsValue = parseRadians(str); } catch(NumberFormatException e1) { try { // See if the string can be parsed as HMS. itsValue = parseHMS(str); } catch(NumberFormatException e2) { try { // See if the string can be parsed as DMS. This will include // DEGREES format as on inptut is is a proper subset of DMS // (and DMS_ASCII). itsValue = parseDMS(str); } catch(NumberFormatException e3) { // There's no hope. Throw a number format exception with // the original string. throw new NumberFormatException("bad angle \"" + str + "\""); } } } } /** * Parse a string as DMS. * * @param str * The string to parse as DMS. * Assume that leading and trailing whitespace has been removed. * * @return * The value of the angle in radians. * * @exception NumberFormatException * The string is not a valid DMS. */ private double parseDMS( String str ) { // An index into the string. int idx; // Place to put the degrees value. long degs; // Place to put the minutes value. long mins; // Place to put the seconds value. long secs; // Place to put the fractional value. double frac; // The end value. double val; // True if the value is negative. boolean isNegative = false; if(str.equals("")) { throw new NumberFormatException("bad angle \"" + str + "\""); } try { // Figure out whether positive or negative. Remove the "-" from // the front of the string if it is negative. if(str.charAt(0) == '-') { isNegative = true; str = str.substring(1,str.length()); } // Find the degrees string. idx = str.indexOf('\u00B0'); if(idx == -1) { idx = str.indexOf('^'); } if(idx == -1) { degs = 0; } else { // Extract a value from the degrees field. degs = (new Long(str.substring(0,idx))).longValue(); if(degs < 0) { throw new NumberFormatException("bad angle \"" + str + "\""); } str = str.substring(idx + 1,str.length()); } if(str.length() == 0) { // Nothing left to do. val = degs * RADS_PER_DEG; } else if(str.charAt(0) == '.') { // Fractional part is degrees. Also implies end of parsing // (ie, no minutes or seconds components). frac = (new Double(str)).doubleValue(); if(frac < 0) { throw new NumberFormatException("bad angle \"" + str + "\""); } val = (degs + frac) * RADS_PER_DEG; } else { // Find the minutes string. idx = str.indexOf('\''); if(idx == -1) { mins = 0; } else { // Extract a value from the minutes field. mins = (new Long(str.substring(0,idx))).longValue(); if(mins < 0) { throw new NumberFormatException("bad angle \"" + str + "\""); } str = str.substring(idx + 1,str.length()); } if(str.length() == 0) { // Nothing left to do. val = (degs + mins / MINS_PER_DEG) * RADS_PER_DEG; } else if(str.charAt(0) == '.') { // Fractional part is minutes. Also implies end of parsing // (ie, no seconds component). frac = (new Double(str)).doubleValue(); if(frac < 0) { throw new NumberFormatException("bad angle \"" + str + "\""); } val = (degs + (mins + frac) / MINS_PER_DEG) * RADS_PER_DEG; } else { // Find the seconds string. idx = str.indexOf('\"'); if(idx == -1) { secs = 0; } else { // Extract a value from the seconds field. secs = (new Long(str.substring(0,idx))).longValue(); if(secs < 0) { throw new NumberFormatException("bad angle \"" + str + "\""); } str = str.substring(idx + 1,str.length()); } if(str.length() == 0) { // Nothing left to do. val = (degs + mins / MINS_PER_DEG + secs / SECS_PER_MIN / MINS_PER_DEG) * RADS_PER_DEG; } else { // Fractional part is seconds. frac = (new Double(str)).doubleValue(); if(frac < 0) { throw new NumberFormatException("bad angle \"" + str + "\""); } val = (degs + mins / MINS_PER_DEG + (secs + frac) / SECS_PER_MIN / MINS_PER_DEG) * RADS_PER_DEG; } } } } catch(NumberFormatException e) { throw new NumberFormatException("bad angle \"" + str + "\""); } catch(Exception e) { throw new NumberFormatException("bad angle \"" + str + "\""); } if(isNegative) { val = -val; } return val; } /** * Parse a string as HMS. * * @param str * The string to parse as HMS. * * @return * THe value of the angle in radians. * * @exception NumberFormatException * The string is not a valid HMS. */ private double parseHMS( String str ) { // The index of the first colon. int idx1; // The index of the second colon. int idx2; // Place to put the hours value. long hours; // Place to put the minutes value. long mins; // Place to put the seconds value. double secs; // The end value. double val; // True if the value is negative. boolean isNegative = false; try { // Find the first colon. idx1 = str.indexOf(':'); // Make sure it was found. if(idx1 == -1) { throw new NumberFormatException("bad angle \"" + str + "\""); } // Find the second colon. idx2 = str.indexOf(':',idx1 + 1); // Make sure it was found. if(idx2 == -1) { throw new NumberFormatException("bad angle \"" + str + "\""); } // Extract the hours value. hours = Math.abs((new Long(str.substring(0,idx1))).longValue()); if(str.charAt(0) == '-') { isNegative = true; } // Extract the minutes value. mins = (new Long(str.substring(idx1 + 1,idx2))).longValue(); // Extract the seconds value. secs = (new Double(str.substring(idx2 + 1,str.length()))).doubleValue(); // Figure out the value. val = (hours + (mins / MINS_PER_HOUR) + (secs / SECS_PER_MIN / MINS_PER_HOUR)) * RADS_PER_HOUR; if(isNegative) { val = -val; } } catch(Exception e) { throw new NumberFormatException("bad angle \"" + str + "\""); } return val; } /** * Parse a string as RADIANS. * * @param str * The string to parse as RADIANS. * * @return * The value of the angle in radians. * * @exception NumberFormatException * The string is not a valid RADIANS. */ private double parseRadians( String str ) { // The value to return. double val; try { // Try to parse the string into a Double. val = (new Double(str)).doubleValue(); } catch(Exception e) { throw new NumberFormatException("bad angle \"" + str + "\""); } return val; } /** * Make a string with a given number of a given character. * * @param ch * The character to make the string out of. * * @param len * The number of characters in the string. * * @return * A string made up of <code>ch</code> repeated <code>len</code> * times. */ private static String repeatChars( char ch, int len ) { // A string buffer to build the string in. StringBuffer str; // Make the string buffer. str = new StringBuffer(len); // Fill it with the characters. for(int iCh = 0 ; iCh < len ; iCh++) { str.append(ch); } return new String(str); } }
UTF-8
Java
43,571
java
Angle.java
Java
[ { "context": "iginal object\n * is not changed.</p>\n *\n * @author David G Loone\n *\n * @version $Id: Angle.java,v 1.39 2005/07/08 ", "end": 1429, "score": 0.9996181726455688, "start": 1416, "tag": "NAME", "value": "David G Loone" } ]
null
[]
// Copyright (C)1997 CSIRO Australia Telescope National Facility // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This library 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 Library General Public License for more details. // // A copy of the GNU Library General Public License is available at: // http://wwwatoms.atnf.csiro.au/doc/gnu/GLGPL.htm // or, write to the Free Software Foundation, Inc., 59 Temple Place, // Suite 330, Boston, MA 02111-1307 USA package atnf.atoms.util; import java.io.*; import java.text.*; /** * Class representing an angle. * * <p>The string representation for an <code>Angle</code> object is * represented by an object of type <code>Angle.Format</code>. * When reading these strings, * it is possible to automatically distinguish * between these formats and obtain the correct internal value.</p> * * <p>Objects of this class are immutable. * Whenever an operation is requested on an object, * a new object with the result is returned and the original object * is not changed.</p> * * @author <NAME> * * @version $Id: Angle.java,v 1.39 2005/07/08 04:47:09 bro764 Exp $ * * @see AngleDisplay */ public class Angle implements Cloneable, Immutable, Serializable { /** * The RCS id. */ final public static String RCSID = "$Id: Angle.java,v 1.39 2005/07/08 04:47:09 bro764 Exp $"; /** * Serialised version id. */ static final long serialVersionUID = -2309745966047874429L; /** * The hours format. */ final private static NumberFormat theirHrFmt = new DecimalFormat("00"); /** * The minutes format. */ final private static NumberFormat theirMinFmt = new DecimalFormat("00"); /** * The seconds format. */ final private static NumberFormat theirSecFmt = new DecimalFormat("00"); /** * String formats. * * Objects of this class represent the different string formats * that an <code>Angle</code> value can take. */ final public static class Format extends Enum { /** * Represents the ordinal value of <code>DMS</code>. */ final public static int DMS_ORD = 1; /** * Indicates degrees/minutes/seconds using UNICODE characters. * This form always specifies degrees, minutes and seconds * components. * The degrees field is a signed integer, followed by a \u00B0. * The minutes field is an unsigned integer, * followed by a '. * The seconds field is a unsigned integer, * followed by a ". * This is optionally follwed by a decimal fractional part of the * seconds. * The minutes field and the integer component of the seconds field * are always two characters wide, * with leading zeros where necessary. * Example formats are: * <ul> * <li>XX\u00B0X'XX"</li> * <li>-XX\u00B0XX'XX".XXX</li> * <li>+XX\u00B0X'XX".X</li> * </ul> */ final public static Format DMS = new Format(DMS_ORD,"DMS"); /** * Represents the ordinal value of <code>DMS_ASCII</code>. */ final public static int DMS_ASCII_ORD = 2; /** * Indicates degrees/minutes/seconds using only ASCII characters. * This form is very similar to <code>DEGREES</code> except that * the degree and minutes fields are seperated by * the '^' character. It is supplied for systems that do not * support UNICODE. On input the 'd' character is acceptable in place * of the '^' character. * Example formats are: * <ul> * <li>XX^XX'XX"</li> * <li>-XX^XX'XX".XXX</li> * <li>+XX^XX'XX".X</li> * </ul> */ final public static Format DMS_ASCII = new Format(DMS_ASCII_ORD,"DMS_ASCII"); /** * Represents the ordinal value of <code>DEGREES</code>. */ final public static int DEGREES_ORD = 3; /** * Indicates decimal degrees using UNICODE characters. * This is a signed floating number, * followed by a \u00B0 character. * Example formats are: * <ul> * <li>XX.XXXX\u00B0</li> * <li>-XX\u00B0</li> * </ul> */ final public static Format DEGREES = new Format(DEGREES_ORD,"DEGREES"); /** * Indicates the ordinal value of <code>HMS</code>. */ final public static int HMS_ORD = 4; /** * Indicates hours/minutes/seconds. * Each of the hours, minutes and seconds fields are * seperated by a colon. * The hours, minutes and the integer part of the seconds fields * are in a two character field, * filled with leading zeros if necessary. * Example formats are: * <ul> * <li>XX:XX:XX.X</li> * <li>-XX:XX:XX</li> * </ul> */ final public static Format HMS = new Format(HMS_ORD,"HMS"); /** * Indicates the ordinal value of <code>RADIANS</code>. */ final public static int RADIANS_ORD = 5; /** * Indicates radians (decimal). * This is a signed floating number. * Example formats include: * <ul> * <li>XX.XXXX</li> * <li>-XX</li> * </ul> */ final public static Format RADIANS = new Format(RADIANS_ORD,"RADIANS"); /** * The default format. */ final public static Format DEFAULT_FORMAT = DMS; /** * Default constructor to prevent instantiation by outsiders. */ private Format() { super(); } /** * Constructor. * * @param ord * The ordinal value of the format. * * @param message * The string message for the format. */ private Format( int ord, String message ) { super(ord,message); } } /** * The number of minutes in a degree. */ private static final double MINS_PER_DEG = 60.0; /** * The number of minutes in an hour. */ private static final double MINS_PER_HOUR = 60.0; /** * The number of seconds in a minute. */ private static final double SECS_PER_MIN = 60.0; /** * The number of degrees in a radian. */ private static final double DEGS_PER_RAD = 360.0 / (2.0 * Math.PI); /** * The number of radians in a degree. */ private static final double RADS_PER_DEG = (2.0 * Math.PI) / 360.0; /** * The number of hours in a radian. */ private static final double HOURS_PER_RAD = 24.0 / (2.0 * Math.PI); /** * The number of radians in an hour. */ private static final double RADS_PER_HOUR = (2.0 * Math.PI) / 24.0; /** * An angle of 0 degrees. */ public static final double A0 = 0.0; /** * An angle of 90 degrees. */ public static final double A90 = Math.PI / 2.0; /** * An angle of 180 degrees. */ public static final double A180 = Math.PI; /** * An angle of 270 degrees. */ public static final double A270 = Math.PI * 3.0 / 2.0; /** * An angle of 360 degrees. */ public static final double A360 = Math.PI * 2.0; /** * The current default output format. */ private static Format theirDefaultFormat = Format.DEFAULT_FORMAT; /** * The value of the angle (in radians). */ protected double itsValue; /** * Make a new object with a value of zero. */ public static Angle factory() { return new Angle(); } /** * Make a new object with a value of zero. */ public Angle() { // Set the value to zero. itsValue = 0; } /** * Make a new object from a double. * * @param value * The angle value (in radians). */ public static Angle factory( double value ) { return new Angle(value); } /** * Make a new object from a double. * * @param value * The angle value (in radians). */ private Angle( double value ) { // Set the value to that indicated. itsValue = value; } /** * Make a new object from a double in either radians or degrees. * * @param value * The angle value * (in units specified by <code>units</code>). * * @param units * The units of <code>value</code>. * This must be equal to either <code>DEGREES</code> * <code>RADIANS</code>. * * @exception IllegalArgumentException * Thrown when <code>units</code> is not equal to either * <code>DEGREES</code> or <code>RADIANS</code>. */ public static Angle factory( double value, Format units ) throws IllegalArgumentException { return new Angle(value,units); } /** * Make a new object from a double in either radians or degrees. * * @param value * The angle value * (in units specified by <code>units</code>). * * @param units * The units of <code>value</code>. * This must be equal to either <code>DEGREES</code> * <code>RADIANS</code>. * * @exception IllegalArgumentException * Thrown when <code>units</code> is not equal to either * <code>DEGREES</code> or <code>RADIANS</code>. */ private Angle( double value, Format units ) throws IllegalArgumentException { if(units.ord() == Format.DEGREES.ord()) { itsValue = value * RADS_PER_DEG; } else if(units.ord() == Format.RADIANS.ord()) { itsValue = value; } else { throw new IllegalArgumentException("bad format: " + units); } } /** * Make a new object from an existing * <code>Angle</code> object. * * @param a * Another <code>Angle</code> object to copy the value from. * Must not be <code>null</code>. */ public static Angle factory( Angle a ) { return new Angle(a); } /** * Make a new object from an existing * <code>Angle</code> object. * * @param a * Another <code>Angle</code> object to copy the value from. * Must not be <code>null</code>. */ private Angle( Angle a ) { // Set the value that indicated. itsValue = a.itsValue; } /** * Make a new object from a string representation. * * <p> * The string can be any one of the valid string representations of * an angle. * The particular format is automatically determined * and the string is parsed accordingly. * * <p> * The allowed formats are generalised somewhat from the formats * that are printed. * The following shows some valid combinations: * <blockquote> * <table cellpadding=4 border=1> * <tr> * <td align=center><font size=+1><code><b>-2.48</b></code></font></td> * <td>radians</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>3:5:27.32</b></code></font></td> * <td>hours/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>-3:5:27.32</b></code></font></td> * <td>hours/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>3:5:27</b></code></font></td> * <td>hours/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B02'34"</b></code></font></td> * <td>degrees/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B0</b></code></font></td> * <td>degrees</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B0.38</b></code></font></td> * <td>degrees</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B02'.38</b></code></font></td> * <td>degrees/minutes</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B02'45"</b></code></font></td> * <td>degrees/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>-48\u00B02'45".38</b></code></font></td> * <td>degrees/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>2'.38</b></code></font></td> * <td>minutes</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>2'45".38</b></code></td> * <td>minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>45"</b></code></td> * <td>seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>45".39</b></code></td> * <td>seconds</td> * </tr> * </table> * </blockquote> * * @param str * A <code>String</code> representation of an * <code>Angle</code> object. * Whitespace at the beginning or end of the string is ignored. * Must not be equal to <code>null</code>. * * @exception NumberFormatException * Thrown when a <code>String</code> is not a valid string * format of an angle. */ public static Angle factory( String str ) throws NumberFormatException { return new Angle(str); } /** * Make a new object from a string representation. * * <p> * The string can be any one of the valid string representations of * an angle. * The particular format is automatically determined * and the string is parsed accordingly. * * <p> * The allowed formats are generalised somewhat from the formats * that are printed. * The following shows some valid combinations: * <blockquote> * <table cellpadding=4 border=1> * <tr> * <td align=center><font size=+1><code><b>-2.48</b></code></font></td> * <td>radians</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>3:5:27.32</b></code></font></td> * <td>hours/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>-3:5:27.32</b></code></font></td> * <td>hours/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>3:5:27</b></code></font></td> * <td>hours/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B02'34"</b></code></font></td> * <td>degrees/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B0</b></code></font></td> * <td>degrees</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B0.38</b></code></font></td> * <td>degrees</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B02'.38</b></code></font></td> * <td>degrees/minutes</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>48\u00B02'45"</b></code></font></td> * <td>degrees/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>-48\u00B02'45".38</b></code></font></td> * <td>degrees/minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>2'.38</b></code></font></td> * <td>minutes</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>2'45".38</b></code></td> * <td>minutes/seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>45"</b></code></td> * <td>seconds</td> * </tr> * <tr> * <td align=center><font size=+1><code><b>45".39</b></code></td> * <td>seconds</td> * </tr> * </table> * </blockquote> * * @param str * A <code>String</code> representation of an * <code>Angle</code> object. * Whitespace at the beginning or end of the string is ignored. * Must not be equal to <code>null</code>. * * @exception NumberFormatException * Thrown when a <code>String</code> is not a valid string * format of an angle. */ private Angle( String str ) throws NumberFormatException { // If the string contains a 'd' characer, replace it with // '^' characters. if(str.indexOf("d") != -1) { // The chars of the string. char[] chars = str.toCharArray(); // Iterate over the char array. for(int i = 0; i < chars.length; i++) { if(chars[i] == 'd') { chars[i] = '^'; } } // Re-create the string. str = new String(chars); } parse(str); } /** * Clone the object. * * @return * A new object identical to this one. */ public Object clone() { // The class is immutable. Just return this. return this; } /** * Test for equivalence. * * @param o * The object to test for equivlence against. * * @return * Returns <code>true</code> if <code>o</code> is equivalent to * this object, * <code>false</code> otherwise. */ public boolean equiv( Object o ) { // The value to return. boolean isEquiv = false; // Local version of o. Angle o1; // Prerequisites. if((o != null) && (o.getClass() == getClass())) { o1 = (Angle)o; // Is equiv if same object. if(equals(o1)) { isEquiv = true; } else { // Test the attributes. isEquiv = (o1.itsValue == itsValue); } } return isEquiv; } /** * Set the default string format for the class. * * @param fmt * The new default string format for the class. */ public static void setTheirDefaultFormat( Format fmt ) { theirDefaultFormat = (Format)fmt.clone(); } /** * Get the default string format for the class. * * @return * The current default string format for the class. */ public static Format getTheirDefaultFormat() { return (Format)theirDefaultFormat.clone(); } /** * Test for proximity with another angle. * * @param a * The angle to test against. * Must not be equal to <code>null</code>. * * @param prox * The proximity to test for. * Must not be equal to <code>null</code>. * * @return * The value <code>true</code> if this angle is within * <code>prox</code> (on either side) of <code>a</code>. */ public boolean isNear( Angle a, Angle prox ) { // Test for prox < 0. if(prox.itsValue < 0) { throw new IllegalArgumentException("prox = " + prox); } return (Math.abs(itsValue - a.itsValue) <= prox.itsValue); } /** * Test for this angle less than another. * * @param a * The angle to test against. * Must not be equal to <code>null</code>. * * @return * The value <code>true</code> if this object * is less than <code>a</code>. */ public boolean isLT( Angle a ) { return (itsValue < a.itsValue); } /** * Test for this angle less than or equal to another. * * @param a * The angle to test against. * Must not be equal to <code>null</code>. * * @return * The value <code>true</code> if this object * is less than or equal to <code>a</code>. */ public boolean isLTE( Angle a ) { return (itsValue <= a.itsValue); } /** * Test for this angle greater than another. * * @param a * The angle to test against. * Must not be equal to <code>null</code>. * * @return * The value <code>true</code> if this object * is greater than <code>a</code>. */ public boolean isGT( Angle a ) { return (itsValue > a.itsValue); } /** * Test for this angle greater than or equal to another. * * @param a * The angle to test against. * Must not be equal to <code>null</code>. * * @return * The value <code>true</code> if this object * is greater than or equal to <code>a</code>. */ public boolean isGTE( Angle a ) { return (itsValue >= a.itsValue); } /** * Test for not-a-number. * * @return * Boolean <code>true</code> if this angle is not-a-number, * <code>false</code> otherwise. */ public boolean isNaN() { // Make a Double object, and call the NaN method. return (new Double(itsValue)).isNaN(); } /** * Test for infinity. * * @return * Boolean <code>true</code> if this angle is infinite, * <code>false</code> otherwise. */ public boolean isInfinite() { // Make a Double object, and call the isInfinite method. return (new Double(itsValue)).isInfinite(); } /** * Returns the value of this angle. * * @return * A double value. */ public double getValue() { // Return the value of this angle. return itsValue; } /** * Returns the value of this angle in degrees. * * @return * A double value (in degrees). */ public double getValueDeg() { // Return the value of this angle in degrees. return (itsValue * DEGS_PER_RAD); } /** * Returns a string representation of this angle in the default * string format and with the default and with one decimal place. * * @return * A <code>String</code> object of this Angle. */ public String toString() { return toString(getTheirDefaultFormat(),1); } /** * Returns a string representation of this angle in the default * format with the given number of decimal places. * * @param digits * The number of decimal places in the string. * Must not be less than zero. */ public String toString( int digits ) { return toString(getTheirDefaultFormat(),digits); } /** * Returns a string representation of this angle in any given * string format and one decimal place. * * @param format * Detemrines which string format will be generated. * A value of <code>null</code> indicates the default format. * * @return * A <code>String</code> object of this Angle. */ public String toString( Format format ) { if(format == null) { format = getTheirDefaultFormat(); } return toString(format,1); } /** * Returns a string representation of this angle in any given * string format, and to an indicated number of digits. * * @param format * Determines which string representation will be generated. * A value of <code>null</code> indicates the default format. * * @param digits * The number of siginificant digits. * The application of this parameter varies slightly with the * string format requested. * It will apply to whichever field is a floating point number. * In the case of <code>DMS</code>, * <code>DMS_ASCII</code> and <code>HMS</code>, * it will apply to the seconds field. * In the case of <code>DEGREES</code> and <code>RADIANS</code>, * it will apply to the degrees and radians fields respectively * (the only numerical field in the number). * Must not be less than zero. * * @return * A <code>String</code> object representing this angle, * formatted according to <code>format</code>. */ public String toString( Format format, int digits ) { // The string to build the result into. String res = null; // The value in its object wrapper. Double itsValueObj = new Double(itsValue); if(format == null) { format = getTheirDefaultFormat(); } // Need to check for the value -0.0, since this is not changed // by the Math.abs function. if(itsValueObj.toString().equals("-0.0")) { itsValue = -itsValue; } // Check for some special cases. if(itsValueObj.isNaN()) { res = new String("NaN"); } else if(itsValueObj.isInfinite()) { res = new String("Infinity"); } else { // Build a result according to the format requested. switch(format.ord()) { case Format.DMS_ORD: res = toStringDMS(digits,'\u00B0'); break; case Format.DMS_ASCII_ORD: res = toStringDMS(digits,'^'); break; case Format.HMS_ORD: res = toStringHMS(digits); break; case Format.DEGREES_ORD: // Make the string. res = toStringDegrees(digits); break; case Format.RADIANS_ORD: res = toStringRadians(digits); break; default: assert false; break; } } return res; } /** * Negate the value of this angle. * The result is returned in a new object. * * @return * A reference to the new object. */ public Angle negate() { return new Angle(-itsValue); } /** * Add a value to this angle. * The result is returned in a new object. * * @param valInc * The value to add to this angle. * * @return * A reference to the new object. */ public Angle add( double valInc ) { return new Angle(itsValue + valInc); } /** * Adds a value to this angle. * The result is returned in a new object. * * @param valInc * The value to add to this angle. * Must not be equal to <code>null</code>. * * @return * A reference to the new object. */ public Angle add( Angle valInc ) { return new Angle(itsValue + valInc.itsValue); } /** * Multiplies this angle by a scalar. * The value is returned in a new object. * * @param valMul * The value to multiply this value by. * * @return * A reference to the new object. */ public Angle multiply( double valMul ) { return new Angle(itsValue * valMul); } /** * Decimates this angle. * The result is returned in a new object. * * The resulting angle is guaranteed to be in the range * 0&nbsp;<=&nbsp;angle&nbsp;<&nbsp;360\u00B0. * * @return * A reference to this object. */ public Angle decimate() { // The new value. double newValue; // Figure out modulo 2PI. newValue = itsValue % (2.0 * Math.PI); // Could still be negative. Correct this. if(newValue < 0.0) { newValue = newValue + (2 * Math.PI); } return new Angle(newValue); } /** * Calculate the absolute value of this angle. * The result is returned in a new object. * * @return * A reference to this object. */ public Angle abs() { // Calculate the absolute value of the value. return new Angle(Math.abs(itsValue)); } /** * Calculate the trigonometric sine of this angle. * * @return * The sine of this angle. */ public double sin() { // Take the trigonometric sine of the value. return (Math.sin(itsValue)); } /** * Calculate the trigonometric cosine of this angle. * * @return * The cosine of this angle. */ public double cos() { // Take the trigonometric cosine of the value. return (Math.cos(itsValue)); } /** * Calculate the trigonometric tangent of this angle. * * @return * The tangent of this angle. */ public double tan() { // Take the trigonometric tangent of the value. return (Math.tan(itsValue)); } /** * Calculate the trigonometric arcsine of a number, and return an * angle with its value. * * @param x * The value to take the arcsine of. * * @return * A reference to a new angle whose value is the trigonometric * arcsine of x. */ public static Angle asin( double x ) { // Make a new Angle of the correct value. return (new Angle(Math.asin(x))); } /** * Calculate the trigonometric arccosine of a number, and return an * angle with its value. * * @param x * The value to take the arccosine of. * * @return * A reference to a new angle whose value is the trigonometric * arccosine of x. */ public static Angle acos( double x ) { // Make a new Angle of the correct value. return (new Angle(Math.acos(x))); } /** * Calculate the trigonometric arctangent of a number, and return an * angle with its value. * * @param x * The value to take the arctangent of. * * @return * A reference to a new angle whose value is the trigonometric * arccosine of x. */ public static Angle atan( double x ) { // Make a new Angle of the correct value. return (new Angle(Math.atan(x))); } /** * Make a string of the object in DMS format. * * @param digits * The number of digits for the floating part. * Must not be less than zero. * * @param degsSep * The degrees seperator. * This is the character that is placed after the degrees field. * * @return * The string represented in DMS. */ private String toStringDMS( int digits, char degsSep ) { // The string to return. String res; // Scratch value. double x; // The degrees field. long degs; // The minutes field. long mins; // The seconds field. long secs; // The seconds fraction field. double secsFrac; // String version of the seconds fraction field. String secsFracStr = null; // The formatter for the seconds fraction field. DecimalFormat secFmt; // Make the number formatter for the seconds fraction field. secFmt = new DecimalFormat("." + repeatChars('0',digits)); // Convert the value to degrees (and take its absolute value). x = Math.abs(itsValue * DEGS_PER_RAD); degs = (long)x; // Calculate the minutes field. x = (x * MINS_PER_DEG) % MINS_PER_DEG; mins = (long)x; // Calculate the seconds field. x = (x * SECS_PER_MIN) % SECS_PER_MIN; secs = (long)x; // Calculate the seconds fraction field. secsFrac = x % 1.0; // If the requested number of decimal places is zero, we may need // to round up. if((digits == 0) && (secsFrac >=0.5)) { secs++; if(secs >= 60) { secs = secs - 60; mins++; if(mins >= 60) { mins = mins - 60; degs++; } } } // If the requested number of decimal places is non-zero, we may // still need to round up. This will be the case when the seconds // fraction string has been rounded up and looks like "1.xx". if(digits != 0) { secsFracStr = secFmt.format(secsFrac); if(secsFracStr.charAt(0) == '1') { // Change the seconds fraction string back to zero. secsFracStr = secFmt.format(0.0); // Round up. secs++; if(secs >= 60) { secs = secs - 60; mins++; if(mins >= 60) { mins = mins - 60; degs++; } } } } // Construct the return string. res = ((itsValue < 0) ? "-" : "") + degs + degsSep + theirMinFmt.format(mins) + "\'" + theirSecFmt.format(secs) + "\""; if(digits != 0) { res = res + secsFracStr; } return res; } /** * Make a string of the object in HMS format. * * @param digits * The number of digits for the floating part. * Must not be less than zero. * * @return * The string representation of the object in HMS format. */ private String toStringHMS( int digits ) { // The string to return. String res; // Scratch value. double x; // The number of hours. long hrs; // The number of minutes. long mins; // The number of seconds. long secs; // The seconds fraction field. double secsFrac; // String version the seconds fraction field. String secsFracStr = null; // The formatter for the seconds fraction field. NumberFormat secFmt; // Make the number formatter for the seconds fraction field. secFmt = new DecimalFormat("." + repeatChars('0',digits)); // Convert the value to hours (and take its absolute value). x = Math.abs(itsValue * HOURS_PER_RAD); hrs = (long)x; // Calculate the minutes field. x = (x * MINS_PER_HOUR) % MINS_PER_HOUR; mins = (long)x; // Calculate the seconds field. x = (x * SECS_PER_MIN) % SECS_PER_MIN; secs = (long)x; // Calculate the seconds fraction field. secsFrac = x % 1.0; // If the requested number of decimal places is zero, we may need // to round up. if((digits == 0) && (secsFrac >=0.5)) { secs++; if(secs >= 60) { secs = secs - 60; mins++; if(mins >= 60) { mins = mins - 60; hrs++; } } } // If the requested number of decimal places is non-zero, we may // still need to round up. This will be the case when the seconds // fraction string has been rounded up and looks like "1.xx". if(digits != 0) { secsFracStr = secFmt.format(secsFrac); if(secsFracStr.charAt(0) == '1') { // Change the seconds fraction string back to zero. secsFracStr = secFmt.format(0.0); // Round up. secs++; if(secs >= 60) { secs = secs - 60; mins++; if(mins >= 60) { mins = mins - 60; hrs++; } } } } // Construct the return string. res = ((itsValue < 0) ? "-" : "") + theirHrFmt.format(hrs) + ":" + theirMinFmt.format(mins) + ":" + theirSecFmt.format(secs); if(digits != 0) { res = res + secsFracStr; } return res; } /** * Make a string of the object in DEGREES format. * * @param digits * The number of digits for the floating part. * Must not be less than zero. * * @return * The string represented in DEGREES format. */ private String toStringDegrees( int digits ) { // The string to return. String res; // The format specifier. NumberFormat fmt; // Make the format specifier for the fraction part. if(digits == 0) { fmt = new DecimalFormat("0"); } else { fmt = new DecimalFormat("0." + repeatChars('0',digits)); } // Convert it to a string. res = fmt.format(itsValue * DEGS_PER_RAD); if(digits == 0) { // Append a degrees sign. res = res + "\u00B0"; } else { // Replace the decimal point with degrees sign and decimal point. res = res.substring(0,res.indexOf('.')) + "\u00B0." + res.substring(res.indexOf('.') + 1); } return res; } /** * Make a string of the object in RADIANS format. * * @param digits * The number of digits for the floating part. * Must not be less than zero. * * @return * The object in RADIANS format. */ private String toStringRadians( int digits ) { // The format specifier. NumberFormat fmt; // Make the format specifier. if(digits == 0) { fmt = new DecimalFormat("#0"); } else { fmt = new DecimalFormat("#0." + repeatChars('0',digits)); } return fmt.format(itsValue); } /** * Parse a string. * * @param str * The string to parse. * * @exception NumberFormatException * Thrown when the string could not be converted. */ private void parse( String str ) { // Apply some heuristics to see which format the string is in. // As we find each, try to parse the string according to the // candidate format. // Trim whitespace from the string. str = str.trim(); try { // See if the string can be parsed as radians. itsValue = parseRadians(str); } catch(NumberFormatException e1) { try { // See if the string can be parsed as HMS. itsValue = parseHMS(str); } catch(NumberFormatException e2) { try { // See if the string can be parsed as DMS. This will include // DEGREES format as on inptut is is a proper subset of DMS // (and DMS_ASCII). itsValue = parseDMS(str); } catch(NumberFormatException e3) { // There's no hope. Throw a number format exception with // the original string. throw new NumberFormatException("bad angle \"" + str + "\""); } } } } /** * Parse a string as DMS. * * @param str * The string to parse as DMS. * Assume that leading and trailing whitespace has been removed. * * @return * The value of the angle in radians. * * @exception NumberFormatException * The string is not a valid DMS. */ private double parseDMS( String str ) { // An index into the string. int idx; // Place to put the degrees value. long degs; // Place to put the minutes value. long mins; // Place to put the seconds value. long secs; // Place to put the fractional value. double frac; // The end value. double val; // True if the value is negative. boolean isNegative = false; if(str.equals("")) { throw new NumberFormatException("bad angle \"" + str + "\""); } try { // Figure out whether positive or negative. Remove the "-" from // the front of the string if it is negative. if(str.charAt(0) == '-') { isNegative = true; str = str.substring(1,str.length()); } // Find the degrees string. idx = str.indexOf('\u00B0'); if(idx == -1) { idx = str.indexOf('^'); } if(idx == -1) { degs = 0; } else { // Extract a value from the degrees field. degs = (new Long(str.substring(0,idx))).longValue(); if(degs < 0) { throw new NumberFormatException("bad angle \"" + str + "\""); } str = str.substring(idx + 1,str.length()); } if(str.length() == 0) { // Nothing left to do. val = degs * RADS_PER_DEG; } else if(str.charAt(0) == '.') { // Fractional part is degrees. Also implies end of parsing // (ie, no minutes or seconds components). frac = (new Double(str)).doubleValue(); if(frac < 0) { throw new NumberFormatException("bad angle \"" + str + "\""); } val = (degs + frac) * RADS_PER_DEG; } else { // Find the minutes string. idx = str.indexOf('\''); if(idx == -1) { mins = 0; } else { // Extract a value from the minutes field. mins = (new Long(str.substring(0,idx))).longValue(); if(mins < 0) { throw new NumberFormatException("bad angle \"" + str + "\""); } str = str.substring(idx + 1,str.length()); } if(str.length() == 0) { // Nothing left to do. val = (degs + mins / MINS_PER_DEG) * RADS_PER_DEG; } else if(str.charAt(0) == '.') { // Fractional part is minutes. Also implies end of parsing // (ie, no seconds component). frac = (new Double(str)).doubleValue(); if(frac < 0) { throw new NumberFormatException("bad angle \"" + str + "\""); } val = (degs + (mins + frac) / MINS_PER_DEG) * RADS_PER_DEG; } else { // Find the seconds string. idx = str.indexOf('\"'); if(idx == -1) { secs = 0; } else { // Extract a value from the seconds field. secs = (new Long(str.substring(0,idx))).longValue(); if(secs < 0) { throw new NumberFormatException("bad angle \"" + str + "\""); } str = str.substring(idx + 1,str.length()); } if(str.length() == 0) { // Nothing left to do. val = (degs + mins / MINS_PER_DEG + secs / SECS_PER_MIN / MINS_PER_DEG) * RADS_PER_DEG; } else { // Fractional part is seconds. frac = (new Double(str)).doubleValue(); if(frac < 0) { throw new NumberFormatException("bad angle \"" + str + "\""); } val = (degs + mins / MINS_PER_DEG + (secs + frac) / SECS_PER_MIN / MINS_PER_DEG) * RADS_PER_DEG; } } } } catch(NumberFormatException e) { throw new NumberFormatException("bad angle \"" + str + "\""); } catch(Exception e) { throw new NumberFormatException("bad angle \"" + str + "\""); } if(isNegative) { val = -val; } return val; } /** * Parse a string as HMS. * * @param str * The string to parse as HMS. * * @return * THe value of the angle in radians. * * @exception NumberFormatException * The string is not a valid HMS. */ private double parseHMS( String str ) { // The index of the first colon. int idx1; // The index of the second colon. int idx2; // Place to put the hours value. long hours; // Place to put the minutes value. long mins; // Place to put the seconds value. double secs; // The end value. double val; // True if the value is negative. boolean isNegative = false; try { // Find the first colon. idx1 = str.indexOf(':'); // Make sure it was found. if(idx1 == -1) { throw new NumberFormatException("bad angle \"" + str + "\""); } // Find the second colon. idx2 = str.indexOf(':',idx1 + 1); // Make sure it was found. if(idx2 == -1) { throw new NumberFormatException("bad angle \"" + str + "\""); } // Extract the hours value. hours = Math.abs((new Long(str.substring(0,idx1))).longValue()); if(str.charAt(0) == '-') { isNegative = true; } // Extract the minutes value. mins = (new Long(str.substring(idx1 + 1,idx2))).longValue(); // Extract the seconds value. secs = (new Double(str.substring(idx2 + 1,str.length()))).doubleValue(); // Figure out the value. val = (hours + (mins / MINS_PER_HOUR) + (secs / SECS_PER_MIN / MINS_PER_HOUR)) * RADS_PER_HOUR; if(isNegative) { val = -val; } } catch(Exception e) { throw new NumberFormatException("bad angle \"" + str + "\""); } return val; } /** * Parse a string as RADIANS. * * @param str * The string to parse as RADIANS. * * @return * The value of the angle in radians. * * @exception NumberFormatException * The string is not a valid RADIANS. */ private double parseRadians( String str ) { // The value to return. double val; try { // Try to parse the string into a Double. val = (new Double(str)).doubleValue(); } catch(Exception e) { throw new NumberFormatException("bad angle \"" + str + "\""); } return val; } /** * Make a string with a given number of a given character. * * @param ch * The character to make the string out of. * * @param len * The number of characters in the string. * * @return * A string made up of <code>ch</code> repeated <code>len</code> * times. */ private static String repeatChars( char ch, int len ) { // A string buffer to build the string in. StringBuffer str; // Make the string buffer. str = new StringBuffer(len); // Fill it with the characters. for(int iCh = 0 ; iCh < len ; iCh++) { str.append(ch); } return new String(str); } }
43,564
0.567006
0.554979
1,879
22.188398
20.415995
88
false
false
0
0
0
0
0
0
0.184141
false
false
14
a31ec963cb4304730b39f5b4082195975272a392
18,356,690,240,305
f116fa2ce4c0d9aad21efcb9c01c7cb61648d679
/src/main/java/com/rentCloud/cloud/app/repositories/scoreRepository.java
f718462f3f7dd503fc73e61bd95753a95b908c24
[]
no_license
NataliaTuiran2806/cloud-backend
https://github.com/NataliaTuiran2806/cloud-backend
97ffbd1dc53b99d6240e333f7bb37b5c839a5e63
477b25175e28c0e6f00b72bfe32ec93d60a41891
refs/heads/master
2023-08-29T14:27:11.910000
2021-10-27T12:52:35
2021-10-27T12:52:35
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.rentCloud.cloud.app.repositories; import com.rentCloud.cloud.app.entities.Score; import com.rentCloud.cloud.app.repositories.crud.scoreCrudRepository; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; /** * * @author Naty */ @Repository public class scoreRepository { @Autowired private scoreCrudRepository repository; /** * SELEC * FROM ADMIN * * @return Retorna todos los administradores */ public List<Score> getAll() { return (List<Score>) this.repository.findAll(); } /** * SELECT * FROM ADMIN WHERE ID= id * * @param id * @return Retorna un administrador por su ID especifico */ public Optional<Score> getOne(int id) { return this.repository.findById(id); } /** * INSERT & UPDATE * * @param score * @return Actualiza o guarda un administrador */ public Score save(Score score) { return this.repository.save(score); } /** * DELETE FROM TABLE * * @param score */ public void delete(Score score) { this.repository.delete(score); } }
UTF-8
Java
1,434
java
scoreRepository.java
Java
[ { "context": "ramework.stereotype.Repository;\n\n/**\n *\n * @author Naty\n */\n@Repository\npublic class scoreRepository {\n\n ", "end": 535, "score": 0.9591711759567261, "start": 531, "tag": "USERNAME", "value": "Naty" } ]
null
[]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.rentCloud.cloud.app.repositories; import com.rentCloud.cloud.app.entities.Score; import com.rentCloud.cloud.app.repositories.crud.scoreCrudRepository; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; /** * * @author Naty */ @Repository public class scoreRepository { @Autowired private scoreCrudRepository repository; /** * SELEC * FROM ADMIN * * @return Retorna todos los administradores */ public List<Score> getAll() { return (List<Score>) this.repository.findAll(); } /** * SELECT * FROM ADMIN WHERE ID= id * * @param id * @return Retorna un administrador por su ID especifico */ public Optional<Score> getOne(int id) { return this.repository.findById(id); } /** * INSERT & UPDATE * * @param score * @return Actualiza o guarda un administrador */ public Score save(Score score) { return this.repository.save(score); } /** * DELETE FROM TABLE * * @param score */ public void delete(Score score) { this.repository.delete(score); } }
1,434
0.654114
0.654114
62
22.129032
21.008818
79
false
false
0
0
0
0
0
0
0.241935
false
false
14
b0b7f154ea42de5fb83b64107e4e474a19c9f80f
32,160,715,129,896
4e1bcb32a8fce4e6dadfec43756b8a7eb0edb5bf
/URI/1051.java
f326c66b15b5cc680cc6cb8141681388964360c8
[ "MIT" ]
permissive
gustavoccintrao/BabySteps
https://github.com/gustavoccintrao/BabySteps
ba4be36da480eccfa5d2533f261ee9a7b41f2205
29657a9a7e161252b4e47cd289a68f2fccb6de0b
refs/heads/master
2023-08-29T00:02:30.967000
2021-10-31T18:23:23
2021-10-31T18:23:23
423,227,431
1
0
MIT
true
2021-10-31T18:23:24
2021-10-31T18:20:52
2021-10-31T18:20:53
2021-10-31T18:23:24
394
0
0
0
null
false
false
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); double imposto = 0.00; double salario = input.nextDouble(); if(2000.00 < salario && salario <= 3000.00) { imposto += calculaImposto(salario - 2000.00, 8); } else if(3000.00 < salario && salario <= 4500.00) { imposto += calculaImposto(1000.00, 8); imposto += calculaImposto(salario - 3000.00, 18); } else if(4500.00 < salario) { imposto += calculaImposto(1000.00, 8); imposto += calculaImposto(1500.00, 18); imposto += calculaImposto(salario - 4500.00, 28); } if(imposto == 0.00) { System.out.println("Isento"); } else { System.out.printf("R$ %.2f%n", imposto); } input.close(); } public static double calculaImposto(double valor, int taxa) { return valor * taxa / 100; } }
UTF-8
Java
881
java
1051.java
Java
[]
null
[]
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); double imposto = 0.00; double salario = input.nextDouble(); if(2000.00 < salario && salario <= 3000.00) { imposto += calculaImposto(salario - 2000.00, 8); } else if(3000.00 < salario && salario <= 4500.00) { imposto += calculaImposto(1000.00, 8); imposto += calculaImposto(salario - 3000.00, 18); } else if(4500.00 < salario) { imposto += calculaImposto(1000.00, 8); imposto += calculaImposto(1500.00, 18); imposto += calculaImposto(salario - 4500.00, 28); } if(imposto == 0.00) { System.out.println("Isento"); } else { System.out.printf("R$ %.2f%n", imposto); } input.close(); } public static double calculaImposto(double valor, int taxa) { return valor * taxa / 100; } }
881
0.627696
0.531215
40
21.025
20.09787
62
false
false
0
0
0
0
0
0
2.325
false
false
14
f2d194d9f0f1fee9e7caf8c80a75576742c7ebb0
19,679,540,173,706
150d051e4ea00772b9f4a0bfe23276bef311e6d7
/app/src/main/java/com/example/te_lord/Adapters/ComplaintAdapter.java
77da97e1e3d9c3e366e043d31105ac794ef9bbcb
[]
no_license
Syiera97/Te-Lord-Landlord
https://github.com/Syiera97/Te-Lord-Landlord
2fd119d20a175b70942fb68e4193085f87d646cf
73bbc55574162ce5620c1e76fc0be84bd4d258de
refs/heads/master
2020-06-23T11:08:44.340000
2019-07-24T09:42:39
2019-07-24T09:42:39
198,605,209
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.te_lord.Adapters; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; 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.TextView; import com.bumptech.glide.Glide; import com.example.te_lord.Activities.ComplaintDetailsActivity; import com.example.te_lord_landlord.Models.Complaint; import com.example.te_lord.R; import java.util.List; public class ComplaintAdapter extends RecyclerView.Adapter <ComplaintAdapter.MyViewHolder> { Context mContext; List<Complaint> mData; public ComplaintAdapter(Context mContext, List<Complaint> mData) { this.mContext = mContext; this.mData = mData; } @NonNull @Override public ComplaintAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View row = LayoutInflater.from(mContext).inflate(R.layout.row_post_item,parent,false); return new MyViewHolder(row); } @Override public void onBindViewHolder(@NonNull ComplaintAdapter.MyViewHolder myViewHolder, int position) { myViewHolder.tvTitle.setText(mData.get(position).getTitle()); Glide.with(mContext).load(mData.get(position).getPicture()).into(myViewHolder.imgPost); Glide.with(mContext).load(mData.get(position).getUserPhoto()).into(myViewHolder.imgProfilePhoto); } @Override public int getItemCount() { return mData.size(); } public class MyViewHolder extends RecyclerView.ViewHolder{ TextView tvTitle; ImageView imgPost; ImageView imgProfilePhoto; public MyViewHolder(@NonNull View itemView) { super(itemView); tvTitle = itemView.findViewById(R.id.row_complaint_title); imgPost = itemView.findViewById(R.id.row_post_img); imgProfilePhoto = itemView.findViewById(R.id.row_post_profilephoto); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent ComplaintDetailsActivity = new Intent(mContext, com.example.te_lord.Activities.ComplaintDetailsActivity.class); int position = getAdapterPosition(); ComplaintDetailsActivity.putExtra("title",mData.get(position).getTitle()); ComplaintDetailsActivity.putExtra("complaintImage",mData.get(position).getPicture()); ComplaintDetailsActivity.putExtra("description",mData.get(position).getDesc()); ComplaintDetailsActivity.putExtra("complaintKey",mData.get(position).getComplaintKey()); ComplaintDetailsActivity.putExtra("userPhoto",mData.get(position).getUserPhoto()); long timestamp = (long) mData.get(position).getTimeStamp(); ComplaintDetailsActivity.putExtra("postDate", timestamp); mContext.startActivity(ComplaintDetailsActivity); } }); } } }
UTF-8
Java
3,178
java
ComplaintAdapter.java
Java
[]
null
[]
package com.example.te_lord.Adapters; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; 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.TextView; import com.bumptech.glide.Glide; import com.example.te_lord.Activities.ComplaintDetailsActivity; import com.example.te_lord_landlord.Models.Complaint; import com.example.te_lord.R; import java.util.List; public class ComplaintAdapter extends RecyclerView.Adapter <ComplaintAdapter.MyViewHolder> { Context mContext; List<Complaint> mData; public ComplaintAdapter(Context mContext, List<Complaint> mData) { this.mContext = mContext; this.mData = mData; } @NonNull @Override public ComplaintAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View row = LayoutInflater.from(mContext).inflate(R.layout.row_post_item,parent,false); return new MyViewHolder(row); } @Override public void onBindViewHolder(@NonNull ComplaintAdapter.MyViewHolder myViewHolder, int position) { myViewHolder.tvTitle.setText(mData.get(position).getTitle()); Glide.with(mContext).load(mData.get(position).getPicture()).into(myViewHolder.imgPost); Glide.with(mContext).load(mData.get(position).getUserPhoto()).into(myViewHolder.imgProfilePhoto); } @Override public int getItemCount() { return mData.size(); } public class MyViewHolder extends RecyclerView.ViewHolder{ TextView tvTitle; ImageView imgPost; ImageView imgProfilePhoto; public MyViewHolder(@NonNull View itemView) { super(itemView); tvTitle = itemView.findViewById(R.id.row_complaint_title); imgPost = itemView.findViewById(R.id.row_post_img); imgProfilePhoto = itemView.findViewById(R.id.row_post_profilephoto); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent ComplaintDetailsActivity = new Intent(mContext, com.example.te_lord.Activities.ComplaintDetailsActivity.class); int position = getAdapterPosition(); ComplaintDetailsActivity.putExtra("title",mData.get(position).getTitle()); ComplaintDetailsActivity.putExtra("complaintImage",mData.get(position).getPicture()); ComplaintDetailsActivity.putExtra("description",mData.get(position).getDesc()); ComplaintDetailsActivity.putExtra("complaintKey",mData.get(position).getComplaintKey()); ComplaintDetailsActivity.putExtra("userPhoto",mData.get(position).getUserPhoto()); long timestamp = (long) mData.get(position).getTimeStamp(); ComplaintDetailsActivity.putExtra("postDate", timestamp); mContext.startActivity(ComplaintDetailsActivity); } }); } } }
3,178
0.688169
0.687854
83
37.277107
35.421154
138
false
false
0
0
0
0
0
0
0.662651
false
false
14
176f04f27ee8d576e3bd964c02151686d848b51a
2,989,297,278,920
8db3eafd0914b0a38adcf3cb7431f4755b12b3ea
/gui/adapter/PersonnelTableMouseAdapter.java
516f89da1dfa19bd817b2380c5ccaf979d706149
[]
no_license
genveir/MekHQ
https://github.com/genveir/MekHQ
e708c1eeb9ea633b9c429390425dc85b9d00066e
1a3a01e51ae4111da76300b71715fec8964b8e60
refs/heads/master
2021-01-01T06:00:26.716000
2015-05-06T16:36:00
2015-05-06T16:36:00
35,021,327
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mekhq.gui.adapter; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Enumeration; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.UUID; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.event.MouseInputAdapter; import megamek.common.Aero; import megamek.common.BattleArmor; import megamek.common.Crew; import megamek.common.Infantry; import megamek.common.Mounted; import megamek.common.Tank; import megamek.common.options.IOption; import megamek.common.options.PilotOptions; import mekhq.Utilities; import mekhq.campaign.Kill; import mekhq.campaign.LogEntry; import mekhq.campaign.personnel.Injury; import mekhq.campaign.personnel.Person; import mekhq.campaign.personnel.Rank; import mekhq.campaign.personnel.Ranks; import mekhq.campaign.personnel.SkillType; import mekhq.campaign.personnel.SpecialAbility; import mekhq.campaign.unit.Unit; import mekhq.gui.CampaignGUI; import mekhq.gui.MenuScroller; import mekhq.gui.dialog.CustomizePersonDialog; import mekhq.gui.dialog.EditKillLogDialog; import mekhq.gui.dialog.EditLogEntryDialog; import mekhq.gui.dialog.EditPersonnelInjuriesDialog; import mekhq.gui.dialog.EditPersonnelLogDialog; import mekhq.gui.dialog.KillDialog; import mekhq.gui.dialog.PopupValueChoiceDialog; import mekhq.gui.dialog.PortraitChoiceDialog; import mekhq.gui.dialog.RetirementDefectionDialog; import mekhq.gui.dialog.TextAreaDialog; import mekhq.gui.tab.PersonnelTab; import mekhq.gui.utilities.StaticChecks; public class PersonnelTableMouseAdapter extends MouseInputAdapter implements ActionListener { private CampaignGUI gui; public PersonnelTableMouseAdapter(CampaignGUI gui) { super(); this.gui = gui; } public PersonnelTableMouseAdapter() { super(); } public void actionPerformed(ActionEvent action) { StringTokenizer st = new StringTokenizer(action.getActionCommand(), "|"); String command = st.nextToken(); int row = gui.getPersonnelTable().getSelectedRow(); if (row < 0) { return; } Person selectedPerson = gui.getPersonnelModel().getPerson(gui.getPersonnelTable() .convertRowIndexToModel(row)); int[] rows = gui.getPersonnelTable().getSelectedRows(); Person[] people = new Person[rows.length]; for (int i = 0; i < rows.length; i++) { people[i] = gui.getPersonnelModel().getPerson(gui.getPersonnelTable() .convertRowIndexToModel(rows[i])); } if (command.startsWith("RANKSYSTEM")) { int system = Integer.parseInt(st.nextToken()); for (Person person : people) { person.setRankSystem(system); } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); } else if (command.startsWith("RANK")) { int rank = Integer.parseInt(st.nextToken()); int level = 0; // Check to see if we added a rank level... if (st.hasMoreTokens()) { level = Integer.parseInt(st.nextToken()); } for (Person person : people) { gui.getCampaign().changeRank(person, rank, level, true); } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.startsWith("MD_RANK")) { int md_rank = Integer.parseInt(st.nextToken()); for (Person person : people) { person.setManeiDominiRank(md_rank); } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.startsWith("MD_CLASS")) { int md_class = Integer.parseInt(st.nextToken()); for (Person person : people) { person.setManeiDominiClass(md_class); } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.startsWith("DESIG_PRI")) { int designation = Integer.parseInt(st.nextToken()); for (Person person : people) { person.setPrimaryDesignator(designation); } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.startsWith("DESIG_SEC")) { int designation = Integer.parseInt(st.nextToken()); for (Person person : people) { person.setSecondaryDesignator(designation); } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("PROLE")) { int role = Integer.parseInt(st.nextToken()); for (Person person : people) { person.setPrimaryRole(role); gui.getCampaign().personUpdated(person); } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("SROLE")) { int role = Integer.parseInt(st.nextToken()); for (Person person : people) { person.setSecondaryRole(role); gui.getCampaign().personUpdated(person); } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("REMOVE_UNIT")) { for (Person person : people) { Unit u = gui.getCampaign().getUnit(person.getUnitId()); if (null != u) { u.remove(person, true); u.resetEngineerOrTech(); u.runDiagnostic(); } // check for tech unit assignments if (!person.getTechUnitIDs().isEmpty()) { // I need to create a new array list to avoid concurrent // problems ArrayList<UUID> temp = new ArrayList<UUID>(); for (UUID i : person.getTechUnitIDs()) { temp.add(i); } for (UUID i : temp) { u = gui.getCampaign().getUnit(i); if (null != u) { u.remove(person, true); u.resetEngineerOrTech(); u.runDiagnostic(); } } } } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("ADD_PILOT")) { UUID selected = UUID.fromString(st.nextToken()); Unit u = gui.getCampaign().getUnit(selected); Unit oldUnit = gui.getCampaign() .getUnit(selectedPerson.getUnitId()); if (null != oldUnit) { oldUnit.remove(selectedPerson, true); } if (null != u) { u.addPilotOrSoldier(selectedPerson); } u.resetPilotAndEntity(); u.runDiagnostic(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("ADD_SOLDIER")) { UUID selected = UUID.fromString(st.nextToken()); Unit u = gui.getCampaign().getUnit(selected); if (null != u) { for (Person p : people) { if (u.canTakeMoreGunners()) { Unit oldUnit = gui.getCampaign().getUnit(p.getUnitId()); if (null != oldUnit) { oldUnit.remove(p, true); } u.addPilotOrSoldier(p); } } } u.resetPilotAndEntity(); u.runDiagnostic(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("ADD_DRIVER")) { UUID selected = UUID.fromString(st.nextToken()); Unit u = gui.getCampaign().getUnit(selected); Unit oldUnit = gui.getCampaign() .getUnit(selectedPerson.getUnitId()); if (null != oldUnit) { oldUnit.remove(selectedPerson, true); } if (null != u) { u.addDriver(selectedPerson); } u.resetPilotAndEntity(); u.runDiagnostic(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("ADD_VESSEL_PILOT")) { UUID selected = UUID.fromString(st.nextToken()); Unit u = gui.getCampaign().getUnit(selected); if (null != u) { for (Person p : people) { if (u.canTakeMoreDrivers()) { Unit oldUnit = gui.getCampaign().getUnit(p.getUnitId()); if (null != oldUnit) { oldUnit.remove(p, true); } u.addDriver(p); } } } u.resetPilotAndEntity(); u.runDiagnostic(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("ADD_GUNNER")) { UUID selected = UUID.fromString(st.nextToken()); Unit u = gui.getCampaign().getUnit(selected); if (null != u) { for (Person p : people) { if (u.canTakeMoreGunners()) { Unit oldUnit = gui.getCampaign().getUnit(p.getUnitId()); if (null != oldUnit) { oldUnit.remove(p, true); } u.addGunner(p); } } } u.resetPilotAndEntity(); u.runDiagnostic(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("ADD_CREW")) { UUID selected = UUID.fromString(st.nextToken()); Unit u = gui.getCampaign().getUnit(selected); if (null != u) { for (Person p : people) { if (u.canTakeMoreVesselCrew()) { Unit oldUnit = gui.getCampaign().getUnit(p.getUnitId()); if (null != oldUnit) { oldUnit.remove(p, true); } u.addVesselCrew(p); } } } u.resetPilotAndEntity(); u.runDiagnostic(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("ADD_NAV")) { UUID selected = UUID.fromString(st.nextToken()); Unit u = gui.getCampaign().getUnit(selected); if (null != u) { for (Person p : people) { if (u.canTakeNavigator()) { Unit oldUnit = gui.getCampaign().getUnit(p.getUnitId()); if (null != oldUnit) { oldUnit.remove(p, true); } u.setNavigator(p); } } } u.resetPilotAndEntity(); u.runDiagnostic(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("ADD_TECH")) { UUID selected = UUID.fromString(st.nextToken()); Unit u = gui.getCampaign().getUnit(selected); if (null != u) { if (u.canTakeTech()) { u.setTech(selectedPerson); } } u.resetPilotAndEntity(); u.runDiagnostic(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("REMOVE_SPOUSE")) { selectedPerson.getSpouse().addLogEntry(gui.getCampaign().getDate(), "Divorced from " + selectedPerson.getFullName()); selectedPerson.addLogEntry(gui.getCampaign().getDate(), "Divorced from " + selectedPerson.getSpouse().getFullName()); selectedPerson.getSpouse().setSpouseID(null); selectedPerson.setSpouseID(null); gui.refreshPersonnelList(); } else if (command.contains("SPOUSE")) { Person spouse = gui.getCampaign().getPerson( UUID.fromString(st.nextToken())); spouse.setSpouseID(selectedPerson.getId()); spouse.addLogEntry(gui.getCampaign().getDate(), "Marries " + selectedPerson.getFullName()); selectedPerson.setSpouseID(spouse.getId()); selectedPerson.addLogEntry(gui.getCampaign().getDate(), "Marries " + spouse.getFullName()); gui.refreshPersonnelList(); } else if (command.contains("IMPROVE")) { String type = st.nextToken(); int cost = Integer.parseInt(st.nextToken()); int oldExpLevel = selectedPerson.getExperienceLevel(false); selectedPerson.improveSkill(type); gui.getCampaign().personUpdated(selectedPerson); selectedPerson.setXp(selectedPerson.getXp() - cost); gui.getCampaign().addReport( selectedPerson.getHyperlinkedName() + " improved " + type + "!"); if (gui.getCampaign().getCampaignOptions().getUseAtB()) { if (selectedPerson.getPrimaryRole() > Person.T_NONE && selectedPerson.getPrimaryRole() <= Person.T_CONV_PILOT && selectedPerson.getExperienceLevel(false) > oldExpLevel && oldExpLevel >= SkillType.EXP_REGULAR) { String spa = gui.getCampaign() .rollSPA(selectedPerson.getPrimaryRole(), selectedPerson); if (null == spa) { if (gui.getCampaign().getCampaignOptions().useEdge()) { selectedPerson.acquireAbility( PilotOptions.EDGE_ADVANTAGES, "edge", selectedPerson.getEdge() + 1); gui.getCampaign().addReport( selectedPerson.getHyperlinkedName() + " gained edge point!"); } } else { gui.getCampaign().addReport( selectedPerson.getHyperlinkedName() + " gained " + SpecialAbility .getDisplayName(spa) + "!"); } } } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshReport(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("ABILITY")) { String selected = st.nextToken(); int cost = Integer.parseInt(st.nextToken()); selectedPerson.acquireAbility(PilotOptions.LVL3_ADVANTAGES, selected, true); gui.getCampaign().personUpdated(selectedPerson); selectedPerson.setXp(selectedPerson.getXp() - cost); // TODO: add gui.getCampaign() report gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshReport(); gui.refreshOverview(); } else if (command.contains("WSPECIALIST")) { String selected = st.nextToken(); int cost = Integer.parseInt(st.nextToken()); selectedPerson.acquireAbility(PilotOptions.LVL3_ADVANTAGES, "weapon_specialist", selected); gui.getCampaign().personUpdated(selectedPerson); selectedPerson.setXp(selectedPerson.getXp() - cost); // TODO: add campaign report gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshReport(); gui.refreshOverview(); } else if (command.contains("SPECIALIST")) { String selected = st.nextToken(); int cost = Integer.parseInt(st.nextToken()); selectedPerson.acquireAbility(PilotOptions.LVL3_ADVANTAGES, "specialist", selected); gui.getCampaign().personUpdated(selectedPerson); selectedPerson.setXp(selectedPerson.getXp() - cost); // TODO: add campaign report gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshReport(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("STATUS")) { int selected = Integer.parseInt(st.nextToken()); for (Person person : people) { if (selected == Person.S_ACTIVE || (0 == JOptionPane.showConfirmDialog(null, "Do you really want to change the status of " + person.getFullTitle() + " to a non-active status?", "KIA?", JOptionPane.YES_NO_OPTION))) { gui.getCampaign().changeStatus(person, selected); } } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.filterPersonnel(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshReport(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("PRISONER_STATUS")) { int selected = Integer.parseInt(st.nextToken()); for (Person person : people) { gui.getCampaign().changePrisonerStatus(person, selected); } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.filterPersonnel(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshReport(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("EDGE")) { String trigger = st.nextToken(); if (people.length > 1) { boolean status = Boolean.parseBoolean(st.nextToken()); for (Person person : people) { person.setEdgeTrigger(trigger, status); gui.getCampaign().personUpdated(person); } } else { selectedPerson.changeEdgeTrigger(trigger); gui.getCampaign().personUpdated(selectedPerson); } gui.refreshPersonnelList(); gui.refreshPersonnelView(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("REMOVE")) { for (Person person : people) { if (0 == JOptionPane.showConfirmDialog( null, "Do you really want to remove " + person.getFullTitle() + "?", "Remove?", JOptionPane.YES_NO_OPTION)) { gui.getCampaign().removePerson(person.getId()); } } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); gui.refreshReport(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("SACK")) { boolean showDialog = false; ArrayList<UUID> toRemove = new ArrayList<UUID>(); for (Person person : people) { if (gui.getCampaign().getRetirementDefectionTracker() .removeFromCampaign( person, false, gui.getCampaign().getCampaignOptions() .getUseShareSystem() ? person .getNumShares(gui.getCampaign() .getCampaignOptions() .getSharesForAll()) : 0, gui.getCampaign(), null)) { showDialog = true; } else { toRemove.add(person.getId()); } } if (showDialog) { RetirementDefectionDialog rdd = new RetirementDefectionDialog( gui, null, false); rdd.setVisible(true); if (rdd.wasAborted() || !gui.getCampaign().applyRetirement(rdd.totalPayout(), rdd.getUnitAssignments())) { for (Person person : people) { gui.getCampaign().getRetirementDefectionTracker() .removePayout(person); } } else { for (UUID id : toRemove) { gui.getCampaign().removePerson(id); } } } else { if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog( null, "Do you really want to remove " + ((people.length > 1)?"personnel?": people[0].getFullTitle() + "?"), "Remove?", JOptionPane.YES_NO_OPTION)) { for (Person person : people) { gui.getCampaign().removePerson(person.getId()); } } } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); gui.refreshReport(); } else if (command.equalsIgnoreCase("EDIT")) { CustomizePersonDialog npd = new CustomizePersonDialog( gui.getFrame(), true, selectedPerson, gui.getCampaign()); npd.setVisible(true); gui.getCampaign().personUpdated(selectedPerson); gui.refreshPatientList(); gui.refreshDoctorsList(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("HEAL")) { for (Person person : people) { person.setHits(0); person.setDoctorId(null, gui.getCampaign().getCampaignOptions() .getNaturalHealingWaitingPeriod()); } gui.getCampaign().personUpdated(selectedPerson); gui.refreshPatientList(); gui.refreshDoctorsList(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("PORTRAIT")) { PortraitChoiceDialog pcd = new PortraitChoiceDialog(gui.getFrame(), true, selectedPerson.getPortraitCategory(), selectedPerson.getPortraitFileName(), gui.getIconPackage() .getPortraits()); pcd.setVisible(true); selectedPerson.setPortraitCategory(pcd.getCategory()); selectedPerson.setPortraitFileName(pcd.getFileName()); gui.getCampaign().personUpdated(selectedPerson); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("BIOGRAPHY")) { TextAreaDialog tad = new TextAreaDialog(gui.getFrame(), true, "Edit Biography", selectedPerson.getBiography()); tad.setVisible(true); if (tad.wasChanged()) { selectedPerson.setBiography(tad.getText()); } gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("XP_ADD")) { for (Person person : people) { person.setXp(person.getXp() + 1); } gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("XP_SET")) { PopupValueChoiceDialog pvcd = new PopupValueChoiceDialog( gui.getFrame(), true, "XP", selectedPerson.getXp(), 0, Math.max(selectedPerson.getXp() + 10, 100)); pvcd.setVisible(true); if (pvcd.getValue() < 0) { return; } int i = pvcd.getValue(); for (Person person : people) { person.setXp(i); } gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("EDGE_SET")) { PopupValueChoiceDialog pvcd = new PopupValueChoiceDialog( gui.getFrame(), true, "Edge", selectedPerson.getEdge(), 0, 10); pvcd.setVisible(true); if (pvcd.getValue() < 0) { return; } int i = pvcd.getValue(); for (Person person : people) { person.setEdge(i); gui.getCampaign().personUpdated(person); } gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("KILL")) { KillDialog nkd; if (people.length > 1) { nkd = new KillDialog( gui.getFrame(), true, new Kill( null, "?", gui.getCampaign().getUnit( selectedPerson.getUnitId()) != null ? gui.getCampaign() .getUnit(selectedPerson.getUnitId()) .getName() : "Bare Hands", gui.getCampaign() .getDate()), "Crew"); } else { nkd = new KillDialog( gui.getFrame(), true, new Kill( selectedPerson.getId(), "?", gui.getCampaign().getUnit( selectedPerson.getUnitId()) != null ? gui.getCampaign() .getUnit(selectedPerson.getUnitId()) .getName() : "Bare Hands", gui.getCampaign() .getDate()), selectedPerson.getFullName()); } nkd.setVisible(true); if (!nkd.wasCancelled()) { Kill kill = nkd.getKill(); if (people.length > 1) { for (Person person : people) { Kill k = kill.clone(); k.setPilotId(person.getId()); gui.getCampaign().addKill(k); } } else { gui.getCampaign().addKill(kill); } } gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("KILL_LOG")) { EditKillLogDialog ekld = new EditKillLogDialog(gui.getFrame(), true, gui.getCampaign(), selectedPerson); ekld.setVisible(true); gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("LOG")) { EditPersonnelLogDialog epld = new EditPersonnelLogDialog( gui.getFrame(), true, gui.getCampaign(), selectedPerson); epld.setVisible(true); gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("LOG_SINGLE")) { EditLogEntryDialog eeld = new EditLogEntryDialog(gui.getFrame(), true, new LogEntry(gui.getCampaign().getDate(), "")); eeld.setVisible(true); LogEntry entry = eeld.getEntry(); if (null != entry) { for (Person person : people) { person.addLogEntry(entry.clone()); } } gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("COMMANDER")) { selectedPerson.setCommander(!selectedPerson.isCommander()); if (selectedPerson.isCommander()) { for (Person p : gui.getCampaign().getPersonnel()) { if (p.isCommander() && !p.getId().equals(selectedPerson.getId())) { p.setCommander(false); gui.getCampaign() .addReport( p.getHyperlinkedFullTitle() + " has been removed as the overall unit commander."); gui.getCampaign().personUpdated(p); } } gui.getCampaign() .addReport( selectedPerson.getHyperlinkedFullTitle() + " has been set as the overall unit commander."); gui.getCampaign().personUpdated(selectedPerson); } gui.refreshReport(); } else if (command.equalsIgnoreCase("DEPENDENT")) { if (people.length > 1) { boolean status = Boolean.parseBoolean(st.nextToken()); for (Person person : people) { person.setDependent(status); gui.getCampaign().personUpdated(person); } } else { selectedPerson.setDependent(!selectedPerson.isDependent()); gui.getCampaign().personUpdated(selectedPerson); } } else if (command.equalsIgnoreCase("CALLSIGN")) { String s = (String) JOptionPane.showInputDialog(gui.getFrame(), "Enter new callsign", "Edit Callsign", JOptionPane.PLAIN_MESSAGE, null, null, selectedPerson.getCallsign()); if (null != s) { selectedPerson.setCallsign(s); } gui.getCampaign().personUpdated(selectedPerson); gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("CLEAR_INJURIES")) { for (Person person : people) { person.clearInjuries(); Unit u = gui.getCampaign().getUnit(person.getUnitId()); if (null != u) { u.resetPilotAndEntity(); } } gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.contains("REMOVE_INJURY")) { String sel = command.split(":")[1]; Injury toRemove = null; for (Injury i : selectedPerson.getInjuries()) { if (i.getUUIDAsString().equals(sel)) { toRemove = i; break; } } if (toRemove != null) { selectedPerson.removeInjury(toRemove); } Unit u = gui.getCampaign().getUnit(selectedPerson.getUnitId()); if (null != u) { u.resetPilotAndEntity(); } gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("EDIT_INJURIES")) { EditPersonnelInjuriesDialog epid = new EditPersonnelInjuriesDialog( gui.getFrame(), true, gui.getCampaign(), selectedPerson); epid.setVisible(true); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("BLOODNAME")) { for (Person p : people) { if (!p.isClanner()) { continue; } gui.getCampaign() .checkBloodnameAdd(p, p.getPrimaryRole(), true); } gui.getCampaign().personUpdated(selectedPerson); gui.refreshPatientList(); gui.refreshDoctorsList(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); } else if (command.equalsIgnoreCase("SALARY")) { PopupValueChoiceDialog pcvd = new PopupValueChoiceDialog(gui.getFrame(), true, "Change Salary (-1 to remove custom salary)", selectedPerson.getSalary(), -1, 100000); pcvd.setVisible(true); int salary = pcvd.getValue(); if (salary < -1) { return; } for (Person person : people) { person.setSalary(salary); } gui.refreshPersonnelList(); } } @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { if ((gui.getSplitPersonnel().getSize().width - gui.getSplitPersonnel().getDividerLocation() + gui.getSplitPersonnel() .getDividerSize()) < PersonnelTab.PERSONNEL_VIEW_WIDTH) { // expand gui.getSplitPersonnel().resetToPreferredSizes(); } else { // collapse gui.getSplitPersonnel().setDividerLocation(1.0); } } } @Override public void mousePressed(MouseEvent e) { maybeShowPopup(e); } @Override public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { JPopupMenu popup = new JPopupMenu(); if (e.isPopupTrigger()) { if (gui.getPersonnelTable().getSelectedRowCount() == 0) { return; } int row = gui.getPersonnelTable().getSelectedRow(); boolean oneSelected = gui.getPersonnelTable().getSelectedRowCount() == 1; Person person = gui.getPersonnelModel().getPerson(gui.getPersonnelTable() .convertRowIndexToModel(row)); JMenuItem menuItem = null; JMenu menu = null; JMenu submenu = null; JCheckBoxMenuItem cbMenuItem = null; Person[] selected = gui.getSelectedPeople(); // **lets fill the pop up menu**// if (StaticChecks.areAllEligible(selected)) { menu = new JMenu("Change Rank"); Ranks ranks = person.getRanks(); for (int rankOrder = 0; rankOrder < Ranks.RC_NUM; rankOrder++) { Rank rank = ranks.getAllRanks().get(rankOrder); int profession = person.getProfession(); // Empty professions need swapped before the // continuation while (ranks.isEmptyProfession(profession) && profession != Ranks.RPROF_MW) { profession = ranks .getAlternateProfession(profession); } if (rank.getName(profession).equals("-")) { continue; } // re-route through any profession redirections, // starting with the empty profession check while (rank.getName(profession).startsWith("--") && profession != Ranks.RPROF_MW) { if (rank.getName(profession).equals("--")) { profession = ranks .getAlternateProfession(profession); } else if (rank.getName(profession) .startsWith("--")) { profession = ranks.getAlternateProfession(rank .getName(profession)); } } if (rank.getRankLevels(profession) > 0) { submenu = new JMenu(rank.getName(profession)); for (int level = 0; level <= rank .getRankLevels(profession); level++) { cbMenuItem = new JCheckBoxMenuItem( rank.getName(profession) + Utilities .getRomanNumeralsFromArabicNumber( level, true)); cbMenuItem.setActionCommand("RANK|" + rankOrder + "|" + level); if (person.getRankNumeric() == rankOrder && person.getRankLevel() == level) { cbMenuItem.setSelected(true); } cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); submenu.add(cbMenuItem); } if (submenu.getItemCount() > 20) { MenuScroller.setScrollerFor(submenu, 20); } menu.add(submenu); } else { cbMenuItem = new JCheckBoxMenuItem( rank.getName(profession)); cbMenuItem.setActionCommand("RANK|" + rankOrder); if (person.getRankNumeric() == rankOrder) { cbMenuItem.setSelected(true); } cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); menu.add(cbMenuItem); } } if (menu.getItemCount() > 20) { MenuScroller.setScrollerFor(menu, 20); } popup.add(menu); } menu = new JMenu("Change Rank System"); // First allow them to revert to the campaign system cbMenuItem = new JCheckBoxMenuItem("Use Campaign Rank System"); cbMenuItem.setActionCommand("RANKSYSTEM|" + "-1"); cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); menu.add(cbMenuItem); for (int system = 0; system < Ranks.RS_NUM; system++) { if (system == Ranks.RS_CUSTOM) { continue; } cbMenuItem = new JCheckBoxMenuItem( Ranks.getRankSystemName(system)); cbMenuItem.setActionCommand("RANKSYSTEM|" + system); cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); if (system == person.getRanks().getRankSystem()) { cbMenuItem.setSelected(true); } menu.add(cbMenuItem); } if (menu.getItemCount() > 20) { MenuScroller.setScrollerFor(menu, 20); } popup.add(menu); if (StaticChecks.areAllWoB(selected)) { // MD Ranks menu = new JMenu("Change Manei Domini Rank"); for (int i = Rank.MD_RANK_NONE; i < Rank.MD_RANK_NUM; i++) { cbMenuItem = new JCheckBoxMenuItem( Rank.getManeiDominiRankName(i)); cbMenuItem.setActionCommand("MD_RANK|" + i); cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); if (i == person.getManeiDominiRank()) { cbMenuItem.setSelected(true); } menu.add(cbMenuItem); } if (menu.getItemCount() > 20) { MenuScroller.setScrollerFor(menu, 20); } popup.add(menu); // MD Classes menu = new JMenu("Change Manei Domini Class"); for (int i = Person.MD_NONE; i < Person.MD_NUM; i++) { cbMenuItem = new JCheckBoxMenuItem( Person.getManeiDominiClassNames(i, Ranks.RS_WOB)); cbMenuItem.setActionCommand("MD_CLASS|" + i); cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); if (i == person.getManeiDominiClass()) { cbMenuItem.setSelected(true); } menu.add(cbMenuItem); } if (menu.getItemCount() > 20) { MenuScroller.setScrollerFor(menu, 20); } popup.add(menu); } if (StaticChecks.areAllWoBOrComstar(selected)) { menu = new JMenu("Change Primary Designation"); for (int i = Person.DESIG_NONE; i < Person.DESIG_NUM; i++) { cbMenuItem = new JCheckBoxMenuItem( Person.parseDesignator(i)); cbMenuItem.setActionCommand("DESIG_PRI|" + i); cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); if (i == person.getPrimaryDesignator()) { cbMenuItem.setSelected(true); } menu.add(cbMenuItem); } if (menu.getItemCount() > 20) { MenuScroller.setScrollerFor(menu, 20); } popup.add(menu); menu = new JMenu("Change Secondary Designation"); for (int i = Person.DESIG_NONE; i < Person.DESIG_NUM; i++) { cbMenuItem = new JCheckBoxMenuItem( Person.parseDesignator(i)); cbMenuItem.setActionCommand("DESIG_SEC|" + i); cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); if (i == person.getSecondaryDesignator()) { cbMenuItem.setSelected(true); } menu.add(cbMenuItem); } if (menu.getItemCount() > 20) { MenuScroller.setScrollerFor(menu, 20); } popup.add(menu); } menu = new JMenu("Change Status"); for (int s = 0; s < Person.S_NUM; s++) { cbMenuItem = new JCheckBoxMenuItem(Person.getStatusName(s)); if (person.getStatus() == s) { cbMenuItem.setSelected(true); } cbMenuItem.setActionCommand("STATUS|" + s); cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); menu.add(cbMenuItem); } popup.add(menu); menu = new JMenu("Change Prisoner Status"); for (int s = 0; s < Person.PRISONER_NUM; s++) { cbMenuItem = new JCheckBoxMenuItem( Person.getPrisonerStatusName(s)); if (person.getPrisonerStatus() == s) { cbMenuItem.setSelected(true); } cbMenuItem.setActionCommand("PRISONER_STATUS|" + s); cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); menu.add(cbMenuItem); } popup.add(menu); menu = new JMenu("Change Primary Role"); for (int i = Person.T_MECHWARRIOR; i < Person.T_NUM; i++) { if (person.canPerformRole(i) && person.getSecondaryRole() != i) { cbMenuItem = new JCheckBoxMenuItem(Person.getRoleDesc( i, gui.getCampaign().getFaction().isClan())); cbMenuItem.setActionCommand("PROLE|" + i); if (person.getPrimaryRole() == i) { cbMenuItem.setSelected(true); } cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); menu.add(cbMenuItem); } } if (menu.getItemCount() > 20) { MenuScroller.setScrollerFor(menu, 20); } popup.add(menu); menu = new JMenu("Change Secondary Role"); for (int i = 0; i < Person.T_NUM; i++) { if (i == Person.T_NONE || (person.canPerformRole(i) && person .getPrimaryRole() != i)) { // you cant be an astech if you are a tech, or a medic // if you are a doctor if (person.isTechPrimary() && i == Person.T_ASTECH) { continue; } if (person.getPrimaryRole() == Person.T_DOCTOR && i == Person.T_MEDIC) { continue; } cbMenuItem = new JCheckBoxMenuItem(Person.getRoleDesc( i, gui.getCampaign().getFaction().isClan())); cbMenuItem.setActionCommand("SROLE|" + i); if (person.getSecondaryRole() == i) { cbMenuItem.setSelected(true); } cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); menu.add(cbMenuItem); } } if (menu.getItemCount() > 20) { MenuScroller.setScrollerFor(menu, 20); } popup.add(menu); // Bloodnames if (StaticChecks.areAllClanEligible(selected)) { menuItem = new JMenuItem("Give Random Bloodname"); menuItem.setActionCommand("BLOODNAME"); menuItem.addActionListener(this); menuItem.setEnabled(StaticChecks.areAllActive(selected)); popup.add(menuItem); } // change salary if (gui.getCampaign().getCampaignOptions().payForSalaries()) { menuItem = new JMenuItem("Set Salary..."); menuItem.setActionCommand("SALARY"); menuItem.addActionListener(this); menuItem.setEnabled(StaticChecks.areAllActive(selected)); popup.add(menuItem); } // switch pilot menu = new JMenu("Assign to Unit"); JMenu pilotMenu = new JMenu("As Pilot"); JMenu crewMenu = new JMenu("As Crewmember"); JMenu driverMenu = new JMenu("As Driver"); JMenu gunnerMenu = new JMenu("As Gunner"); JMenu soldierMenu = new JMenu("As Soldier"); JMenu techMenu = new JMenu("As Tech"); JMenu navMenu = new JMenu("As Navigator"); /* * if(!person.isAssigned()) { cbMenuItem.setSelected(true); } */ if (oneSelected && person.isActive() && !(person.isPrisoner() || person.isBondsman())) { for (Unit unit : gui.getCampaign().getUnits()) { if (!unit.isAvailable()) { continue; } if (unit.usesSoloPilot()) { if (unit.canTakeMoreDrivers() && person.canDrive(unit.getEntity()) && person.canGun(unit.getEntity())) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_PILOT|" + unit.getId()); cbMenuItem.addActionListener(this); pilotMenu.add(cbMenuItem); } } else if (unit.usesSoldiers()) { if (unit.canTakeMoreGunners() && person.canGun(unit.getEntity())) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_SOLDIER|" + unit.getId()); cbMenuItem.addActionListener(this); soldierMenu.add(cbMenuItem); } } else { if (unit.canTakeMoreDrivers() && person.canDrive(unit.getEntity())) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_DRIVER|" + unit.getId()); cbMenuItem.addActionListener(this); if (unit.getEntity() instanceof Aero) { pilotMenu.add(cbMenuItem); } else { driverMenu.add(cbMenuItem); } } if (unit.canTakeMoreGunners() && person.canGun(unit.getEntity())) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_GUNNER|" + unit.getId()); cbMenuItem.addActionListener(this); gunnerMenu.add(cbMenuItem); } if (unit.canTakeMoreVesselCrew() && person.hasSkill(SkillType.S_TECH_VESSEL)) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_CREW|" + unit.getId()); cbMenuItem.addActionListener(this); crewMenu.add(cbMenuItem); } if (unit.canTakeNavigator() && person.hasSkill(SkillType.S_NAV)) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_NAV|" + unit.getId()); cbMenuItem.addActionListener(this); navMenu.add(cbMenuItem); } } if (unit.canTakeTech() && person.canTech(unit.getEntity()) && (person.getMaintenanceTimeUsing() + unit .getMaintenanceTime()) <= 480) { cbMenuItem = new JCheckBoxMenuItem(unit.getName() + " (" + unit.getMaintenanceTime() + " minutes/day)"); // TODO: check the box cbMenuItem.setActionCommand("ADD_TECH|" + unit.getId()); cbMenuItem.addActionListener(this); techMenu.add(cbMenuItem); } } if (pilotMenu.getItemCount() > 0) { menu.add(pilotMenu); if (pilotMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(pilotMenu, 20); } } if (driverMenu.getItemCount() > 0) { menu.add(driverMenu); if (driverMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(driverMenu, 20); } } if (crewMenu.getItemCount() > 0) { menu.add(crewMenu); if (crewMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(crewMenu, 20); } } if (navMenu.getItemCount() > 0) { menu.add(navMenu); if (navMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(navMenu, 20); } } if (gunnerMenu.getItemCount() > 0) { menu.add(gunnerMenu); if (gunnerMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(gunnerMenu, 20); } } if (soldierMenu.getItemCount() > 0) { menu.add(soldierMenu); if (soldierMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(soldierMenu, 20); } } if (techMenu.getItemCount() > 0) { menu.add(techMenu); if (techMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(techMenu, 20); } } menu.setEnabled(!person.isDeployed()); popup.add(menu); } else if (StaticChecks.areAllActive(selected) && StaticChecks.areAllEligible(selected)) { for (Unit unit : gui.getCampaign().getUnits()) { if (!unit.isAvailable()) { continue; } if (StaticChecks.areAllInfantry(selected)) { if (!(unit.getEntity() instanceof Infantry) || unit.getEntity() instanceof BattleArmor) { continue; } if (unit.canTakeMoreGunners() && person.canGun(unit.getEntity())) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_SOLDIER|" + unit.getId()); cbMenuItem.addActionListener(this); soldierMenu.add(cbMenuItem); } } else if (StaticChecks.areAllBattleArmor(selected)) { if (!(unit.getEntity() instanceof BattleArmor)) { continue; } if (unit.canTakeMoreGunners() && person.canGun(unit.getEntity())) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_SOLDIER|" + unit.getId()); cbMenuItem.addActionListener(this); soldierMenu.add(cbMenuItem); } } else if (StaticChecks.areAllVeeGunners(selected)) { if (!(unit.getEntity() instanceof Tank)) { continue; } if (unit.canTakeMoreGunners() && person.canGun(unit.getEntity())) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_GUNNER|" + unit.getId()); cbMenuItem.addActionListener(this); gunnerMenu.add(cbMenuItem); } } else if (StaticChecks.areAllVesselGunners(selected)) { if (!(unit.getEntity() instanceof Aero)) { continue; } if (unit.canTakeMoreGunners() && person.canGun(unit.getEntity())) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_GUNNER|" + unit.getId()); cbMenuItem.addActionListener(this); gunnerMenu.add(cbMenuItem); } } else if (StaticChecks.areAllVesselCrew(selected)) { if (!(unit.getEntity() instanceof Aero)) { continue; } if (unit.canTakeMoreVesselCrew() && person.hasSkill(SkillType.S_TECH_VESSEL)) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_CREW|" + unit.getId()); cbMenuItem.addActionListener(this); crewMenu.add(cbMenuItem); } } else if (StaticChecks.areAllVesselPilots(selected)) { if (!(unit.getEntity() instanceof Aero)) { continue; } if (unit.canTakeMoreDrivers() && person.canDrive(unit.getEntity())) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_VESSEL_PILOT|" + unit.getId()); cbMenuItem.addActionListener(this); pilotMenu.add(cbMenuItem); } } else if (StaticChecks.areAllVesselNavigators(selected)) { if (!(unit.getEntity() instanceof Aero)) { continue; } if (unit.canTakeNavigator() && person.hasSkill(SkillType.S_NAV)) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_NAV|" + unit.getId()); cbMenuItem.addActionListener(this); navMenu.add(cbMenuItem); } } } if (soldierMenu.getItemCount() > 0) { menu.add(soldierMenu); if (soldierMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(soldierMenu, 20); } } if (pilotMenu.getItemCount() > 0) { menu.add(pilotMenu); if (pilotMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(pilotMenu, 20); } } if (driverMenu.getItemCount() > 0) { menu.add(driverMenu); if (driverMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(driverMenu, 20); } } if (crewMenu.getItemCount() > 0) { menu.add(crewMenu); if (crewMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(crewMenu, 20); } } if (navMenu.getItemCount() > 0) { menu.add(navMenu); if (navMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(navMenu, 20); } } if (gunnerMenu.getItemCount() > 0) { menu.add(gunnerMenu); if (gunnerMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(gunnerMenu, 20); } } if (soldierMenu.getItemCount() > 0) { menu.add(soldierMenu); if (soldierMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(soldierMenu, 20); } } menu.setEnabled(!person.isDeployed()); popup.add(menu); } cbMenuItem = new JCheckBoxMenuItem("None"); cbMenuItem.setActionCommand("REMOVE_UNIT|" + -1); cbMenuItem.addActionListener(this); menu.add(cbMenuItem); if (oneSelected && person.isActive()) { if (person.getAge(gui.getCampaign().getCalendar()) > 13 && person.getSpouseID() == null) { menu = new JMenu("Choose Spouse (Mate)"); for (Person ps : gui.getCampaign().getPersonnel()) { if (person.safeSpouse(ps)) { menuItem = new JMenuItem( ps.getFullName() + ", " + ps.getAge(gui.getCampaign() .getCalendar()) + ", " + ps.getRoleDesc()); menuItem.setActionCommand("SPOUSE|" + ps.getId().toString()); menuItem.addActionListener(this); menu.add(menuItem); } } if (menu.getItemCount() > 30) { MenuScroller.setScrollerFor(menu, 20); } popup.add(menu); } if (person.getSpouseID() != null) { menuItem = new JMenuItem("Remove Spouse"); menuItem.setActionCommand("REMOVE_SPOUSE"); menuItem.addActionListener(this); popup.add(menuItem); } menu = new JMenu("Spend XP"); JMenu currentMenu = new JMenu("Current Skills"); JMenu newMenu = new JMenu("New Skills"); for (int i = 0; i < SkillType.getSkillList().length; i++) { String type = SkillType.getSkillList()[i]; if (person.hasSkill(type)) { int cost = person.getSkill(type).getCostToImprove(); if (cost >= 0) { String costDesc = " (" + cost + "XP)"; menuItem = new JMenuItem(type + costDesc); menuItem.setActionCommand("IMPROVE|" + type + "|" + cost); menuItem.addActionListener(this); menuItem.setEnabled(person.getXp() >= cost); currentMenu.add(menuItem); } } else { int cost = SkillType.getType(type).getCost(0); if (cost >= 0) { String costDesc = " (" + cost + "XP)"; menuItem = new JMenuItem(type + costDesc); menuItem.setActionCommand("IMPROVE|" + type + "|" + cost); menuItem.addActionListener(this); menuItem.setEnabled(person.getXp() >= cost); newMenu.add(menuItem); } } } menu.add(currentMenu); menu.add(newMenu); if (gui.getCampaign().getCampaignOptions().useAbilities()) { JMenu abMenu = new JMenu("Special Abilities"); int cost = -1; String costDesc = ""; for (Enumeration<IOption> i = person .getOptions(PilotOptions.LVL3_ADVANTAGES); i .hasMoreElements();) { IOption ability = i.nextElement(); if (!ability.booleanValue()) { SpecialAbility spa = SpecialAbility .getAbility(ability.getName()); if (null == spa) { continue; } if (!spa.isEligible(person)) { continue; } cost = spa.getCost(); costDesc = " (" + cost + "XP)"; if (cost < 0) { costDesc = " (Not Possible)"; } if (ability.getName().equals( "weapon_specialist")) { Unit u = gui.getCampaign().getUnit( person.getUnitId()); if (null != u) { JMenu specialistMenu = new JMenu( "Weapon Specialist"); TreeSet<String> uniqueWeapons = new TreeSet<String>(); for (int j = 0; j < u.getEntity() .getWeaponList().size(); j++) { Mounted m = u.getEntity() .getWeaponList().get(j); uniqueWeapons.add(m.getName()); } for (String name : uniqueWeapons) { menuItem = new JMenuItem(name + costDesc); menuItem.setActionCommand("WSPECIALIST|" + name + "|" + cost); menuItem.addActionListener(this); menuItem.setEnabled(cost >= 0 && person.getXp() >= cost); specialistMenu.add(menuItem); } abMenu.add(specialistMenu); } } else if (ability.getName().equals( "specialist")) { JMenu specialistMenu = new JMenu( "Specialist"); menuItem = new JMenuItem("Laser Specialist" + costDesc); menuItem.setActionCommand("SPECIALIST|" + Crew.SPECIAL_LASER + "|" + cost); menuItem.addActionListener(this); menuItem.setEnabled(cost >= 0 && person.getXp() >= cost); specialistMenu.add(menuItem); menuItem = new JMenuItem( "Missile Specialist" + costDesc); menuItem.setActionCommand("SPECIALIST|" + Crew.SPECIAL_MISSILE + "|" + cost); menuItem.addActionListener(this); menuItem.setEnabled(cost >= 0 && person.getXp() >= cost); specialistMenu.add(menuItem); menuItem = new JMenuItem( "Ballistic Specialist" + costDesc); menuItem.setActionCommand("SPECIALIST|" + Crew.SPECIAL_BALLISTIC + "|" + cost); menuItem.addActionListener(this); menuItem.setEnabled(cost >= 0 && person.getXp() >= cost); specialistMenu.add(menuItem); abMenu.add(specialistMenu); } else { menuItem = new JMenuItem( ability.getDisplayableName() + costDesc); menuItem.setActionCommand("ABILITY|" + ability.getName() + "|" + cost); menuItem.addActionListener(this); menuItem.setEnabled(cost >= 0 && person.getXp() >= cost); abMenu.add(menuItem); } } } if (abMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(abMenu, 20); } menu.add(abMenu); } popup.add(menu); } if (oneSelected && person.isActive()) { if (gui.getCampaign().getCampaignOptions().useEdge()) { menu = new JMenu("Set Edge Triggers"); cbMenuItem = new JCheckBoxMenuItem("Head Hits"); cbMenuItem.setSelected(person.getOptions() .booleanOption("edge_when_headhit")); cbMenuItem.setActionCommand("EDGE|edge_when_headhit"); cbMenuItem.addActionListener(this); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem( "Through Armor Crits"); cbMenuItem.setSelected(person.getOptions() .booleanOption("edge_when_tac")); cbMenuItem.setActionCommand("EDGE|edge_when_tac"); cbMenuItem.addActionListener(this); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Fail KO check"); cbMenuItem.setSelected(person.getOptions() .booleanOption("edge_when_ko")); cbMenuItem.setActionCommand("EDGE|edge_when_ko"); cbMenuItem.addActionListener(this); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Ammo Explosion"); cbMenuItem.setSelected(person.getOptions() .booleanOption("edge_when_explosion")); cbMenuItem.setActionCommand("EDGE|edge_when_explosion"); cbMenuItem.addActionListener(this); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("MASC Failures"); cbMenuItem.setSelected(person.getOptions() .booleanOption("edge_when_masc_fails")); cbMenuItem .setActionCommand("EDGE|edge_when_masc_fails"); cbMenuItem.addActionListener(this); menu.add(cbMenuItem); popup.add(menu); } menu = new JMenu("Special Flags..."); cbMenuItem = new JCheckBoxMenuItem("Dependent"); cbMenuItem.setSelected(person.isDependent()); cbMenuItem.setActionCommand("DEPENDENT"); cbMenuItem.addActionListener(this); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Commander"); cbMenuItem.setSelected(person.isCommander()); cbMenuItem.setActionCommand("COMMANDER"); cbMenuItem.addActionListener(this); menu.add(cbMenuItem); popup.add(menu); } else if (StaticChecks.areAllActive(selected)) { if (gui.getCampaign().getCampaignOptions().useEdge()) { menu = new JMenu("Set Edge Triggers"); submenu = new JMenu("On"); menuItem = new JMenuItem("Head Hits"); menuItem.setActionCommand("EDGE|edge_when_headhit|true"); menuItem.addActionListener(this); submenu.add(menuItem); menuItem = new JMenuItem("Through Armor Crits"); menuItem.setActionCommand("EDGE|edge_when_tac|true"); menuItem.addActionListener(this); submenu.add(menuItem); menuItem = new JMenuItem("Fail KO check"); menuItem.setActionCommand("EDGE|edge_when_ko|true"); menuItem.addActionListener(this); submenu.add(menuItem); menuItem = new JMenuItem("Ammo Explosion"); menuItem.setActionCommand("EDGE|edge_when_explosion|true"); menuItem.addActionListener(this); submenu.add(menuItem); menuItem = new JMenuItem("MASC Failures"); menuItem.setActionCommand("EDGE|edge_when_masc_fails|true"); menuItem.addActionListener(this); submenu.add(menuItem); menu.add(submenu); submenu = new JMenu("Off"); menuItem = new JMenuItem("Head Hits"); menuItem.setActionCommand("EDGE|edge_when_headhit|false"); menuItem.addActionListener(this); submenu.add(menuItem); menuItem = new JMenuItem("Through Armor Crits"); menuItem.setActionCommand("EDGE|edge_when_tac|false"); menuItem.addActionListener(this); submenu.add(menuItem); menuItem = new JMenuItem("Fail KO check"); menuItem.setActionCommand("EDGE|edge_when_ko|false"); menuItem.addActionListener(this); submenu.add(menuItem); menuItem = new JMenuItem("Ammo Explosion"); menuItem.setActionCommand("EDGE|edge_when_explosion|false"); menuItem.addActionListener(this); submenu.add(menuItem); menuItem = new JMenuItem("MASC Failures"); menuItem.setActionCommand("EDGE|edge_when_masc_fails|false"); menuItem.addActionListener(this); submenu.add(menuItem); menu.add(submenu); popup.add(menu); } menu = new JMenu("Special Flags..."); submenu = new JMenu("Dependent"); menuItem = new JMenuItem("Yes"); menuItem.setActionCommand("DEPENDENT|true"); menuItem.addActionListener(this); submenu.add(menuItem); menuItem = new JMenuItem("No"); menuItem.setActionCommand("DEPENDENT|false"); menuItem.addActionListener(this); submenu.add(menuItem); menu.add(submenu); popup.add(menu); } if (oneSelected) { // change portrait menuItem = new JMenuItem("Change Portrait..."); menuItem.setActionCommand("PORTRAIT"); menuItem.addActionListener(this); menuItem.setEnabled(true); popup.add(menuItem); // change Biography menuItem = new JMenuItem("Change Biography..."); menuItem.setActionCommand("BIOGRAPHY"); menuItem.addActionListener(this); menuItem.setEnabled(true); popup.add(menuItem); menuItem = new JMenuItem("Change Callsign..."); menuItem.setActionCommand("CALLSIGN"); menuItem.addActionListener(this); menuItem.setEnabled(true); popup.add(menuItem); menuItem = new JMenuItem("Edit Personnel Log..."); menuItem.setActionCommand("LOG"); menuItem.addActionListener(this); menuItem.setEnabled(true); popup.add(menuItem); } menuItem = new JMenuItem("Add Single Log Entry..."); menuItem.setActionCommand("LOG_SINGLE"); menuItem.addActionListener(this); menuItem.setEnabled(true); popup.add(menuItem); if (oneSelected || StaticChecks.allHaveSameUnit(selected)) { menuItem = new JMenuItem("Assign Kill..."); menuItem.setActionCommand("KILL"); menuItem.addActionListener(this); menuItem.setEnabled(true); popup.add(menuItem); } if (oneSelected) { menuItem = new JMenuItem("Edit Kill Log..."); menuItem.setActionCommand("KILL_LOG"); menuItem.addActionListener(this); menuItem.setEnabled(true); popup.add(menuItem); } menuItem = new JMenuItem("Export Personnel"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { gui.miExportPersonActionPerformed(evt); } }); menuItem.setEnabled(true); popup.add(menuItem); if (gui.getCampaign().getCampaignOptions().getUseAtB() && StaticChecks.areAllActive(selected)) { menuItem = new JMenuItem("Sack..."); menuItem.setActionCommand("SACK"); menuItem.addActionListener(this); popup.add(menuItem); } menu = new JMenu("GM Mode"); menuItem = new JMenuItem("Remove Person"); menuItem.setActionCommand("REMOVE"); menuItem.addActionListener(this); menuItem.setEnabled(gui.getCampaign().isGM()); menu.add(menuItem); if (!gui.getCampaign().getCampaignOptions().useAdvancedMedical()) { menuItem = new JMenuItem("Heal Person"); menuItem.setActionCommand("HEAL"); menuItem.addActionListener(this); menuItem.setEnabled(gui.getCampaign().isGM()); menu.add(menuItem); } menuItem = new JMenuItem("Add XP"); menuItem.setActionCommand("XP_ADD"); menuItem.addActionListener(this); menuItem.setEnabled(gui.getCampaign().isGM()); menu.add(menuItem); menuItem = new JMenuItem("Set XP"); menuItem.setActionCommand("XP_SET"); menuItem.addActionListener(this); menuItem.setEnabled(gui.getCampaign().isGM()); menu.add(menuItem); if (gui.getCampaign().getCampaignOptions().useEdge()) { menuItem = new JMenuItem("Set Edge"); menuItem.setActionCommand("EDGE_SET"); menuItem.addActionListener(this); menuItem.setEnabled(gui.getCampaign().isGM()); menu.add(menuItem); } if (oneSelected) { menuItem = new JMenuItem("Edit..."); menuItem.setActionCommand("EDIT"); menuItem.addActionListener(this); menuItem.setEnabled(gui.getCampaign().isGM()); menu.add(menuItem); } if (gui.getCampaign().getCampaignOptions().useAdvancedMedical()) { menuItem = new JMenuItem("Remove All Injuries"); menuItem.setActionCommand("CLEAR_INJURIES"); menuItem.addActionListener(this); menuItem.setEnabled(gui.getCampaign().isGM()); menu.add(menuItem); if (oneSelected) { for (Injury i : person.getInjuries()) { menuItem = new JMenuItem("Remove Injury: " + i.getName()); menuItem.setActionCommand("REMOVE_INJURY:" + i.getUUIDAsString()); menuItem.addActionListener(this); menuItem.setEnabled(gui.getCampaign().isGM()); menu.add(menuItem); } menuItem = new JMenuItem("Edit Injuries"); menuItem.setActionCommand("EDIT_INJURIES"); menuItem.addActionListener(this); menuItem.setEnabled(gui.getCampaign().isGM()); menu.add(menuItem); } } popup.addSeparator(); popup.add(menu); popup.show(e.getComponent(), e.getX(), e.getY()); } } }
UTF-8
Java
87,875
java
PersonnelTableMouseAdapter.java
Java
[ { "context": " spouse.addLogEntry(gui.getCampaign().getDate(), \"Marries \"\n + selectedPerson.getFullNam", "end": 15693, "score": 0.9996395111083984, "start": 15686, "tag": "NAME", "value": "Marries" }, { "context": "dPerson.addLogEntry(gui.getCampaign().getDate(), \"Marries \"\n + spouse.getFullName());\n ", "end": 15881, "score": 0.9996957778930664, "start": 15874, "tag": "NAME", "value": "Marries" } ]
null
[]
package mekhq.gui.adapter; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Enumeration; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.UUID; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.event.MouseInputAdapter; import megamek.common.Aero; import megamek.common.BattleArmor; import megamek.common.Crew; import megamek.common.Infantry; import megamek.common.Mounted; import megamek.common.Tank; import megamek.common.options.IOption; import megamek.common.options.PilotOptions; import mekhq.Utilities; import mekhq.campaign.Kill; import mekhq.campaign.LogEntry; import mekhq.campaign.personnel.Injury; import mekhq.campaign.personnel.Person; import mekhq.campaign.personnel.Rank; import mekhq.campaign.personnel.Ranks; import mekhq.campaign.personnel.SkillType; import mekhq.campaign.personnel.SpecialAbility; import mekhq.campaign.unit.Unit; import mekhq.gui.CampaignGUI; import mekhq.gui.MenuScroller; import mekhq.gui.dialog.CustomizePersonDialog; import mekhq.gui.dialog.EditKillLogDialog; import mekhq.gui.dialog.EditLogEntryDialog; import mekhq.gui.dialog.EditPersonnelInjuriesDialog; import mekhq.gui.dialog.EditPersonnelLogDialog; import mekhq.gui.dialog.KillDialog; import mekhq.gui.dialog.PopupValueChoiceDialog; import mekhq.gui.dialog.PortraitChoiceDialog; import mekhq.gui.dialog.RetirementDefectionDialog; import mekhq.gui.dialog.TextAreaDialog; import mekhq.gui.tab.PersonnelTab; import mekhq.gui.utilities.StaticChecks; public class PersonnelTableMouseAdapter extends MouseInputAdapter implements ActionListener { private CampaignGUI gui; public PersonnelTableMouseAdapter(CampaignGUI gui) { super(); this.gui = gui; } public PersonnelTableMouseAdapter() { super(); } public void actionPerformed(ActionEvent action) { StringTokenizer st = new StringTokenizer(action.getActionCommand(), "|"); String command = st.nextToken(); int row = gui.getPersonnelTable().getSelectedRow(); if (row < 0) { return; } Person selectedPerson = gui.getPersonnelModel().getPerson(gui.getPersonnelTable() .convertRowIndexToModel(row)); int[] rows = gui.getPersonnelTable().getSelectedRows(); Person[] people = new Person[rows.length]; for (int i = 0; i < rows.length; i++) { people[i] = gui.getPersonnelModel().getPerson(gui.getPersonnelTable() .convertRowIndexToModel(rows[i])); } if (command.startsWith("RANKSYSTEM")) { int system = Integer.parseInt(st.nextToken()); for (Person person : people) { person.setRankSystem(system); } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); } else if (command.startsWith("RANK")) { int rank = Integer.parseInt(st.nextToken()); int level = 0; // Check to see if we added a rank level... if (st.hasMoreTokens()) { level = Integer.parseInt(st.nextToken()); } for (Person person : people) { gui.getCampaign().changeRank(person, rank, level, true); } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.startsWith("MD_RANK")) { int md_rank = Integer.parseInt(st.nextToken()); for (Person person : people) { person.setManeiDominiRank(md_rank); } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.startsWith("MD_CLASS")) { int md_class = Integer.parseInt(st.nextToken()); for (Person person : people) { person.setManeiDominiClass(md_class); } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.startsWith("DESIG_PRI")) { int designation = Integer.parseInt(st.nextToken()); for (Person person : people) { person.setPrimaryDesignator(designation); } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.startsWith("DESIG_SEC")) { int designation = Integer.parseInt(st.nextToken()); for (Person person : people) { person.setSecondaryDesignator(designation); } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("PROLE")) { int role = Integer.parseInt(st.nextToken()); for (Person person : people) { person.setPrimaryRole(role); gui.getCampaign().personUpdated(person); } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("SROLE")) { int role = Integer.parseInt(st.nextToken()); for (Person person : people) { person.setSecondaryRole(role); gui.getCampaign().personUpdated(person); } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("REMOVE_UNIT")) { for (Person person : people) { Unit u = gui.getCampaign().getUnit(person.getUnitId()); if (null != u) { u.remove(person, true); u.resetEngineerOrTech(); u.runDiagnostic(); } // check for tech unit assignments if (!person.getTechUnitIDs().isEmpty()) { // I need to create a new array list to avoid concurrent // problems ArrayList<UUID> temp = new ArrayList<UUID>(); for (UUID i : person.getTechUnitIDs()) { temp.add(i); } for (UUID i : temp) { u = gui.getCampaign().getUnit(i); if (null != u) { u.remove(person, true); u.resetEngineerOrTech(); u.runDiagnostic(); } } } } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("ADD_PILOT")) { UUID selected = UUID.fromString(st.nextToken()); Unit u = gui.getCampaign().getUnit(selected); Unit oldUnit = gui.getCampaign() .getUnit(selectedPerson.getUnitId()); if (null != oldUnit) { oldUnit.remove(selectedPerson, true); } if (null != u) { u.addPilotOrSoldier(selectedPerson); } u.resetPilotAndEntity(); u.runDiagnostic(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("ADD_SOLDIER")) { UUID selected = UUID.fromString(st.nextToken()); Unit u = gui.getCampaign().getUnit(selected); if (null != u) { for (Person p : people) { if (u.canTakeMoreGunners()) { Unit oldUnit = gui.getCampaign().getUnit(p.getUnitId()); if (null != oldUnit) { oldUnit.remove(p, true); } u.addPilotOrSoldier(p); } } } u.resetPilotAndEntity(); u.runDiagnostic(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("ADD_DRIVER")) { UUID selected = UUID.fromString(st.nextToken()); Unit u = gui.getCampaign().getUnit(selected); Unit oldUnit = gui.getCampaign() .getUnit(selectedPerson.getUnitId()); if (null != oldUnit) { oldUnit.remove(selectedPerson, true); } if (null != u) { u.addDriver(selectedPerson); } u.resetPilotAndEntity(); u.runDiagnostic(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("ADD_VESSEL_PILOT")) { UUID selected = UUID.fromString(st.nextToken()); Unit u = gui.getCampaign().getUnit(selected); if (null != u) { for (Person p : people) { if (u.canTakeMoreDrivers()) { Unit oldUnit = gui.getCampaign().getUnit(p.getUnitId()); if (null != oldUnit) { oldUnit.remove(p, true); } u.addDriver(p); } } } u.resetPilotAndEntity(); u.runDiagnostic(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("ADD_GUNNER")) { UUID selected = UUID.fromString(st.nextToken()); Unit u = gui.getCampaign().getUnit(selected); if (null != u) { for (Person p : people) { if (u.canTakeMoreGunners()) { Unit oldUnit = gui.getCampaign().getUnit(p.getUnitId()); if (null != oldUnit) { oldUnit.remove(p, true); } u.addGunner(p); } } } u.resetPilotAndEntity(); u.runDiagnostic(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("ADD_CREW")) { UUID selected = UUID.fromString(st.nextToken()); Unit u = gui.getCampaign().getUnit(selected); if (null != u) { for (Person p : people) { if (u.canTakeMoreVesselCrew()) { Unit oldUnit = gui.getCampaign().getUnit(p.getUnitId()); if (null != oldUnit) { oldUnit.remove(p, true); } u.addVesselCrew(p); } } } u.resetPilotAndEntity(); u.runDiagnostic(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("ADD_NAV")) { UUID selected = UUID.fromString(st.nextToken()); Unit u = gui.getCampaign().getUnit(selected); if (null != u) { for (Person p : people) { if (u.canTakeNavigator()) { Unit oldUnit = gui.getCampaign().getUnit(p.getUnitId()); if (null != oldUnit) { oldUnit.remove(p, true); } u.setNavigator(p); } } } u.resetPilotAndEntity(); u.runDiagnostic(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("ADD_TECH")) { UUID selected = UUID.fromString(st.nextToken()); Unit u = gui.getCampaign().getUnit(selected); if (null != u) { if (u.canTakeTech()) { u.setTech(selectedPerson); } } u.resetPilotAndEntity(); u.runDiagnostic(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("REMOVE_SPOUSE")) { selectedPerson.getSpouse().addLogEntry(gui.getCampaign().getDate(), "Divorced from " + selectedPerson.getFullName()); selectedPerson.addLogEntry(gui.getCampaign().getDate(), "Divorced from " + selectedPerson.getSpouse().getFullName()); selectedPerson.getSpouse().setSpouseID(null); selectedPerson.setSpouseID(null); gui.refreshPersonnelList(); } else if (command.contains("SPOUSE")) { Person spouse = gui.getCampaign().getPerson( UUID.fromString(st.nextToken())); spouse.setSpouseID(selectedPerson.getId()); spouse.addLogEntry(gui.getCampaign().getDate(), "Marries " + selectedPerson.getFullName()); selectedPerson.setSpouseID(spouse.getId()); selectedPerson.addLogEntry(gui.getCampaign().getDate(), "Marries " + spouse.getFullName()); gui.refreshPersonnelList(); } else if (command.contains("IMPROVE")) { String type = st.nextToken(); int cost = Integer.parseInt(st.nextToken()); int oldExpLevel = selectedPerson.getExperienceLevel(false); selectedPerson.improveSkill(type); gui.getCampaign().personUpdated(selectedPerson); selectedPerson.setXp(selectedPerson.getXp() - cost); gui.getCampaign().addReport( selectedPerson.getHyperlinkedName() + " improved " + type + "!"); if (gui.getCampaign().getCampaignOptions().getUseAtB()) { if (selectedPerson.getPrimaryRole() > Person.T_NONE && selectedPerson.getPrimaryRole() <= Person.T_CONV_PILOT && selectedPerson.getExperienceLevel(false) > oldExpLevel && oldExpLevel >= SkillType.EXP_REGULAR) { String spa = gui.getCampaign() .rollSPA(selectedPerson.getPrimaryRole(), selectedPerson); if (null == spa) { if (gui.getCampaign().getCampaignOptions().useEdge()) { selectedPerson.acquireAbility( PilotOptions.EDGE_ADVANTAGES, "edge", selectedPerson.getEdge() + 1); gui.getCampaign().addReport( selectedPerson.getHyperlinkedName() + " gained edge point!"); } } else { gui.getCampaign().addReport( selectedPerson.getHyperlinkedName() + " gained " + SpecialAbility .getDisplayName(spa) + "!"); } } } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshReport(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.contains("ABILITY")) { String selected = st.nextToken(); int cost = Integer.parseInt(st.nextToken()); selectedPerson.acquireAbility(PilotOptions.LVL3_ADVANTAGES, selected, true); gui.getCampaign().personUpdated(selectedPerson); selectedPerson.setXp(selectedPerson.getXp() - cost); // TODO: add gui.getCampaign() report gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshReport(); gui.refreshOverview(); } else if (command.contains("WSPECIALIST")) { String selected = st.nextToken(); int cost = Integer.parseInt(st.nextToken()); selectedPerson.acquireAbility(PilotOptions.LVL3_ADVANTAGES, "weapon_specialist", selected); gui.getCampaign().personUpdated(selectedPerson); selectedPerson.setXp(selectedPerson.getXp() - cost); // TODO: add campaign report gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshReport(); gui.refreshOverview(); } else if (command.contains("SPECIALIST")) { String selected = st.nextToken(); int cost = Integer.parseInt(st.nextToken()); selectedPerson.acquireAbility(PilotOptions.LVL3_ADVANTAGES, "specialist", selected); gui.getCampaign().personUpdated(selectedPerson); selectedPerson.setXp(selectedPerson.getXp() - cost); // TODO: add campaign report gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshReport(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("STATUS")) { int selected = Integer.parseInt(st.nextToken()); for (Person person : people) { if (selected == Person.S_ACTIVE || (0 == JOptionPane.showConfirmDialog(null, "Do you really want to change the status of " + person.getFullTitle() + " to a non-active status?", "KIA?", JOptionPane.YES_NO_OPTION))) { gui.getCampaign().changeStatus(person, selected); } } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.filterPersonnel(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshReport(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("PRISONER_STATUS")) { int selected = Integer.parseInt(st.nextToken()); for (Person person : people) { gui.getCampaign().changePrisonerStatus(person, selected); } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.filterPersonnel(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshReport(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("EDGE")) { String trigger = st.nextToken(); if (people.length > 1) { boolean status = Boolean.parseBoolean(st.nextToken()); for (Person person : people) { person.setEdgeTrigger(trigger, status); gui.getCampaign().personUpdated(person); } } else { selectedPerson.changeEdgeTrigger(trigger); gui.getCampaign().personUpdated(selectedPerson); } gui.refreshPersonnelList(); gui.refreshPersonnelView(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("REMOVE")) { for (Person person : people) { if (0 == JOptionPane.showConfirmDialog( null, "Do you really want to remove " + person.getFullTitle() + "?", "Remove?", JOptionPane.YES_NO_OPTION)) { gui.getCampaign().removePerson(person.getId()); } } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); gui.refreshReport(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("SACK")) { boolean showDialog = false; ArrayList<UUID> toRemove = new ArrayList<UUID>(); for (Person person : people) { if (gui.getCampaign().getRetirementDefectionTracker() .removeFromCampaign( person, false, gui.getCampaign().getCampaignOptions() .getUseShareSystem() ? person .getNumShares(gui.getCampaign() .getCampaignOptions() .getSharesForAll()) : 0, gui.getCampaign(), null)) { showDialog = true; } else { toRemove.add(person.getId()); } } if (showDialog) { RetirementDefectionDialog rdd = new RetirementDefectionDialog( gui, null, false); rdd.setVisible(true); if (rdd.wasAborted() || !gui.getCampaign().applyRetirement(rdd.totalPayout(), rdd.getUnitAssignments())) { for (Person person : people) { gui.getCampaign().getRetirementDefectionTracker() .removePayout(person); } } else { for (UUID id : toRemove) { gui.getCampaign().removePerson(id); } } } else { if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog( null, "Do you really want to remove " + ((people.length > 1)?"personnel?": people[0].getFullTitle() + "?"), "Remove?", JOptionPane.YES_NO_OPTION)) { for (Person person : people) { gui.getCampaign().removePerson(person.getId()); } } } gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshTechsList(); gui.refreshDoctorsList(); gui.refreshOrganization(); gui.refreshReport(); } else if (command.equalsIgnoreCase("EDIT")) { CustomizePersonDialog npd = new CustomizePersonDialog( gui.getFrame(), true, selectedPerson, gui.getCampaign()); npd.setVisible(true); gui.getCampaign().personUpdated(selectedPerson); gui.refreshPatientList(); gui.refreshDoctorsList(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("HEAL")) { for (Person person : people) { person.setHits(0); person.setDoctorId(null, gui.getCampaign().getCampaignOptions() .getNaturalHealingWaitingPeriod()); } gui.getCampaign().personUpdated(selectedPerson); gui.refreshPatientList(); gui.refreshDoctorsList(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("PORTRAIT")) { PortraitChoiceDialog pcd = new PortraitChoiceDialog(gui.getFrame(), true, selectedPerson.getPortraitCategory(), selectedPerson.getPortraitFileName(), gui.getIconPackage() .getPortraits()); pcd.setVisible(true); selectedPerson.setPortraitCategory(pcd.getCategory()); selectedPerson.setPortraitFileName(pcd.getFileName()); gui.getCampaign().personUpdated(selectedPerson); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshOrganization(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("BIOGRAPHY")) { TextAreaDialog tad = new TextAreaDialog(gui.getFrame(), true, "Edit Biography", selectedPerson.getBiography()); tad.setVisible(true); if (tad.wasChanged()) { selectedPerson.setBiography(tad.getText()); } gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("XP_ADD")) { for (Person person : people) { person.setXp(person.getXp() + 1); } gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("XP_SET")) { PopupValueChoiceDialog pvcd = new PopupValueChoiceDialog( gui.getFrame(), true, "XP", selectedPerson.getXp(), 0, Math.max(selectedPerson.getXp() + 10, 100)); pvcd.setVisible(true); if (pvcd.getValue() < 0) { return; } int i = pvcd.getValue(); for (Person person : people) { person.setXp(i); } gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("EDGE_SET")) { PopupValueChoiceDialog pvcd = new PopupValueChoiceDialog( gui.getFrame(), true, "Edge", selectedPerson.getEdge(), 0, 10); pvcd.setVisible(true); if (pvcd.getValue() < 0) { return; } int i = pvcd.getValue(); for (Person person : people) { person.setEdge(i); gui.getCampaign().personUpdated(person); } gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("KILL")) { KillDialog nkd; if (people.length > 1) { nkd = new KillDialog( gui.getFrame(), true, new Kill( null, "?", gui.getCampaign().getUnit( selectedPerson.getUnitId()) != null ? gui.getCampaign() .getUnit(selectedPerson.getUnitId()) .getName() : "Bare Hands", gui.getCampaign() .getDate()), "Crew"); } else { nkd = new KillDialog( gui.getFrame(), true, new Kill( selectedPerson.getId(), "?", gui.getCampaign().getUnit( selectedPerson.getUnitId()) != null ? gui.getCampaign() .getUnit(selectedPerson.getUnitId()) .getName() : "Bare Hands", gui.getCampaign() .getDate()), selectedPerson.getFullName()); } nkd.setVisible(true); if (!nkd.wasCancelled()) { Kill kill = nkd.getKill(); if (people.length > 1) { for (Person person : people) { Kill k = kill.clone(); k.setPilotId(person.getId()); gui.getCampaign().addKill(k); } } else { gui.getCampaign().addKill(kill); } } gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("KILL_LOG")) { EditKillLogDialog ekld = new EditKillLogDialog(gui.getFrame(), true, gui.getCampaign(), selectedPerson); ekld.setVisible(true); gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("LOG")) { EditPersonnelLogDialog epld = new EditPersonnelLogDialog( gui.getFrame(), true, gui.getCampaign(), selectedPerson); epld.setVisible(true); gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("LOG_SINGLE")) { EditLogEntryDialog eeld = new EditLogEntryDialog(gui.getFrame(), true, new LogEntry(gui.getCampaign().getDate(), "")); eeld.setVisible(true); LogEntry entry = eeld.getEntry(); if (null != entry) { for (Person person : people) { person.addLogEntry(entry.clone()); } } gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("COMMANDER")) { selectedPerson.setCommander(!selectedPerson.isCommander()); if (selectedPerson.isCommander()) { for (Person p : gui.getCampaign().getPersonnel()) { if (p.isCommander() && !p.getId().equals(selectedPerson.getId())) { p.setCommander(false); gui.getCampaign() .addReport( p.getHyperlinkedFullTitle() + " has been removed as the overall unit commander."); gui.getCampaign().personUpdated(p); } } gui.getCampaign() .addReport( selectedPerson.getHyperlinkedFullTitle() + " has been set as the overall unit commander."); gui.getCampaign().personUpdated(selectedPerson); } gui.refreshReport(); } else if (command.equalsIgnoreCase("DEPENDENT")) { if (people.length > 1) { boolean status = Boolean.parseBoolean(st.nextToken()); for (Person person : people) { person.setDependent(status); gui.getCampaign().personUpdated(person); } } else { selectedPerson.setDependent(!selectedPerson.isDependent()); gui.getCampaign().personUpdated(selectedPerson); } } else if (command.equalsIgnoreCase("CALLSIGN")) { String s = (String) JOptionPane.showInputDialog(gui.getFrame(), "Enter new callsign", "Edit Callsign", JOptionPane.PLAIN_MESSAGE, null, null, selectedPerson.getCallsign()); if (null != s) { selectedPerson.setCallsign(s); } gui.getCampaign().personUpdated(selectedPerson); gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("CLEAR_INJURIES")) { for (Person person : people) { person.clearInjuries(); Unit u = gui.getCampaign().getUnit(person.getUnitId()); if (null != u) { u.resetPilotAndEntity(); } } gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.contains("REMOVE_INJURY")) { String sel = command.split(":")[1]; Injury toRemove = null; for (Injury i : selectedPerson.getInjuries()) { if (i.getUUIDAsString().equals(sel)) { toRemove = i; break; } } if (toRemove != null) { selectedPerson.removeInjury(toRemove); } Unit u = gui.getCampaign().getUnit(selectedPerson.getUnitId()); if (null != u) { u.resetPilotAndEntity(); } gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("EDIT_INJURIES")) { EditPersonnelInjuriesDialog epid = new EditPersonnelInjuriesDialog( gui.getFrame(), true, gui.getCampaign(), selectedPerson); epid.setVisible(true); gui.refreshPatientList(); gui.refreshPersonnelList(); gui.refreshOverview(); } else if (command.equalsIgnoreCase("BLOODNAME")) { for (Person p : people) { if (!p.isClanner()) { continue; } gui.getCampaign() .checkBloodnameAdd(p, p.getPrimaryRole(), true); } gui.getCampaign().personUpdated(selectedPerson); gui.refreshPatientList(); gui.refreshDoctorsList(); gui.refreshServicedUnitList(); gui.refreshUnitList(); gui.refreshPersonnelList(); gui.refreshOrganization(); } else if (command.equalsIgnoreCase("SALARY")) { PopupValueChoiceDialog pcvd = new PopupValueChoiceDialog(gui.getFrame(), true, "Change Salary (-1 to remove custom salary)", selectedPerson.getSalary(), -1, 100000); pcvd.setVisible(true); int salary = pcvd.getValue(); if (salary < -1) { return; } for (Person person : people) { person.setSalary(salary); } gui.refreshPersonnelList(); } } @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { if ((gui.getSplitPersonnel().getSize().width - gui.getSplitPersonnel().getDividerLocation() + gui.getSplitPersonnel() .getDividerSize()) < PersonnelTab.PERSONNEL_VIEW_WIDTH) { // expand gui.getSplitPersonnel().resetToPreferredSizes(); } else { // collapse gui.getSplitPersonnel().setDividerLocation(1.0); } } } @Override public void mousePressed(MouseEvent e) { maybeShowPopup(e); } @Override public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { JPopupMenu popup = new JPopupMenu(); if (e.isPopupTrigger()) { if (gui.getPersonnelTable().getSelectedRowCount() == 0) { return; } int row = gui.getPersonnelTable().getSelectedRow(); boolean oneSelected = gui.getPersonnelTable().getSelectedRowCount() == 1; Person person = gui.getPersonnelModel().getPerson(gui.getPersonnelTable() .convertRowIndexToModel(row)); JMenuItem menuItem = null; JMenu menu = null; JMenu submenu = null; JCheckBoxMenuItem cbMenuItem = null; Person[] selected = gui.getSelectedPeople(); // **lets fill the pop up menu**// if (StaticChecks.areAllEligible(selected)) { menu = new JMenu("Change Rank"); Ranks ranks = person.getRanks(); for (int rankOrder = 0; rankOrder < Ranks.RC_NUM; rankOrder++) { Rank rank = ranks.getAllRanks().get(rankOrder); int profession = person.getProfession(); // Empty professions need swapped before the // continuation while (ranks.isEmptyProfession(profession) && profession != Ranks.RPROF_MW) { profession = ranks .getAlternateProfession(profession); } if (rank.getName(profession).equals("-")) { continue; } // re-route through any profession redirections, // starting with the empty profession check while (rank.getName(profession).startsWith("--") && profession != Ranks.RPROF_MW) { if (rank.getName(profession).equals("--")) { profession = ranks .getAlternateProfession(profession); } else if (rank.getName(profession) .startsWith("--")) { profession = ranks.getAlternateProfession(rank .getName(profession)); } } if (rank.getRankLevels(profession) > 0) { submenu = new JMenu(rank.getName(profession)); for (int level = 0; level <= rank .getRankLevels(profession); level++) { cbMenuItem = new JCheckBoxMenuItem( rank.getName(profession) + Utilities .getRomanNumeralsFromArabicNumber( level, true)); cbMenuItem.setActionCommand("RANK|" + rankOrder + "|" + level); if (person.getRankNumeric() == rankOrder && person.getRankLevel() == level) { cbMenuItem.setSelected(true); } cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); submenu.add(cbMenuItem); } if (submenu.getItemCount() > 20) { MenuScroller.setScrollerFor(submenu, 20); } menu.add(submenu); } else { cbMenuItem = new JCheckBoxMenuItem( rank.getName(profession)); cbMenuItem.setActionCommand("RANK|" + rankOrder); if (person.getRankNumeric() == rankOrder) { cbMenuItem.setSelected(true); } cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); menu.add(cbMenuItem); } } if (menu.getItemCount() > 20) { MenuScroller.setScrollerFor(menu, 20); } popup.add(menu); } menu = new JMenu("Change Rank System"); // First allow them to revert to the campaign system cbMenuItem = new JCheckBoxMenuItem("Use Campaign Rank System"); cbMenuItem.setActionCommand("RANKSYSTEM|" + "-1"); cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); menu.add(cbMenuItem); for (int system = 0; system < Ranks.RS_NUM; system++) { if (system == Ranks.RS_CUSTOM) { continue; } cbMenuItem = new JCheckBoxMenuItem( Ranks.getRankSystemName(system)); cbMenuItem.setActionCommand("RANKSYSTEM|" + system); cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); if (system == person.getRanks().getRankSystem()) { cbMenuItem.setSelected(true); } menu.add(cbMenuItem); } if (menu.getItemCount() > 20) { MenuScroller.setScrollerFor(menu, 20); } popup.add(menu); if (StaticChecks.areAllWoB(selected)) { // MD Ranks menu = new JMenu("Change Manei Domini Rank"); for (int i = Rank.MD_RANK_NONE; i < Rank.MD_RANK_NUM; i++) { cbMenuItem = new JCheckBoxMenuItem( Rank.getManeiDominiRankName(i)); cbMenuItem.setActionCommand("MD_RANK|" + i); cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); if (i == person.getManeiDominiRank()) { cbMenuItem.setSelected(true); } menu.add(cbMenuItem); } if (menu.getItemCount() > 20) { MenuScroller.setScrollerFor(menu, 20); } popup.add(menu); // MD Classes menu = new JMenu("Change Manei Domini Class"); for (int i = Person.MD_NONE; i < Person.MD_NUM; i++) { cbMenuItem = new JCheckBoxMenuItem( Person.getManeiDominiClassNames(i, Ranks.RS_WOB)); cbMenuItem.setActionCommand("MD_CLASS|" + i); cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); if (i == person.getManeiDominiClass()) { cbMenuItem.setSelected(true); } menu.add(cbMenuItem); } if (menu.getItemCount() > 20) { MenuScroller.setScrollerFor(menu, 20); } popup.add(menu); } if (StaticChecks.areAllWoBOrComstar(selected)) { menu = new JMenu("Change Primary Designation"); for (int i = Person.DESIG_NONE; i < Person.DESIG_NUM; i++) { cbMenuItem = new JCheckBoxMenuItem( Person.parseDesignator(i)); cbMenuItem.setActionCommand("DESIG_PRI|" + i); cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); if (i == person.getPrimaryDesignator()) { cbMenuItem.setSelected(true); } menu.add(cbMenuItem); } if (menu.getItemCount() > 20) { MenuScroller.setScrollerFor(menu, 20); } popup.add(menu); menu = new JMenu("Change Secondary Designation"); for (int i = Person.DESIG_NONE; i < Person.DESIG_NUM; i++) { cbMenuItem = new JCheckBoxMenuItem( Person.parseDesignator(i)); cbMenuItem.setActionCommand("DESIG_SEC|" + i); cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); if (i == person.getSecondaryDesignator()) { cbMenuItem.setSelected(true); } menu.add(cbMenuItem); } if (menu.getItemCount() > 20) { MenuScroller.setScrollerFor(menu, 20); } popup.add(menu); } menu = new JMenu("Change Status"); for (int s = 0; s < Person.S_NUM; s++) { cbMenuItem = new JCheckBoxMenuItem(Person.getStatusName(s)); if (person.getStatus() == s) { cbMenuItem.setSelected(true); } cbMenuItem.setActionCommand("STATUS|" + s); cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); menu.add(cbMenuItem); } popup.add(menu); menu = new JMenu("Change Prisoner Status"); for (int s = 0; s < Person.PRISONER_NUM; s++) { cbMenuItem = new JCheckBoxMenuItem( Person.getPrisonerStatusName(s)); if (person.getPrisonerStatus() == s) { cbMenuItem.setSelected(true); } cbMenuItem.setActionCommand("PRISONER_STATUS|" + s); cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); menu.add(cbMenuItem); } popup.add(menu); menu = new JMenu("Change Primary Role"); for (int i = Person.T_MECHWARRIOR; i < Person.T_NUM; i++) { if (person.canPerformRole(i) && person.getSecondaryRole() != i) { cbMenuItem = new JCheckBoxMenuItem(Person.getRoleDesc( i, gui.getCampaign().getFaction().isClan())); cbMenuItem.setActionCommand("PROLE|" + i); if (person.getPrimaryRole() == i) { cbMenuItem.setSelected(true); } cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); menu.add(cbMenuItem); } } if (menu.getItemCount() > 20) { MenuScroller.setScrollerFor(menu, 20); } popup.add(menu); menu = new JMenu("Change Secondary Role"); for (int i = 0; i < Person.T_NUM; i++) { if (i == Person.T_NONE || (person.canPerformRole(i) && person .getPrimaryRole() != i)) { // you cant be an astech if you are a tech, or a medic // if you are a doctor if (person.isTechPrimary() && i == Person.T_ASTECH) { continue; } if (person.getPrimaryRole() == Person.T_DOCTOR && i == Person.T_MEDIC) { continue; } cbMenuItem = new JCheckBoxMenuItem(Person.getRoleDesc( i, gui.getCampaign().getFaction().isClan())); cbMenuItem.setActionCommand("SROLE|" + i); if (person.getSecondaryRole() == i) { cbMenuItem.setSelected(true); } cbMenuItem.addActionListener(this); cbMenuItem.setEnabled(true); menu.add(cbMenuItem); } } if (menu.getItemCount() > 20) { MenuScroller.setScrollerFor(menu, 20); } popup.add(menu); // Bloodnames if (StaticChecks.areAllClanEligible(selected)) { menuItem = new JMenuItem("Give Random Bloodname"); menuItem.setActionCommand("BLOODNAME"); menuItem.addActionListener(this); menuItem.setEnabled(StaticChecks.areAllActive(selected)); popup.add(menuItem); } // change salary if (gui.getCampaign().getCampaignOptions().payForSalaries()) { menuItem = new JMenuItem("Set Salary..."); menuItem.setActionCommand("SALARY"); menuItem.addActionListener(this); menuItem.setEnabled(StaticChecks.areAllActive(selected)); popup.add(menuItem); } // switch pilot menu = new JMenu("Assign to Unit"); JMenu pilotMenu = new JMenu("As Pilot"); JMenu crewMenu = new JMenu("As Crewmember"); JMenu driverMenu = new JMenu("As Driver"); JMenu gunnerMenu = new JMenu("As Gunner"); JMenu soldierMenu = new JMenu("As Soldier"); JMenu techMenu = new JMenu("As Tech"); JMenu navMenu = new JMenu("As Navigator"); /* * if(!person.isAssigned()) { cbMenuItem.setSelected(true); } */ if (oneSelected && person.isActive() && !(person.isPrisoner() || person.isBondsman())) { for (Unit unit : gui.getCampaign().getUnits()) { if (!unit.isAvailable()) { continue; } if (unit.usesSoloPilot()) { if (unit.canTakeMoreDrivers() && person.canDrive(unit.getEntity()) && person.canGun(unit.getEntity())) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_PILOT|" + unit.getId()); cbMenuItem.addActionListener(this); pilotMenu.add(cbMenuItem); } } else if (unit.usesSoldiers()) { if (unit.canTakeMoreGunners() && person.canGun(unit.getEntity())) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_SOLDIER|" + unit.getId()); cbMenuItem.addActionListener(this); soldierMenu.add(cbMenuItem); } } else { if (unit.canTakeMoreDrivers() && person.canDrive(unit.getEntity())) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_DRIVER|" + unit.getId()); cbMenuItem.addActionListener(this); if (unit.getEntity() instanceof Aero) { pilotMenu.add(cbMenuItem); } else { driverMenu.add(cbMenuItem); } } if (unit.canTakeMoreGunners() && person.canGun(unit.getEntity())) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_GUNNER|" + unit.getId()); cbMenuItem.addActionListener(this); gunnerMenu.add(cbMenuItem); } if (unit.canTakeMoreVesselCrew() && person.hasSkill(SkillType.S_TECH_VESSEL)) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_CREW|" + unit.getId()); cbMenuItem.addActionListener(this); crewMenu.add(cbMenuItem); } if (unit.canTakeNavigator() && person.hasSkill(SkillType.S_NAV)) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_NAV|" + unit.getId()); cbMenuItem.addActionListener(this); navMenu.add(cbMenuItem); } } if (unit.canTakeTech() && person.canTech(unit.getEntity()) && (person.getMaintenanceTimeUsing() + unit .getMaintenanceTime()) <= 480) { cbMenuItem = new JCheckBoxMenuItem(unit.getName() + " (" + unit.getMaintenanceTime() + " minutes/day)"); // TODO: check the box cbMenuItem.setActionCommand("ADD_TECH|" + unit.getId()); cbMenuItem.addActionListener(this); techMenu.add(cbMenuItem); } } if (pilotMenu.getItemCount() > 0) { menu.add(pilotMenu); if (pilotMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(pilotMenu, 20); } } if (driverMenu.getItemCount() > 0) { menu.add(driverMenu); if (driverMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(driverMenu, 20); } } if (crewMenu.getItemCount() > 0) { menu.add(crewMenu); if (crewMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(crewMenu, 20); } } if (navMenu.getItemCount() > 0) { menu.add(navMenu); if (navMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(navMenu, 20); } } if (gunnerMenu.getItemCount() > 0) { menu.add(gunnerMenu); if (gunnerMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(gunnerMenu, 20); } } if (soldierMenu.getItemCount() > 0) { menu.add(soldierMenu); if (soldierMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(soldierMenu, 20); } } if (techMenu.getItemCount() > 0) { menu.add(techMenu); if (techMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(techMenu, 20); } } menu.setEnabled(!person.isDeployed()); popup.add(menu); } else if (StaticChecks.areAllActive(selected) && StaticChecks.areAllEligible(selected)) { for (Unit unit : gui.getCampaign().getUnits()) { if (!unit.isAvailable()) { continue; } if (StaticChecks.areAllInfantry(selected)) { if (!(unit.getEntity() instanceof Infantry) || unit.getEntity() instanceof BattleArmor) { continue; } if (unit.canTakeMoreGunners() && person.canGun(unit.getEntity())) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_SOLDIER|" + unit.getId()); cbMenuItem.addActionListener(this); soldierMenu.add(cbMenuItem); } } else if (StaticChecks.areAllBattleArmor(selected)) { if (!(unit.getEntity() instanceof BattleArmor)) { continue; } if (unit.canTakeMoreGunners() && person.canGun(unit.getEntity())) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_SOLDIER|" + unit.getId()); cbMenuItem.addActionListener(this); soldierMenu.add(cbMenuItem); } } else if (StaticChecks.areAllVeeGunners(selected)) { if (!(unit.getEntity() instanceof Tank)) { continue; } if (unit.canTakeMoreGunners() && person.canGun(unit.getEntity())) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_GUNNER|" + unit.getId()); cbMenuItem.addActionListener(this); gunnerMenu.add(cbMenuItem); } } else if (StaticChecks.areAllVesselGunners(selected)) { if (!(unit.getEntity() instanceof Aero)) { continue; } if (unit.canTakeMoreGunners() && person.canGun(unit.getEntity())) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_GUNNER|" + unit.getId()); cbMenuItem.addActionListener(this); gunnerMenu.add(cbMenuItem); } } else if (StaticChecks.areAllVesselCrew(selected)) { if (!(unit.getEntity() instanceof Aero)) { continue; } if (unit.canTakeMoreVesselCrew() && person.hasSkill(SkillType.S_TECH_VESSEL)) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_CREW|" + unit.getId()); cbMenuItem.addActionListener(this); crewMenu.add(cbMenuItem); } } else if (StaticChecks.areAllVesselPilots(selected)) { if (!(unit.getEntity() instanceof Aero)) { continue; } if (unit.canTakeMoreDrivers() && person.canDrive(unit.getEntity())) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_VESSEL_PILOT|" + unit.getId()); cbMenuItem.addActionListener(this); pilotMenu.add(cbMenuItem); } } else if (StaticChecks.areAllVesselNavigators(selected)) { if (!(unit.getEntity() instanceof Aero)) { continue; } if (unit.canTakeNavigator() && person.hasSkill(SkillType.S_NAV)) { cbMenuItem = new JCheckBoxMenuItem( unit.getName()); // TODO: check the box cbMenuItem.setActionCommand("ADD_NAV|" + unit.getId()); cbMenuItem.addActionListener(this); navMenu.add(cbMenuItem); } } } if (soldierMenu.getItemCount() > 0) { menu.add(soldierMenu); if (soldierMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(soldierMenu, 20); } } if (pilotMenu.getItemCount() > 0) { menu.add(pilotMenu); if (pilotMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(pilotMenu, 20); } } if (driverMenu.getItemCount() > 0) { menu.add(driverMenu); if (driverMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(driverMenu, 20); } } if (crewMenu.getItemCount() > 0) { menu.add(crewMenu); if (crewMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(crewMenu, 20); } } if (navMenu.getItemCount() > 0) { menu.add(navMenu); if (navMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(navMenu, 20); } } if (gunnerMenu.getItemCount() > 0) { menu.add(gunnerMenu); if (gunnerMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(gunnerMenu, 20); } } if (soldierMenu.getItemCount() > 0) { menu.add(soldierMenu); if (soldierMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(soldierMenu, 20); } } menu.setEnabled(!person.isDeployed()); popup.add(menu); } cbMenuItem = new JCheckBoxMenuItem("None"); cbMenuItem.setActionCommand("REMOVE_UNIT|" + -1); cbMenuItem.addActionListener(this); menu.add(cbMenuItem); if (oneSelected && person.isActive()) { if (person.getAge(gui.getCampaign().getCalendar()) > 13 && person.getSpouseID() == null) { menu = new JMenu("Choose Spouse (Mate)"); for (Person ps : gui.getCampaign().getPersonnel()) { if (person.safeSpouse(ps)) { menuItem = new JMenuItem( ps.getFullName() + ", " + ps.getAge(gui.getCampaign() .getCalendar()) + ", " + ps.getRoleDesc()); menuItem.setActionCommand("SPOUSE|" + ps.getId().toString()); menuItem.addActionListener(this); menu.add(menuItem); } } if (menu.getItemCount() > 30) { MenuScroller.setScrollerFor(menu, 20); } popup.add(menu); } if (person.getSpouseID() != null) { menuItem = new JMenuItem("Remove Spouse"); menuItem.setActionCommand("REMOVE_SPOUSE"); menuItem.addActionListener(this); popup.add(menuItem); } menu = new JMenu("Spend XP"); JMenu currentMenu = new JMenu("Current Skills"); JMenu newMenu = new JMenu("New Skills"); for (int i = 0; i < SkillType.getSkillList().length; i++) { String type = SkillType.getSkillList()[i]; if (person.hasSkill(type)) { int cost = person.getSkill(type).getCostToImprove(); if (cost >= 0) { String costDesc = " (" + cost + "XP)"; menuItem = new JMenuItem(type + costDesc); menuItem.setActionCommand("IMPROVE|" + type + "|" + cost); menuItem.addActionListener(this); menuItem.setEnabled(person.getXp() >= cost); currentMenu.add(menuItem); } } else { int cost = SkillType.getType(type).getCost(0); if (cost >= 0) { String costDesc = " (" + cost + "XP)"; menuItem = new JMenuItem(type + costDesc); menuItem.setActionCommand("IMPROVE|" + type + "|" + cost); menuItem.addActionListener(this); menuItem.setEnabled(person.getXp() >= cost); newMenu.add(menuItem); } } } menu.add(currentMenu); menu.add(newMenu); if (gui.getCampaign().getCampaignOptions().useAbilities()) { JMenu abMenu = new JMenu("Special Abilities"); int cost = -1; String costDesc = ""; for (Enumeration<IOption> i = person .getOptions(PilotOptions.LVL3_ADVANTAGES); i .hasMoreElements();) { IOption ability = i.nextElement(); if (!ability.booleanValue()) { SpecialAbility spa = SpecialAbility .getAbility(ability.getName()); if (null == spa) { continue; } if (!spa.isEligible(person)) { continue; } cost = spa.getCost(); costDesc = " (" + cost + "XP)"; if (cost < 0) { costDesc = " (Not Possible)"; } if (ability.getName().equals( "weapon_specialist")) { Unit u = gui.getCampaign().getUnit( person.getUnitId()); if (null != u) { JMenu specialistMenu = new JMenu( "Weapon Specialist"); TreeSet<String> uniqueWeapons = new TreeSet<String>(); for (int j = 0; j < u.getEntity() .getWeaponList().size(); j++) { Mounted m = u.getEntity() .getWeaponList().get(j); uniqueWeapons.add(m.getName()); } for (String name : uniqueWeapons) { menuItem = new JMenuItem(name + costDesc); menuItem.setActionCommand("WSPECIALIST|" + name + "|" + cost); menuItem.addActionListener(this); menuItem.setEnabled(cost >= 0 && person.getXp() >= cost); specialistMenu.add(menuItem); } abMenu.add(specialistMenu); } } else if (ability.getName().equals( "specialist")) { JMenu specialistMenu = new JMenu( "Specialist"); menuItem = new JMenuItem("Laser Specialist" + costDesc); menuItem.setActionCommand("SPECIALIST|" + Crew.SPECIAL_LASER + "|" + cost); menuItem.addActionListener(this); menuItem.setEnabled(cost >= 0 && person.getXp() >= cost); specialistMenu.add(menuItem); menuItem = new JMenuItem( "Missile Specialist" + costDesc); menuItem.setActionCommand("SPECIALIST|" + Crew.SPECIAL_MISSILE + "|" + cost); menuItem.addActionListener(this); menuItem.setEnabled(cost >= 0 && person.getXp() >= cost); specialistMenu.add(menuItem); menuItem = new JMenuItem( "Ballistic Specialist" + costDesc); menuItem.setActionCommand("SPECIALIST|" + Crew.SPECIAL_BALLISTIC + "|" + cost); menuItem.addActionListener(this); menuItem.setEnabled(cost >= 0 && person.getXp() >= cost); specialistMenu.add(menuItem); abMenu.add(specialistMenu); } else { menuItem = new JMenuItem( ability.getDisplayableName() + costDesc); menuItem.setActionCommand("ABILITY|" + ability.getName() + "|" + cost); menuItem.addActionListener(this); menuItem.setEnabled(cost >= 0 && person.getXp() >= cost); abMenu.add(menuItem); } } } if (abMenu.getItemCount() > 20) { MenuScroller.setScrollerFor(abMenu, 20); } menu.add(abMenu); } popup.add(menu); } if (oneSelected && person.isActive()) { if (gui.getCampaign().getCampaignOptions().useEdge()) { menu = new JMenu("Set Edge Triggers"); cbMenuItem = new JCheckBoxMenuItem("Head Hits"); cbMenuItem.setSelected(person.getOptions() .booleanOption("edge_when_headhit")); cbMenuItem.setActionCommand("EDGE|edge_when_headhit"); cbMenuItem.addActionListener(this); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem( "Through Armor Crits"); cbMenuItem.setSelected(person.getOptions() .booleanOption("edge_when_tac")); cbMenuItem.setActionCommand("EDGE|edge_when_tac"); cbMenuItem.addActionListener(this); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Fail KO check"); cbMenuItem.setSelected(person.getOptions() .booleanOption("edge_when_ko")); cbMenuItem.setActionCommand("EDGE|edge_when_ko"); cbMenuItem.addActionListener(this); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Ammo Explosion"); cbMenuItem.setSelected(person.getOptions() .booleanOption("edge_when_explosion")); cbMenuItem.setActionCommand("EDGE|edge_when_explosion"); cbMenuItem.addActionListener(this); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("MASC Failures"); cbMenuItem.setSelected(person.getOptions() .booleanOption("edge_when_masc_fails")); cbMenuItem .setActionCommand("EDGE|edge_when_masc_fails"); cbMenuItem.addActionListener(this); menu.add(cbMenuItem); popup.add(menu); } menu = new JMenu("Special Flags..."); cbMenuItem = new JCheckBoxMenuItem("Dependent"); cbMenuItem.setSelected(person.isDependent()); cbMenuItem.setActionCommand("DEPENDENT"); cbMenuItem.addActionListener(this); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Commander"); cbMenuItem.setSelected(person.isCommander()); cbMenuItem.setActionCommand("COMMANDER"); cbMenuItem.addActionListener(this); menu.add(cbMenuItem); popup.add(menu); } else if (StaticChecks.areAllActive(selected)) { if (gui.getCampaign().getCampaignOptions().useEdge()) { menu = new JMenu("Set Edge Triggers"); submenu = new JMenu("On"); menuItem = new JMenuItem("Head Hits"); menuItem.setActionCommand("EDGE|edge_when_headhit|true"); menuItem.addActionListener(this); submenu.add(menuItem); menuItem = new JMenuItem("Through Armor Crits"); menuItem.setActionCommand("EDGE|edge_when_tac|true"); menuItem.addActionListener(this); submenu.add(menuItem); menuItem = new JMenuItem("Fail KO check"); menuItem.setActionCommand("EDGE|edge_when_ko|true"); menuItem.addActionListener(this); submenu.add(menuItem); menuItem = new JMenuItem("Ammo Explosion"); menuItem.setActionCommand("EDGE|edge_when_explosion|true"); menuItem.addActionListener(this); submenu.add(menuItem); menuItem = new JMenuItem("MASC Failures"); menuItem.setActionCommand("EDGE|edge_when_masc_fails|true"); menuItem.addActionListener(this); submenu.add(menuItem); menu.add(submenu); submenu = new JMenu("Off"); menuItem = new JMenuItem("Head Hits"); menuItem.setActionCommand("EDGE|edge_when_headhit|false"); menuItem.addActionListener(this); submenu.add(menuItem); menuItem = new JMenuItem("Through Armor Crits"); menuItem.setActionCommand("EDGE|edge_when_tac|false"); menuItem.addActionListener(this); submenu.add(menuItem); menuItem = new JMenuItem("Fail KO check"); menuItem.setActionCommand("EDGE|edge_when_ko|false"); menuItem.addActionListener(this); submenu.add(menuItem); menuItem = new JMenuItem("Ammo Explosion"); menuItem.setActionCommand("EDGE|edge_when_explosion|false"); menuItem.addActionListener(this); submenu.add(menuItem); menuItem = new JMenuItem("MASC Failures"); menuItem.setActionCommand("EDGE|edge_when_masc_fails|false"); menuItem.addActionListener(this); submenu.add(menuItem); menu.add(submenu); popup.add(menu); } menu = new JMenu("Special Flags..."); submenu = new JMenu("Dependent"); menuItem = new JMenuItem("Yes"); menuItem.setActionCommand("DEPENDENT|true"); menuItem.addActionListener(this); submenu.add(menuItem); menuItem = new JMenuItem("No"); menuItem.setActionCommand("DEPENDENT|false"); menuItem.addActionListener(this); submenu.add(menuItem); menu.add(submenu); popup.add(menu); } if (oneSelected) { // change portrait menuItem = new JMenuItem("Change Portrait..."); menuItem.setActionCommand("PORTRAIT"); menuItem.addActionListener(this); menuItem.setEnabled(true); popup.add(menuItem); // change Biography menuItem = new JMenuItem("Change Biography..."); menuItem.setActionCommand("BIOGRAPHY"); menuItem.addActionListener(this); menuItem.setEnabled(true); popup.add(menuItem); menuItem = new JMenuItem("Change Callsign..."); menuItem.setActionCommand("CALLSIGN"); menuItem.addActionListener(this); menuItem.setEnabled(true); popup.add(menuItem); menuItem = new JMenuItem("Edit Personnel Log..."); menuItem.setActionCommand("LOG"); menuItem.addActionListener(this); menuItem.setEnabled(true); popup.add(menuItem); } menuItem = new JMenuItem("Add Single Log Entry..."); menuItem.setActionCommand("LOG_SINGLE"); menuItem.addActionListener(this); menuItem.setEnabled(true); popup.add(menuItem); if (oneSelected || StaticChecks.allHaveSameUnit(selected)) { menuItem = new JMenuItem("Assign Kill..."); menuItem.setActionCommand("KILL"); menuItem.addActionListener(this); menuItem.setEnabled(true); popup.add(menuItem); } if (oneSelected) { menuItem = new JMenuItem("Edit Kill Log..."); menuItem.setActionCommand("KILL_LOG"); menuItem.addActionListener(this); menuItem.setEnabled(true); popup.add(menuItem); } menuItem = new JMenuItem("Export Personnel"); menuItem.addActionListener(new ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { gui.miExportPersonActionPerformed(evt); } }); menuItem.setEnabled(true); popup.add(menuItem); if (gui.getCampaign().getCampaignOptions().getUseAtB() && StaticChecks.areAllActive(selected)) { menuItem = new JMenuItem("Sack..."); menuItem.setActionCommand("SACK"); menuItem.addActionListener(this); popup.add(menuItem); } menu = new JMenu("GM Mode"); menuItem = new JMenuItem("Remove Person"); menuItem.setActionCommand("REMOVE"); menuItem.addActionListener(this); menuItem.setEnabled(gui.getCampaign().isGM()); menu.add(menuItem); if (!gui.getCampaign().getCampaignOptions().useAdvancedMedical()) { menuItem = new JMenuItem("Heal Person"); menuItem.setActionCommand("HEAL"); menuItem.addActionListener(this); menuItem.setEnabled(gui.getCampaign().isGM()); menu.add(menuItem); } menuItem = new JMenuItem("Add XP"); menuItem.setActionCommand("XP_ADD"); menuItem.addActionListener(this); menuItem.setEnabled(gui.getCampaign().isGM()); menu.add(menuItem); menuItem = new JMenuItem("Set XP"); menuItem.setActionCommand("XP_SET"); menuItem.addActionListener(this); menuItem.setEnabled(gui.getCampaign().isGM()); menu.add(menuItem); if (gui.getCampaign().getCampaignOptions().useEdge()) { menuItem = new JMenuItem("Set Edge"); menuItem.setActionCommand("EDGE_SET"); menuItem.addActionListener(this); menuItem.setEnabled(gui.getCampaign().isGM()); menu.add(menuItem); } if (oneSelected) { menuItem = new JMenuItem("Edit..."); menuItem.setActionCommand("EDIT"); menuItem.addActionListener(this); menuItem.setEnabled(gui.getCampaign().isGM()); menu.add(menuItem); } if (gui.getCampaign().getCampaignOptions().useAdvancedMedical()) { menuItem = new JMenuItem("Remove All Injuries"); menuItem.setActionCommand("CLEAR_INJURIES"); menuItem.addActionListener(this); menuItem.setEnabled(gui.getCampaign().isGM()); menu.add(menuItem); if (oneSelected) { for (Injury i : person.getInjuries()) { menuItem = new JMenuItem("Remove Injury: " + i.getName()); menuItem.setActionCommand("REMOVE_INJURY:" + i.getUUIDAsString()); menuItem.addActionListener(this); menuItem.setEnabled(gui.getCampaign().isGM()); menu.add(menuItem); } menuItem = new JMenuItem("Edit Injuries"); menuItem.setActionCommand("EDIT_INJURIES"); menuItem.addActionListener(this); menuItem.setEnabled(gui.getCampaign().isGM()); menu.add(menuItem); } } popup.addSeparator(); popup.add(menu); popup.show(e.getComponent(), e.getX(), e.getY()); } } }
87,875
0.461394
0.459289
1,875
45.867199
18.250288
102
false
false
0
0
0
0
0
0
0.698133
false
false
14
1bd3a5718f1acca221433d1dcc968ae03841b559
7,258,494,780,721
d953eb0973066a633d11b8db7fdc9c2846a9c48a
/ch4.5exe/src/lydia/porter/ch4_5/Example.java
c69ff2d982f1583c2be9a8a11227b4f01ca24e9a
[]
no_license
LydiaPorter/Java_2020_6_7projects
https://github.com/LydiaPorter/Java_2020_6_7projects
70888af7207d0b04348907d7bdd4aef1afd592c9
88bed44f1f7ac005e78fa4cb03ba5abbade30c48
refs/heads/master
2023-04-29T01:50:43.833000
2021-04-30T15:47:11
2021-04-30T15:47:11
293,859,523
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package lydia.porter.ch4_5; import java.util.*; public class Example { public Example() { Scanner input = new Scanner(System.in); System.out.println("type something in"); String word1 = input.nextLine(); //grabs next line of text that comes in String word2 = input.nextLine(); String word3 = input.nextLine(); String word4 = input.nextLine(); String word5 = input.nextLine(); //String.format("The input format parameter", "Object parameter"); //precision: how many decimal points? // %[parameter_index$][flags][width] //%s String result = String.format("Three %(d blind mice %2$tr", -2856935, Calendar.getInstance( )); System.out.println(result); //System.out.print("enter in a word"); //String word1 -input.nextLine(); String myText = String.format("Turmoil has engulfed the\n" + " %1$s Republic. The taxation\n" + "of trade routes to outlying star\n" + "systems is in dispute.\n" + "\n" + "Hoping to resolve the matter\n" + "with a blockade of %2$s \n" + "battleships, the greedy Trade\n" + "Federation has stopped all\n" + "shipping to the small planet\n" + "of %3$s.\n" + "\n" + "While the Congress of the\n" + "Republic endlessly debates\n" + "this %4$s chain of events,\n" + "the Supreme Chancellor has\n" + "secretly dispatched two %5$s \n" + "Knights, the guardians of\n" + "peace and justice in the\n" + "galaxy, to settle the conflict....", word1, word2, word3, word4, word5); System.out.println(myText); input.close(); } public static void main(String[] args) { new Example(); } }
UTF-8
Java
1,639
java
Example.java
Java
[]
null
[]
package lydia.porter.ch4_5; import java.util.*; public class Example { public Example() { Scanner input = new Scanner(System.in); System.out.println("type something in"); String word1 = input.nextLine(); //grabs next line of text that comes in String word2 = input.nextLine(); String word3 = input.nextLine(); String word4 = input.nextLine(); String word5 = input.nextLine(); //String.format("The input format parameter", "Object parameter"); //precision: how many decimal points? // %[parameter_index$][flags][width] //%s String result = String.format("Three %(d blind mice %2$tr", -2856935, Calendar.getInstance( )); System.out.println(result); //System.out.print("enter in a word"); //String word1 -input.nextLine(); String myText = String.format("Turmoil has engulfed the\n" + " %1$s Republic. The taxation\n" + "of trade routes to outlying star\n" + "systems is in dispute.\n" + "\n" + "Hoping to resolve the matter\n" + "with a blockade of %2$s \n" + "battleships, the greedy Trade\n" + "Federation has stopped all\n" + "shipping to the small planet\n" + "of %3$s.\n" + "\n" + "While the Congress of the\n" + "Republic endlessly debates\n" + "this %4$s chain of events,\n" + "the Supreme Chancellor has\n" + "secretly dispatched two %5$s \n" + "Knights, the guardians of\n" + "peace and justice in the\n" + "galaxy, to settle the conflict....", word1, word2, word3, word4, word5); System.out.println(myText); input.close(); } public static void main(String[] args) { new Example(); } }
1,639
0.635754
0.61989
58
27.258621
21.596264
98
false
false
0
0
0
0
0
0
2.793103
false
false
14
27a2a718084b018780abb904d63a78861223b14e
34,479,997,454,437
fffe714578b23739acd445d4a212ebde99c1cfeb
/Team-5-TCSS-450/app/src/main/java/edu/uw/tcss450/team_5_tcss_450/ui/chat/CreateGroupChatFragment.java
7f6a9088082c353e1f295a44d2830fe6cf017d64
[]
no_license
IJones52/Anabatos-Clone
https://github.com/IJones52/Anabatos-Clone
61250807fa56613ecbed207aa693fd09e920fa40
267facb36448c862ed93b75750211e7d14126c8b
refs/heads/main
2023-06-02T03:15:24.965000
2021-06-20T21:51:39
2021-06-20T21:51:39
378,744,061
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package edu.uw.tcss450.team_5_tcss_450.ui.chat; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.Navigation; import com.google.android.material.snackbar.Snackbar; import java.util.ArrayList; import java.util.List; import edu.uw.tcss450.team_5_tcss_450.R; import edu.uw.tcss450.team_5_tcss_450.databinding.FragmentCreateGroupChatBinding; import edu.uw.tcss450.team_5_tcss_450.model.UserInfoViewModel; import edu.uw.tcss450.team_5_tcss_450.ui.connections.Connection; import edu.uw.tcss450.team_5_tcss_450.ui.connections.ConnectionsViewModel; /** * A dialog that allows the user to select the connections they want to create a group chat. * * @author Khue Nguyen * @version 6/5/2021 */ public class CreateGroupChatFragment extends DialogFragment { /** * Connection view model. */ ConnectionsViewModel mConnectionModel; /** * User info view model. */ UserInfoViewModel mUserModel; /** * Chat list view model. */ ChatListViewModel mChatModel; /** * Determines whether list is retrieved initially or not. */ private boolean isInit = true; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NORMAL, R.style.FullscreenDialogTheme); ViewModelProvider provider = new ViewModelProvider(getActivity()); mConnectionModel = provider.get(ConnectionsViewModel.class); mUserModel = provider.get(UserInfoViewModel.class); mConnectionModel.getConnections(mUserModel.getmId()); mChatModel = provider.get(ChatListViewModel.class); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_create_group_chat, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); FragmentCreateGroupChatBinding binding = FragmentCreateGroupChatBinding.bind(view); List<Connection> selectedUsers = new ArrayList<>(); mConnectionModel.addConnectionListObserver(getViewLifecycleOwner(), list -> { binding.recyclerConnections.setAdapter(new CreateGroupChatRecyclerViewAdapter(list, new CreateGroupChatRecyclerViewAdapter.OnUserSelectedListener() { @Override public void onUserSelected(Connection connection) { if (!selectedUsers.contains(connection)) { selectedUsers.add(connection); } Log.d("selectedUsers", selectedUsers.toString()); } @Override public void onUserUnselected(Connection connection) { selectedUsers.remove(connection); Log.d("selectedUsers", selectedUsers.toString()); } })); }); binding.buttonClose.setOnClickListener(button -> dismiss()); binding.buttonCreateChat.setOnClickListener(button -> { if (selectedUsers.size() < 2) { Snackbar.make(view, "Please select at least two users in order to create a group chat.", Snackbar.LENGTH_SHORT).show(); } else if (binding.editGroupName.getText().toString().trim().length() == 0) { Snackbar.make(view, "Please enter a group name.", Snackbar.LENGTH_SHORT).show(); } else { String name = binding.editGroupName.getText().toString(); mChatModel.createGroupChatRoom(name, selectedUsers, mUserModel.getmJwt()); } }); mChatModel.addChatListObserver(getViewLifecycleOwner(), this::observeChatList); } /** * Observes changes in the chat list. If chat list is updated initially then don't do anything. * Otherwise, navigate to that chat room. * * @param list the list of chat rooms */ private void observeChatList(List<ChatRoomInfo> list) { if (isInit) { isInit = false; Log.d("observeChatList", "initial list values"); } else { Log.d("observeChatList", "chat list updated: " + list.toString()); Navigation.findNavController(getParentFragment().getView()).navigate( CreateGroupChatFragmentDirections .actionCreateGroupChatFragmentToChatRoomFragment(list.get(0))); dismiss(); } } }
UTF-8
Java
5,097
java
CreateGroupChatFragment.java
Java
[ { "context": "ns they want to create a group chat.\n *\n * @author Khue Nguyen\n * @version 6/5/2021\n */\npublic class CreateGroup", "end": 953, "score": 0.9998076558113098, "start": 942, "tag": "NAME", "value": "Khue Nguyen" } ]
null
[]
package edu.uw.tcss450.team_5_tcss_450.ui.chat; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.Navigation; import com.google.android.material.snackbar.Snackbar; import java.util.ArrayList; import java.util.List; import edu.uw.tcss450.team_5_tcss_450.R; import edu.uw.tcss450.team_5_tcss_450.databinding.FragmentCreateGroupChatBinding; import edu.uw.tcss450.team_5_tcss_450.model.UserInfoViewModel; import edu.uw.tcss450.team_5_tcss_450.ui.connections.Connection; import edu.uw.tcss450.team_5_tcss_450.ui.connections.ConnectionsViewModel; /** * A dialog that allows the user to select the connections they want to create a group chat. * * @author <NAME> * @version 6/5/2021 */ public class CreateGroupChatFragment extends DialogFragment { /** * Connection view model. */ ConnectionsViewModel mConnectionModel; /** * User info view model. */ UserInfoViewModel mUserModel; /** * Chat list view model. */ ChatListViewModel mChatModel; /** * Determines whether list is retrieved initially or not. */ private boolean isInit = true; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStyle(DialogFragment.STYLE_NORMAL, R.style.FullscreenDialogTheme); ViewModelProvider provider = new ViewModelProvider(getActivity()); mConnectionModel = provider.get(ConnectionsViewModel.class); mUserModel = provider.get(UserInfoViewModel.class); mConnectionModel.getConnections(mUserModel.getmId()); mChatModel = provider.get(ChatListViewModel.class); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_create_group_chat, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); FragmentCreateGroupChatBinding binding = FragmentCreateGroupChatBinding.bind(view); List<Connection> selectedUsers = new ArrayList<>(); mConnectionModel.addConnectionListObserver(getViewLifecycleOwner(), list -> { binding.recyclerConnections.setAdapter(new CreateGroupChatRecyclerViewAdapter(list, new CreateGroupChatRecyclerViewAdapter.OnUserSelectedListener() { @Override public void onUserSelected(Connection connection) { if (!selectedUsers.contains(connection)) { selectedUsers.add(connection); } Log.d("selectedUsers", selectedUsers.toString()); } @Override public void onUserUnselected(Connection connection) { selectedUsers.remove(connection); Log.d("selectedUsers", selectedUsers.toString()); } })); }); binding.buttonClose.setOnClickListener(button -> dismiss()); binding.buttonCreateChat.setOnClickListener(button -> { if (selectedUsers.size() < 2) { Snackbar.make(view, "Please select at least two users in order to create a group chat.", Snackbar.LENGTH_SHORT).show(); } else if (binding.editGroupName.getText().toString().trim().length() == 0) { Snackbar.make(view, "Please enter a group name.", Snackbar.LENGTH_SHORT).show(); } else { String name = binding.editGroupName.getText().toString(); mChatModel.createGroupChatRoom(name, selectedUsers, mUserModel.getmJwt()); } }); mChatModel.addChatListObserver(getViewLifecycleOwner(), this::observeChatList); } /** * Observes changes in the chat list. If chat list is updated initially then don't do anything. * Otherwise, navigate to that chat room. * * @param list the list of chat rooms */ private void observeChatList(List<ChatRoomInfo> list) { if (isInit) { isInit = false; Log.d("observeChatList", "initial list values"); } else { Log.d("observeChatList", "chat list updated: " + list.toString()); Navigation.findNavController(getParentFragment().getView()).navigate( CreateGroupChatFragmentDirections .actionCreateGroupChatFragmentToChatRoomFragment(list.get(0))); dismiss(); } } }
5,092
0.643123
0.633117
133
37.323307
31.302441
132
false
false
0
0
0
0
0
0
0.548872
false
false
14
2867cdbcf16b99d95a3fe18de8b7ad0e26292153
12,214,887,051,613
10e60a2a3a6ead8d7bd4090966f61d1dc1fd88b9
/COP/src/service/chuanhoa.java
6661a8c61034b6075db264d9d20683a587c34237
[]
no_license
hongsonflute/chuanhoaxau
https://github.com/hongsonflute/chuanhoaxau
e97cf1f93011903754e170679414634b0a270b01
36119a9892f2af4ce28e5a3b0dab66d5ddf6ec1e
refs/heads/master
2020-04-05T10:40:54.139000
2018-11-11T03:43:41
2018-11-11T03:43:41
156,806,221
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package service; import java.util.regex.Matcher; import java.util.regex.Pattern; public class chuanhoa { /* public static void main(String[] args) { String s = new Scanner(System.in).nextLine(); System.out.println("Xau truoc khi chuan hoa: \n"+s); System.out.println("Xau sau khi chuan hoa: \n"+getRes(s.toLowerCase()).toString()); System.out.println(""); } */ public static StringBuilder getRes(String s ){ Pattern pattern = Pattern.compile("\\s+"); Matcher matcher = pattern.matcher(s); StringBuilder sb = new StringBuilder(matcher.replaceAll(" ")); if(sb.charAt(0) == ' ') sb.deleteCharAt(0); if( sb.charAt(sb.length()-1) == ' ') sb.deleteCharAt(sb.length()-1); for( int i = 0; i< sb.length(); i++ ){ if( i < sb.length()-1 ){ if( (sb.charAt(i) == ',' || sb.charAt(i) == '.' || sb.charAt(i) == '?' || sb.charAt(i) == ';' || sb.charAt(i) == ':' || sb.charAt(i) == '!') && sb.charAt(i+1) != ' '){ sb.insert(i+1, " "); } } } for( int i = 0; i< sb.length(); i++ ){ if( i < sb.length()-1 ){ if( (sb.charAt(i+1) == ',' || sb.charAt(i+1) == '.' || sb.charAt(i+1) == '?' || sb.charAt(1+i) == ';' || sb.charAt(i+1) == ':' || sb.charAt(1+i) == '!') && sb.charAt(i) == ' '){ sb.deleteCharAt(i); } } } sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); for( int i = 0; i< sb.length(); i++ ){ if( i < sb.length()-2 ){ if( sb.charAt(i) == '.' || sb.charAt(i) == '?' || sb.charAt(i) == '!'){ sb.setCharAt(i+2, Character.toUpperCase(sb.charAt(2+i))); } } } return sb; } }
UTF-8
Java
1,986
java
chuanhoa.java
Java
[]
null
[]
package service; import java.util.regex.Matcher; import java.util.regex.Pattern; public class chuanhoa { /* public static void main(String[] args) { String s = new Scanner(System.in).nextLine(); System.out.println("Xau truoc khi chuan hoa: \n"+s); System.out.println("Xau sau khi chuan hoa: \n"+getRes(s.toLowerCase()).toString()); System.out.println(""); } */ public static StringBuilder getRes(String s ){ Pattern pattern = Pattern.compile("\\s+"); Matcher matcher = pattern.matcher(s); StringBuilder sb = new StringBuilder(matcher.replaceAll(" ")); if(sb.charAt(0) == ' ') sb.deleteCharAt(0); if( sb.charAt(sb.length()-1) == ' ') sb.deleteCharAt(sb.length()-1); for( int i = 0; i< sb.length(); i++ ){ if( i < sb.length()-1 ){ if( (sb.charAt(i) == ',' || sb.charAt(i) == '.' || sb.charAt(i) == '?' || sb.charAt(i) == ';' || sb.charAt(i) == ':' || sb.charAt(i) == '!') && sb.charAt(i+1) != ' '){ sb.insert(i+1, " "); } } } for( int i = 0; i< sb.length(); i++ ){ if( i < sb.length()-1 ){ if( (sb.charAt(i+1) == ',' || sb.charAt(i+1) == '.' || sb.charAt(i+1) == '?' || sb.charAt(1+i) == ';' || sb.charAt(i+1) == ':' || sb.charAt(1+i) == '!') && sb.charAt(i) == ' '){ sb.deleteCharAt(i); } } } sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); for( int i = 0; i< sb.length(); i++ ){ if( i < sb.length()-2 ){ if( sb.charAt(i) == '.' || sb.charAt(i) == '?' || sb.charAt(i) == '!'){ sb.setCharAt(i+2, Character.toUpperCase(sb.charAt(2+i))); } } } return sb; } }
1,986
0.425982
0.414904
53
36.471699
28.253304
99
false
false
0
0
0
0
0
0
1.056604
false
false
14
ca6bcf89226392b7ad9d0ff89f702ec69dfc6605
25,091,198,982,040
742eb76fc44476bf3ffc42d827e17018a3e0f4f9
/code/labori/src/java/mb/CadastroMB.java
ea2e46a3aa9d30dac2a180621d64ead81d4cccf0
[]
no_license
asimiscuka/labori
https://github.com/asimiscuka/labori
b2a87dc7c08a99683327492f6441667b75500790
ebdb308dd76c8cc307b5462f5f20ed879b78e29d
refs/heads/master
2020-12-24T10:41:43.359000
2012-08-30T20:09:23
2012-08-30T20:09:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mb; import dao.IDAO; import dao.impl.UsuarioDAOImpl; import entity.Usuario; import java.io.Serializable; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; @ManagedBean @ViewScoped public class CadastroMB implements Serializable { private static final long serialVersionUID = 1L; private Usuario usuario; public CadastroMB() { this.usuario = new Usuario(); } public void criarConta() { try { IDAO dao = new UsuarioDAOImpl(); dao.create(usuario); FacesMessage message = new FacesMessage("Usuário criado com sucesso!"); FacesContext.getCurrentInstance().addMessage(null, message); } catch (Exception e) { FacesMessage message = new FacesMessage("Houve um erro ao salvar: " + e); FacesContext.getCurrentInstance().addMessage(null, message); } } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } }
UTF-8
Java
1,080
java
CadastroMB.java
Java
[]
null
[]
package mb; import dao.IDAO; import dao.impl.UsuarioDAOImpl; import entity.Usuario; import java.io.Serializable; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; @ManagedBean @ViewScoped public class CadastroMB implements Serializable { private static final long serialVersionUID = 1L; private Usuario usuario; public CadastroMB() { this.usuario = new Usuario(); } public void criarConta() { try { IDAO dao = new UsuarioDAOImpl(); dao.create(usuario); FacesMessage message = new FacesMessage("Usuário criado com sucesso!"); FacesContext.getCurrentInstance().addMessage(null, message); } catch (Exception e) { FacesMessage message = new FacesMessage("Houve um erro ao salvar: " + e); FacesContext.getCurrentInstance().addMessage(null, message); } } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } }
1,080
0.71177
0.710843
46
21.456522
21.15749
76
false
false
0
0
0
0
0
0
1.478261
false
false
14
0cbf847c90941ebb0b5b42981382aa7c3621abca
25,091,198,978,475
e9b80e12103fa1dc99644e4f58781e173ae9a61e
/Gra/src/WyslanieWyniku.java
fa6f0668936111dc8419e202ca77c0af35cd2af3
[]
no_license
StJakub/Sciezka
https://github.com/StJakub/Sciezka
81fa5a2dd1b8eb07536c5a66d9e63c144bd1d70e
b5d2046bb2d3e2841bbcdd2d035a9fa7fe01e183
refs/heads/master
2020-05-09T17:14:54.827000
2019-04-14T12:06:59
2019-04-14T12:06:59
181,302,164
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.OutputStream; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; /** * Klasa odpowiedzialna za wysłanie wyniku do serwera * @author Jakub Stanisław * */ public class WyslanieWyniku implements Runnable { private String login; private int punkty; private int port; private InetAddress host; /** * * @param login - login gracza * @param punkty - punkty uzyskane podczas rozgrywki * @param port - port, na którym następuje komunikacja między serwerem a klientem * @param host - adres IP */ public WyslanieWyniku(String login, int punkty, int port, InetAddress host) { this.login = login; this.punkty = punkty; this.port = port; this.host = host; } @Override public void run() { try { Socket socket = new Socket(host, port); OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os, true); pw.println(SerwerGry.przeslaniePunktow); pw.println(login); pw.println(punkty); socket.close(); } catch (Exception e) { System.err.println("Client exception: " + e); } } }
WINDOWS-1250
Java
1,117
java
WyslanieWyniku.java
Java
[ { "context": "iedzialna za wysłanie wyniku do serwera\n * @author Jakub Stanisław\n *\n */\npublic class WyslanieWyniku implements Run", "end": 195, "score": 0.9998364448547363, "start": 180, "tag": "NAME", "value": "Jakub Stanisław" } ]
null
[]
import java.io.OutputStream; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; /** * Klasa odpowiedzialna za wysłanie wyniku do serwera * @author <NAME> * */ public class WyslanieWyniku implements Runnable { private String login; private int punkty; private int port; private InetAddress host; /** * * @param login - login gracza * @param punkty - punkty uzyskane podczas rozgrywki * @param port - port, na którym następuje komunikacja między serwerem a klientem * @param host - adres IP */ public WyslanieWyniku(String login, int punkty, int port, InetAddress host) { this.login = login; this.punkty = punkty; this.port = port; this.host = host; } @Override public void run() { try { Socket socket = new Socket(host, port); OutputStream os = socket.getOutputStream(); PrintWriter pw = new PrintWriter(os, true); pw.println(SerwerGry.przeslaniePunktow); pw.println(login); pw.println(punkty); socket.close(); } catch (Exception e) { System.err.println("Client exception: " + e); } } }
1,107
0.690647
0.690647
53
19.943396
19.638636
82
false
false
0
0
0
0
0
0
1.735849
false
false
14
6cf5c01975eb7287fb6d07aeaeaae377210df73c
20,925,080,731,504
fdd8aad32bd6f8813cf1f53ab00a3a8cf6f5b5a5
/src/console/ConsoleReader.java
2a3021d55c13ec05c6f24eb04e51e227799d8189
[]
no_license
PetrEconomist/partsTreeProject
https://github.com/PetrEconomist/partsTreeProject
e363af100e7196875bf81e2cf27c2681eb724773
f281e8a137845f471e3a630ca5d8e2fa9b47d547
refs/heads/main
2023-05-08T10:20:48.578000
2021-05-24T18:45:48
2021-05-24T18:45:48
316,280,381
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package console; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ConsoleReader { public static String getStringFromConsole(String message) { System.out.printf("%s\n", message); //Enter data using BufferReader BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //Reading data using readLine String input = ""; try { input = reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return input; } }
UTF-8
Java
589
java
ConsoleReader.java
Java
[]
null
[]
package console; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ConsoleReader { public static String getStringFromConsole(String message) { System.out.printf("%s\n", message); //Enter data using BufferReader BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //Reading data using readLine String input = ""; try { input = reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return input; } }
589
0.696095
0.696095
27
20.814816
20.695387
87
false
false
0
0
0
0
0
0
1.333333
false
false
14
2454c52d6d6c401caf45e8505ec70296cf3080e4
32,255,204,421,775
89050d714d31b72232cdaeed588dc70ebe20f098
/SPSEJBService/ejbModule/estimate/model/Spstdesthmt.java
c1ea78374a966d2061fffa2c91528dd154e7e833
[]
no_license
se3mis/SPS_VERSION
https://github.com/se3mis/SPS_VERSION
8c185823b2e7ded17a8bd1a84a4bd5eaf7874b8d
50f25979a095e94125c57ca2604d41969f873de9
refs/heads/master
2016-09-14T01:55:23.537000
2016-05-06T05:56:38
2016-05-06T05:56:38
58,184,917
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package estimate.model; import java.io.Serializable; import javax.persistence.*; import java.math.BigDecimal; import java.util.Date; /** * The persistent class for the PCESTHTT database table. * */ @Entity public class Spstdesthmt implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId private SpstdesthmtPK id; @Column(name="JOBNAME") private String jobName; @Column(name="CONTINGENCY") private String contigency; @Column(name="DESCRIPTION") private String description; @Column(name="VATCOST") private BigDecimal vatcost; @Column(name="NBTCOST") private BigDecimal nbtcost; @Column(name="TOTAL_COST") private BigDecimal totalCost; @Column(name="SECDEPOSIT") private BigDecimal secDeposit; @Column(name="STATUS") private Long status; // number @Column(name="ENTRY_BY") private String entryBy; @Temporal( TemporalType.DATE) @Column(name="ENTRY_DATE") private Date entryDate; @Column(name="VALIDATE_BY_EE") private String validateByEE; @Temporal( TemporalType.DATE) @Column(name="VALIDATE_DATE_EE") private Date validateDateEE; @Column(name="VALIDATE_BY_CE") private String validateByCE; @Temporal( TemporalType.DATE) @Column(name="VALIDATE_DATE_CE") private Date validateDateCE; @Column(name="SINNO") private String sinNo; // number @Column(name="SINNO1") private String sinNo1; // number public String getSinNo1() { return sinNo1; } public void setSinNo1(String sinNo1) { this.sinNo1 = sinNo1; } @Column(name="SINNO2") private String sinNo2; // number public String getSinNo2() { return sinNo2; } public void setSinNo2(String sinNo2) { this.sinNo2 = sinNo2; } @Column(name="SINNO3") private String sinNo3; // number public String getSinNo3() { return sinNo3; } public void setSinNo3(String sinNo3) { this.sinNo3 = sinNo3; } @Column(name="SINNO4") private String sinNo4; // number public String getSinNo4() { return sinNo4; } public void setSinNo4(String sinNo4) { this.sinNo4 = sinNo4; } @Column(name="APPROVED_BY") private String approvedBy; @Temporal( TemporalType.DATE) @Column(name="APPROVED_DATE") private Date approvedDate; @Column(name="REJECTED_BY") private String rejectedBy; @Temporal( TemporalType.DATE) @Column(name="REJECTED_DATE") private Date rejectedDate; @Column(name="REJ_REASON_EE") private String rejReasonEE; @Column(name="REJ_RESON_CE") private String rejReasonCE; @Column(name="REJ_RESON_PE") private String rejReasonPE; @Column(name="PLANING_BY") private String planningBy; @Temporal( TemporalType.DATE) @Column(name="PLANING_DATE") private Date planningDate; @Column(name="POST_DEPTID") private String postDeptId; @Column(name="REBATE_COST") private BigDecimal rebateCost; @Column(name="CEBCOST") private BigDecimal cebCost; @Column(name="TOCONPAY") private BigDecimal toConpay; @Column(name="LINE_LENGTH") private BigDecimal line_length; public BigDecimal getLine_length() { return line_length; } public void setLine_length(BigDecimal line_length) { this.line_length = line_length; } @Column(name="CON_COST") private BigDecimal conCost; @Column(name="PROJECTTYPE") private String projectType; @Column(name="ASSIGNEDTO") private String assignTo; @Column(name="COMMENT_PE") private String com_pe; @Column(name="COMMENT_EE") private String com_ee; @Column(name="COMMENT_CE") private String com_ce; @Column(name="COMMENT_PCE") private String com_pce; @Column(name="COMMENT_DGM") private String com_dgm; @Column(name="COMMENT_ES") private String com_es; public String getCom_es() { return com_es; } public void setCom_es(String com_es) { this.com_es = com_es; } @Column(name="VAT") private String vat; public Spstdesthmt() { } public SpstdesthmtPK getId() { return id; } public void setId(SpstdesthmtPK id) { this.id = id; } public String getCom_dgm() { return com_dgm; } public void setCom_dgm(String com_dgm) { this.com_dgm = com_dgm; } public String getCom_pce() { return com_pce; } public void setCom_pce(String com_pce) { this.com_pce = com_pce; } public String getCom_pe() { return com_pe; } public void setCom_pe(String com_pe) { this.com_pe = com_pe; } public String getCom_ee() { return com_ee; } public void setCom_ee(String com_ee) { this.com_ee = com_ee; } public String getCom_ce() { return com_ce; } public void setCom_ce(String com_ce) { this.com_ce = com_ce; } public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getContigency() { return contigency; } public String getAssignTo() { return assignTo; } public void setAssignTo(String assignTo) { this.assignTo = assignTo; } public void setContigency(String contigency) { this.contigency = contigency; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public BigDecimal getTotalCost() { return totalCost; } public void setTotalCost(BigDecimal totalCost) { this.totalCost = totalCost; } public String getSinNo() { return sinNo; } public void setSinNo(String sinNo) { this.sinNo = sinNo; } public String getEntryBy() { return entryBy; } public void setEntryBy(String entryBy) { this.entryBy = entryBy; } public BigDecimal getSecDeposit() { return secDeposit; } public void setSecDeposit(BigDecimal secDeposit) { this.secDeposit = secDeposit; } public Long getStatus() { return status; } public void setStatus(Long status) { this.status = status; } public Date getEntryDate() { return entryDate; } public void setEntryDate(Date entryDate) { this.entryDate = entryDate; } public String getApprovedBy() { return approvedBy; } public void setApprovedBy(String approvedBy) { this.approvedBy = approvedBy; } public Date getApprovedDate() { return approvedDate; } public void setApprovedDate(Date approvedDate) { this.approvedDate = approvedDate; } public String getRejectedBy() { return rejectedBy; } public void setRejectedBy(String rejectedBy) { this.rejectedBy = rejectedBy; } public Date getRejectedDate() { return rejectedDate; } public void setRejectedDate(Date rejectedDate) { this.rejectedDate = rejectedDate; } public String getRejReasonCE() { return rejReasonCE; } public void setRejReasonCE(String rejReasonCE) { this.rejReasonCE = rejReasonCE; } public String getPlanningBy() { return planningBy; } public void setPlanningBy(String planningBy) { this.planningBy = planningBy; } public Date getPlanningDate() { return planningDate; } public void setPlanningDate(Date planningDate) { this.planningDate = planningDate; } public String getPostDeptId() { return postDeptId; } public void setPostDeptId(String postDeptId) { this.postDeptId = postDeptId; } public BigDecimal getRebateCost() { return rebateCost; } public void setRebateCost(BigDecimal rebateCost) { this.rebateCost = rebateCost; } public BigDecimal getCebCost() { return cebCost; } public void setCebCost(BigDecimal cebCost) { this.cebCost = cebCost; } public BigDecimal getToConpay() { return toConpay; } public void setToConpay(BigDecimal toConpay) { this.toConpay = toConpay; } public String getVat() { return vat; } public void setVat(String vat) { this.vat = vat; } public BigDecimal getConCost() { return conCost; } public void setVatcost(BigDecimal vatCost) { this.vatcost = vatCost; } public BigDecimal getVatcost() { return vatcost; } public void setNbtcost(BigDecimal nbtCost) { this.nbtcost = nbtCost; } public BigDecimal getNbtcost() { return nbtcost; } public void setConCost(BigDecimal conCost) { this.conCost = conCost; } public String getProjectType() { return projectType; } public void setProjectType(String projectType) { this.projectType = projectType; } public String getValidateByEE() { return validateByEE; } public void setValidateByEE(String validateByEE) { this.validateByEE = validateByEE; } public Date getValidateDateEE() { return validateDateEE; } public void setValidateDateEE(Date validateDateEE) { this.validateDateEE = validateDateEE; } public String getValidateByCE() { return validateByCE; } public void setValidateByCE(String validateByCE) { this.validateByCE = validateByCE; } public Date getValidateDateCE() { return validateDateCE; } public void setValidateDateCE(Date validateDateCE) { this.validateDateCE = validateDateCE; } public String getRejReasonEE() { return rejReasonEE; } public void setRejReasonEE(String rejReasonEE) { this.rejReasonEE = rejReasonEE; } public String getRejReasonPE() { return rejReasonPE; } public void setRejReasonPE(String rejReasonPE) { this.rejReasonPE = rejReasonPE; } @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append("SpstaymtPK [id=").append( id ); buf.append(", jobName=").append( jobName); buf.append(", contigency=").append( contigency); buf.append(", description=").append( description); buf.append(", vatCost=").append( vatcost); buf.append(", nbtCost=").append( nbtcost); buf.append(", totalCost=").append( totalCost); buf.append(", secDeposit=").append( secDeposit); //buf.append(", deptId=").append( deptId); buf.append(", status=").append( status); buf.append(", entryDate=").append( entryDate); buf.append(", validateDate=").append( validateDateEE); buf.append(", approvedBy=").append( approvedBy); buf.append(", approvedDate=").append( approvedDate); buf.append(", rejectedBy=").append( rejectedBy); buf.append(", rejectedDate=").append( rejectedDate); buf.append(", rejReasonCE=").append( rejReasonCE); buf.append(", rejReason=").append( rejReasonEE); buf.append(", planningBy=").append( planningBy); buf.append(", planningDate=").append( planningDate); buf.append(", postDeptId=").append( postDeptId); buf.append(", rebateCost=").append( rebateCost); buf.append(", cebCost=").append( cebCost); buf.append(", conCost=").append( conCost); buf.append(", projectType=").append( projectType).append("]"); buf.append(", line_length=").append( line_length).append("]"); return buf.toString(); } }
UTF-8
Java
10,654
java
Spstdesthmt.java
Java
[]
null
[]
package estimate.model; import java.io.Serializable; import javax.persistence.*; import java.math.BigDecimal; import java.util.Date; /** * The persistent class for the PCESTHTT database table. * */ @Entity public class Spstdesthmt implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId private SpstdesthmtPK id; @Column(name="JOBNAME") private String jobName; @Column(name="CONTINGENCY") private String contigency; @Column(name="DESCRIPTION") private String description; @Column(name="VATCOST") private BigDecimal vatcost; @Column(name="NBTCOST") private BigDecimal nbtcost; @Column(name="TOTAL_COST") private BigDecimal totalCost; @Column(name="SECDEPOSIT") private BigDecimal secDeposit; @Column(name="STATUS") private Long status; // number @Column(name="ENTRY_BY") private String entryBy; @Temporal( TemporalType.DATE) @Column(name="ENTRY_DATE") private Date entryDate; @Column(name="VALIDATE_BY_EE") private String validateByEE; @Temporal( TemporalType.DATE) @Column(name="VALIDATE_DATE_EE") private Date validateDateEE; @Column(name="VALIDATE_BY_CE") private String validateByCE; @Temporal( TemporalType.DATE) @Column(name="VALIDATE_DATE_CE") private Date validateDateCE; @Column(name="SINNO") private String sinNo; // number @Column(name="SINNO1") private String sinNo1; // number public String getSinNo1() { return sinNo1; } public void setSinNo1(String sinNo1) { this.sinNo1 = sinNo1; } @Column(name="SINNO2") private String sinNo2; // number public String getSinNo2() { return sinNo2; } public void setSinNo2(String sinNo2) { this.sinNo2 = sinNo2; } @Column(name="SINNO3") private String sinNo3; // number public String getSinNo3() { return sinNo3; } public void setSinNo3(String sinNo3) { this.sinNo3 = sinNo3; } @Column(name="SINNO4") private String sinNo4; // number public String getSinNo4() { return sinNo4; } public void setSinNo4(String sinNo4) { this.sinNo4 = sinNo4; } @Column(name="APPROVED_BY") private String approvedBy; @Temporal( TemporalType.DATE) @Column(name="APPROVED_DATE") private Date approvedDate; @Column(name="REJECTED_BY") private String rejectedBy; @Temporal( TemporalType.DATE) @Column(name="REJECTED_DATE") private Date rejectedDate; @Column(name="REJ_REASON_EE") private String rejReasonEE; @Column(name="REJ_RESON_CE") private String rejReasonCE; @Column(name="REJ_RESON_PE") private String rejReasonPE; @Column(name="PLANING_BY") private String planningBy; @Temporal( TemporalType.DATE) @Column(name="PLANING_DATE") private Date planningDate; @Column(name="POST_DEPTID") private String postDeptId; @Column(name="REBATE_COST") private BigDecimal rebateCost; @Column(name="CEBCOST") private BigDecimal cebCost; @Column(name="TOCONPAY") private BigDecimal toConpay; @Column(name="LINE_LENGTH") private BigDecimal line_length; public BigDecimal getLine_length() { return line_length; } public void setLine_length(BigDecimal line_length) { this.line_length = line_length; } @Column(name="CON_COST") private BigDecimal conCost; @Column(name="PROJECTTYPE") private String projectType; @Column(name="ASSIGNEDTO") private String assignTo; @Column(name="COMMENT_PE") private String com_pe; @Column(name="COMMENT_EE") private String com_ee; @Column(name="COMMENT_CE") private String com_ce; @Column(name="COMMENT_PCE") private String com_pce; @Column(name="COMMENT_DGM") private String com_dgm; @Column(name="COMMENT_ES") private String com_es; public String getCom_es() { return com_es; } public void setCom_es(String com_es) { this.com_es = com_es; } @Column(name="VAT") private String vat; public Spstdesthmt() { } public SpstdesthmtPK getId() { return id; } public void setId(SpstdesthmtPK id) { this.id = id; } public String getCom_dgm() { return com_dgm; } public void setCom_dgm(String com_dgm) { this.com_dgm = com_dgm; } public String getCom_pce() { return com_pce; } public void setCom_pce(String com_pce) { this.com_pce = com_pce; } public String getCom_pe() { return com_pe; } public void setCom_pe(String com_pe) { this.com_pe = com_pe; } public String getCom_ee() { return com_ee; } public void setCom_ee(String com_ee) { this.com_ee = com_ee; } public String getCom_ce() { return com_ce; } public void setCom_ce(String com_ce) { this.com_ce = com_ce; } public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getContigency() { return contigency; } public String getAssignTo() { return assignTo; } public void setAssignTo(String assignTo) { this.assignTo = assignTo; } public void setContigency(String contigency) { this.contigency = contigency; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public BigDecimal getTotalCost() { return totalCost; } public void setTotalCost(BigDecimal totalCost) { this.totalCost = totalCost; } public String getSinNo() { return sinNo; } public void setSinNo(String sinNo) { this.sinNo = sinNo; } public String getEntryBy() { return entryBy; } public void setEntryBy(String entryBy) { this.entryBy = entryBy; } public BigDecimal getSecDeposit() { return secDeposit; } public void setSecDeposit(BigDecimal secDeposit) { this.secDeposit = secDeposit; } public Long getStatus() { return status; } public void setStatus(Long status) { this.status = status; } public Date getEntryDate() { return entryDate; } public void setEntryDate(Date entryDate) { this.entryDate = entryDate; } public String getApprovedBy() { return approvedBy; } public void setApprovedBy(String approvedBy) { this.approvedBy = approvedBy; } public Date getApprovedDate() { return approvedDate; } public void setApprovedDate(Date approvedDate) { this.approvedDate = approvedDate; } public String getRejectedBy() { return rejectedBy; } public void setRejectedBy(String rejectedBy) { this.rejectedBy = rejectedBy; } public Date getRejectedDate() { return rejectedDate; } public void setRejectedDate(Date rejectedDate) { this.rejectedDate = rejectedDate; } public String getRejReasonCE() { return rejReasonCE; } public void setRejReasonCE(String rejReasonCE) { this.rejReasonCE = rejReasonCE; } public String getPlanningBy() { return planningBy; } public void setPlanningBy(String planningBy) { this.planningBy = planningBy; } public Date getPlanningDate() { return planningDate; } public void setPlanningDate(Date planningDate) { this.planningDate = planningDate; } public String getPostDeptId() { return postDeptId; } public void setPostDeptId(String postDeptId) { this.postDeptId = postDeptId; } public BigDecimal getRebateCost() { return rebateCost; } public void setRebateCost(BigDecimal rebateCost) { this.rebateCost = rebateCost; } public BigDecimal getCebCost() { return cebCost; } public void setCebCost(BigDecimal cebCost) { this.cebCost = cebCost; } public BigDecimal getToConpay() { return toConpay; } public void setToConpay(BigDecimal toConpay) { this.toConpay = toConpay; } public String getVat() { return vat; } public void setVat(String vat) { this.vat = vat; } public BigDecimal getConCost() { return conCost; } public void setVatcost(BigDecimal vatCost) { this.vatcost = vatCost; } public BigDecimal getVatcost() { return vatcost; } public void setNbtcost(BigDecimal nbtCost) { this.nbtcost = nbtCost; } public BigDecimal getNbtcost() { return nbtcost; } public void setConCost(BigDecimal conCost) { this.conCost = conCost; } public String getProjectType() { return projectType; } public void setProjectType(String projectType) { this.projectType = projectType; } public String getValidateByEE() { return validateByEE; } public void setValidateByEE(String validateByEE) { this.validateByEE = validateByEE; } public Date getValidateDateEE() { return validateDateEE; } public void setValidateDateEE(Date validateDateEE) { this.validateDateEE = validateDateEE; } public String getValidateByCE() { return validateByCE; } public void setValidateByCE(String validateByCE) { this.validateByCE = validateByCE; } public Date getValidateDateCE() { return validateDateCE; } public void setValidateDateCE(Date validateDateCE) { this.validateDateCE = validateDateCE; } public String getRejReasonEE() { return rejReasonEE; } public void setRejReasonEE(String rejReasonEE) { this.rejReasonEE = rejReasonEE; } public String getRejReasonPE() { return rejReasonPE; } public void setRejReasonPE(String rejReasonPE) { this.rejReasonPE = rejReasonPE; } @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append("SpstaymtPK [id=").append( id ); buf.append(", jobName=").append( jobName); buf.append(", contigency=").append( contigency); buf.append(", description=").append( description); buf.append(", vatCost=").append( vatcost); buf.append(", nbtCost=").append( nbtcost); buf.append(", totalCost=").append( totalCost); buf.append(", secDeposit=").append( secDeposit); //buf.append(", deptId=").append( deptId); buf.append(", status=").append( status); buf.append(", entryDate=").append( entryDate); buf.append(", validateDate=").append( validateDateEE); buf.append(", approvedBy=").append( approvedBy); buf.append(", approvedDate=").append( approvedDate); buf.append(", rejectedBy=").append( rejectedBy); buf.append(", rejectedDate=").append( rejectedDate); buf.append(", rejReasonCE=").append( rejReasonCE); buf.append(", rejReason=").append( rejReasonEE); buf.append(", planningBy=").append( planningBy); buf.append(", planningDate=").append( planningDate); buf.append(", postDeptId=").append( postDeptId); buf.append(", rebateCost=").append( rebateCost); buf.append(", cebCost=").append( cebCost); buf.append(", conCost=").append( conCost); buf.append(", projectType=").append( projectType).append("]"); buf.append(", line_length=").append( line_length).append("]"); return buf.toString(); } }
10,654
0.697297
0.694199
715
13.902098
16.68227
64
false
false
0
0
0
0
0
0
1.064336
false
false
14
ea27dfcfdd755a6ae6bd09dc928177f1071cc51b
31,164,282,713,911
9b35fd279e128f42cb744b0bdb7086f946d796d7
/src/main/java/com/bookstore/model/Language.java
0020e1da97e2961294493adb472ea7c1b4294d47
[]
no_license
jpscs/bookstore
https://github.com/jpscs/bookstore
5a44953463aa30883914fa4be41f7af5d6201ded
7960c85bd73e5b7853bd6ed5526e85a5e633aaf5
refs/heads/master
2021-01-01T20:15:17.177000
2017-07-31T00:39:48
2017-07-31T00:39:48
98,802,660
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bookstore.model; //List of availlable languages public enum Language { ENGLISH, FRENCH, SPANISH,PORTUGUESE }
UTF-8
Java
129
java
Language.java
Java
[]
null
[]
package com.bookstore.model; //List of availlable languages public enum Language { ENGLISH, FRENCH, SPANISH,PORTUGUESE }
129
0.751938
0.751938
6
19.5
14.044572
36
false
false
0
0
0
0
0
0
0.833333
false
false
14
3621c61203bb286b852be19cbac7b603a604bcd8
1,245,540,565,107
582c09c977ecdbb5a1d4c79a3770b395237a9700
/netbeans-color-codes-preview-spi/src/main/java/com/junichi11/netbeans/modules/color/codes/preview/spi/ColorCodesProvider.java
dfd608c878bfa2b5bfbcaecfafe5701909566c36
[ "Apache-2.0" ]
permissive
arsi-apli/NBANDROID-V2
https://github.com/arsi-apli/NBANDROID-V2
8d3a963075cddb03620249d7f2dd07aa70aa8b35
18f462486d12fcb86735e471f83759124ed594ab
refs/heads/master
2021-05-15T10:19:27.509000
2019-06-28T21:34:26
2019-06-28T21:34:26
108,177,264
1
0
null
true
2017-10-24T20:03:26
2017-10-24T20:03:25
2017-10-24T20:03:08
2017-10-24T20:03:05
0
0
0
0
null
false
null
/* * Copyright 2019 junichi11. * * 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.junichi11.netbeans.modules.color.codes.preview.spi; import java.util.List; import java.util.Map; import javax.swing.text.Document; /** * This provides support for showing the colors for the specific color code in * the editor side bar. You can add your provider via a ServiceProvider * annotation. e.g. * <pre> * &#64;ServiceProvider(service = ColorCodesProvider.class, position = 1000) * public class MyColorCodesProvider implements ColorCodesProvider { * // implementations... * } * </pre> * * @author junichi11, arsi * @since 0.10.0 */ public interface ColorCodesProvider { /** * Get the id for the specific provider. * * @return the id for the specific provider */ public String getId(); /** * Get the display name. * * @return the display name */ public String getDisplayName(); /** * Get the description. * * @return the description */ public String getDescription(); /** * Is this provider enabled. * * @since 0.10.0 * @param document the document * @return {@code true} if enabled, otherwise {@code false} */ public boolean isProviderEnabled(Document document); /** * Parse the line then return color values. * * @since 0.10.0 * @param document the document * @param line the string to parse * @param lineNumber line number to store to ColorValue * @param variableColorValues save colors of variables to this map * @return color values */ public List<ColorValue> getColorValues(Document document, String line, int lineNumber, Map<String, List<ColorValue>> variableColorValues); /** * Get the start position for parsing lines. * * @since 0.10.0 * @param document the document * @param currentIndex the line number * @return the line number to start parsing */ public int getStartIndex(Document document, int currentIndex); /** * Get the panel for Options. * * @since 0.11.1 * @return the panel for Options */ public ColorCodesPreviewOptionsPanel getOptionsPanel(); /** * Check whether this provider provides generating color code feature. If it * is provided, please return ColorCodeGeneratorItems in * getColorCodeGeneratorItems(). * * @since 0.12.1 * @return {@code true} if this provider provides generating color code * feature, otherwise {@code false} */ public boolean canGenerateColorCode(); /** * Get items for color code generator. * * @since 0.12.1 * @param mimeType the mime type * @return ColorCodeGenaratorItems */ public List<ColorCodeGeneratorItem> getColorCodeGeneratorItems(String mimeType); }
UTF-8
Java
3,391
java
ColorCodesProvider.java
Java
[ { "context": "/*\n * Copyright 2019 junichi11.\n *\n * Licensed under the Apache License, Version", "end": 30, "score": 0.9996845126152039, "start": 21, "tag": "USERNAME", "value": "junichi11" }, { "context": "// implementations...\n * }\n * </pre>\n *\n * @author junichi11, arsi\n * @since 0.10.0\n */\npublic interface Color", "end": 1137, "score": 0.9996052980422974, "start": 1128, "tag": "USERNAME", "value": "junichi11" }, { "context": "tations...\n * }\n * </pre>\n *\n * @author junichi11, arsi\n * @since 0.10.0\n */\npublic interface ColorCodesP", "end": 1143, "score": 0.987038254737854, "start": 1139, "tag": "USERNAME", "value": "arsi" } ]
null
[]
/* * Copyright 2019 junichi11. * * 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.junichi11.netbeans.modules.color.codes.preview.spi; import java.util.List; import java.util.Map; import javax.swing.text.Document; /** * This provides support for showing the colors for the specific color code in * the editor side bar. You can add your provider via a ServiceProvider * annotation. e.g. * <pre> * &#64;ServiceProvider(service = ColorCodesProvider.class, position = 1000) * public class MyColorCodesProvider implements ColorCodesProvider { * // implementations... * } * </pre> * * @author junichi11, arsi * @since 0.10.0 */ public interface ColorCodesProvider { /** * Get the id for the specific provider. * * @return the id for the specific provider */ public String getId(); /** * Get the display name. * * @return the display name */ public String getDisplayName(); /** * Get the description. * * @return the description */ public String getDescription(); /** * Is this provider enabled. * * @since 0.10.0 * @param document the document * @return {@code true} if enabled, otherwise {@code false} */ public boolean isProviderEnabled(Document document); /** * Parse the line then return color values. * * @since 0.10.0 * @param document the document * @param line the string to parse * @param lineNumber line number to store to ColorValue * @param variableColorValues save colors of variables to this map * @return color values */ public List<ColorValue> getColorValues(Document document, String line, int lineNumber, Map<String, List<ColorValue>> variableColorValues); /** * Get the start position for parsing lines. * * @since 0.10.0 * @param document the document * @param currentIndex the line number * @return the line number to start parsing */ public int getStartIndex(Document document, int currentIndex); /** * Get the panel for Options. * * @since 0.11.1 * @return the panel for Options */ public ColorCodesPreviewOptionsPanel getOptionsPanel(); /** * Check whether this provider provides generating color code feature. If it * is provided, please return ColorCodeGeneratorItems in * getColorCodeGeneratorItems(). * * @since 0.12.1 * @return {@code true} if this provider provides generating color code * feature, otherwise {@code false} */ public boolean canGenerateColorCode(); /** * Get items for color code generator. * * @since 0.12.1 * @param mimeType the mime type * @return ColorCodeGenaratorItems */ public List<ColorCodeGeneratorItem> getColorCodeGeneratorItems(String mimeType); }
3,391
0.666765
0.65261
118
27.737288
26.466618
142
false
false
0
0
0
0
0
0
0.245763
false
false
14
aea86348cfbaef1f5c83741046176363744bccda
33,217,277,131,280
cf1ad7421ab331ed37a15b107891cb16942a7b9b
/src/main/java/com/jeeplus/modules/questions/dao/questions_as/YsQuestionsDao.java
1f20fed0d07b98915547a04187bdc96fc0bc7875
[]
no_license
shuba159/RawWater
https://github.com/shuba159/RawWater
b4b6a95ca2666ac46418ab5e3a2078646214fef8
c1a76844f05aa14d797b1779d9242bbeac854ed1
refs/heads/master
2020-03-19T17:40:25.831000
2018-06-10T05:21:25
2018-06-10T05:21:25
136,771,757
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.questions.dao.questions_as; import org.apache.ibatis.annotations.Param; import com.jeeplus.common.persistence.CrudDao; import com.jeeplus.common.persistence.annotation.MyBatisDao; import com.jeeplus.modules.entity.YsQuestions; /** * 题库管理DAO接口 * @author hjm * @version 2018-05-22 */ @MyBatisDao public interface YsQuestionsDao extends CrudDao<YsQuestions> { public String majorTypeSelectQues(@Param("aa")Integer a,@Param("bb")Integer b); public int findTotalNum(); }
UTF-8
Java
622
java
YsQuestionsDao.java
Java
[ { "context": "s.entity.YsQuestions;\n\n/**\n * 题库管理DAO接口\n * @author hjm\n * @version 2018-05-22\n */\n@MyBatisDao\npublic int", "end": 394, "score": 0.9996788501739502, "start": 391, "tag": "USERNAME", "value": "hjm" } ]
null
[]
/** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.questions.dao.questions_as; import org.apache.ibatis.annotations.Param; import com.jeeplus.common.persistence.CrudDao; import com.jeeplus.common.persistence.annotation.MyBatisDao; import com.jeeplus.modules.entity.YsQuestions; /** * 题库管理DAO接口 * @author hjm * @version 2018-05-22 */ @MyBatisDao public interface YsQuestionsDao extends CrudDao<YsQuestions> { public String majorTypeSelectQues(@Param("aa")Integer a,@Param("bb")Integer b); public int findTotalNum(); }
622
0.760656
0.734426
23
25.565218
28.624748
96
false
false
0
0
0
0
0
0
0.521739
false
false
14
12fa9afb8259ef08b12bf8385238a71b3b028f01
4,733,053,979,461
1df4aba8deb4ba0dccc587a2ac61017b3980f0b1
/test/com/iflytek/fin/dao/TestFinanceDao.java
1d1d4e8f7cac20ce907d3eafa8aa528b8a666857
[]
no_license
yhywangzx/PersonalFinance
https://github.com/yhywangzx/PersonalFinance
8a26490c8ca5a3e3c9fb2250ae3ac9c1614028e8
a95146394798553e7406ef4191b0a5b6bc49829c
refs/heads/master
2021-01-21T11:56:55.181000
2017-05-19T05:14:35
2017-05-19T05:14:35
91,768,034
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.iflytek.fin.dao; import static org.junit.Assert.*; import java.util.Date; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.BeforeClass; import org.junit.Test; import com.iflytek.fin.po.Finance; public class TestFinanceDao { private static SqlSession session; @BeforeClass public static void setUpBeforeClass() throws Exception { SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml")); session = sessionFactory.openSession(); } @Test public void testAdd() { FinanceDao dao = session.getMapper(FinanceDao.class); Finance fin = new Finance(); fin.setDetail("买了一辆保时捷"); fin.setMoney("10000000"); fin.setTime(new Date()); fin.setCategoryId(5); fin.setUserId(1); dao.add(fin); session.commit(); } @Test public void testDelete() { FinanceDao dao = session.getMapper(FinanceDao.class); dao.delete(15); session.commit(); } }
UTF-8
Java
1,147
java
TestFinanceDao.java
Java
[]
null
[]
package com.iflytek.fin.dao; import static org.junit.Assert.*; import java.util.Date; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.BeforeClass; import org.junit.Test; import com.iflytek.fin.po.Finance; public class TestFinanceDao { private static SqlSession session; @BeforeClass public static void setUpBeforeClass() throws Exception { SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml")); session = sessionFactory.openSession(); } @Test public void testAdd() { FinanceDao dao = session.getMapper(FinanceDao.class); Finance fin = new Finance(); fin.setDetail("买了一辆保时捷"); fin.setMoney("10000000"); fin.setTime(new Date()); fin.setCategoryId(5); fin.setUserId(1); dao.add(fin); session.commit(); } @Test public void testDelete() { FinanceDao dao = session.getMapper(FinanceDao.class); dao.delete(15); session.commit(); } }
1,147
0.742277
0.731686
47
23.106382
23.414156
127
false
false
0
0
0
0
0
0
1.510638
false
false
14
98a0283f6d4972bb2d8a1ba4c14e707086f0c3c9
21,371,757,286,576
1bc6ea9ff2d428094447f5730d693b821268786a
/com/ibm/rchland/mfgapps/client/utils/IGSCalendar.java
58da0fdc9d03b97d242d77ea242e514fc03028dd
[]
no_license
lmrodrig/client_utils
https://github.com/lmrodrig/client_utils
7d5020bc04fef18199a47556f62945615c7268dd
b17dc604a187ffd54cfdc42bb5af0d80e693b687
refs/heads/master
2020-04-18T00:50:39.569000
2016-09-08T21:01:37
2016-09-08T21:01:37
67,716,614
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Dates should follow the ISO 8601 standard YYYY-MM-DD * The @ symbol has a predefined meaning in Java. * Thus, Flags should not start with the @ symbol. Please use ~ instead. * * Date Flag IPSR/PTR Name Details * ---------- ---- -------- ---------------- ---------------------------------- * 2006-04-20 31214TB R Prechel -Initial version * 2006-08-31 35394PL R Prechel -Move to client utils project * -Fixed compile warnings * 2006-09-22 35394PL R Prechel -Rewrite to make IGSCalendar a model only * -Created IGSCalendarPanel and moved * all view code to IGSCalendarPanel * 2006-09-28 ~1 35394PL R Prechel -Add comments ******************************************************************************/ package com.ibm.rchland.mfgapps.client.utils; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Calendar; import java.util.Date; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.EventListenerList; import com.ibm.rchland.mfgapps.client.utils.event.IGSDateSelectedEvent; import com.ibm.rchland.mfgapps.client.utils.event.IGSDateSelectedListener; /** * <code>IGSCalendar</code> is a calendar model designed for views that * display a month at a time. The model remembers the last selected date. * @author The External Fulfillment Client Development Team */ public class IGSCalendar implements ActionListener { /** The action command for changing the selected date. */ public static final String CHANGE_SELECTED_DATE = "changeSelectedDate"; //$NON-NLS-1$ /** The action command for incrementing the displayed month. */ public static final String INCREMENT_DISPLAYED_MONTH = "incrementDisplayedMonth"; //$NON-NLS-1$ /** The <code>Calendar</code> representing the selected date. */ private Calendar selectedCalendar; /** The <code>Calendar</code> representing the month that is displayed. */ private Calendar displayedCalendar; /** The column the first day of the month occupies in the calendar. */ private int firstDayColumn; /** The number of days in the displayed month. */ private int numberOfDaysInMonth; /** Stores the listeners observing this <code>IGSCalendar</code>. */ private EventListenerList listenerList = new EventListenerList(); /** Constructs a new <code>IGSCalendar</code>. */ public IGSCalendar() { this.selectedCalendar = Calendar.getInstance(); this.displayedCalendar = Calendar.getInstance(); updateDisplayedMonth(); //sets firstDayColumn and numberOfDaysInMonth } /** * Sets the date of the <code>displayedCalendar</code> to the first of the * month and then calculates and sets both <code>firstDayColumn</code> and * <code>numberOfDaysInMonth</code>. */ protected final void updateDisplayedMonth() { this.displayedCalendar.set(Calendar.DATE, 1); switch (this.displayedCalendar.get(Calendar.DAY_OF_WEEK)) { case Calendar.SUNDAY: this.firstDayColumn = 0; break; case Calendar.MONDAY: this.firstDayColumn = 1; break; case Calendar.TUESDAY: this.firstDayColumn = 2; break; case Calendar.WEDNESDAY: this.firstDayColumn = 3; break; case Calendar.THURSDAY: this.firstDayColumn = 4; break; case Calendar.FRIDAY: this.firstDayColumn = 5; break; case Calendar.SATURDAY: this.firstDayColumn = 6; break; default: this.firstDayColumn = 0; break; } this.numberOfDaysInMonth = this.displayedCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); ChangeEvent changeEvent = new ChangeEvent(this); //~1 getListenerList returns a non-null array of // listenerType, listener, listenerType, listener, etc. Object[] listeners = this.listenerList.getListenerList(); //~1 Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { ((ChangeListener) listeners[i + 1]).stateChanged(changeEvent); } } } /** * Adds a <code>ChangeListener</code> to this <code>IGSCalendar</code>. * @param listener the <code>ChangeListener</code> to add */ public void addChangeListener(ChangeListener listener) { this.listenerList.add(ChangeListener.class, listener); } /** * Removes a <code>ChangeListener</code> from this <code>IGSCalendar</code>. * @param listener the <code>ChangeListener</code> to remove */ public void removeChangeListener(ChangeListener listener) { this.listenerList.remove(ChangeListener.class, listener); } /** * Adds an <code>IGSDateSelectedListener</code> to this <code>IGSCalendar</code>. * @param listener the <code>IGSDateSelectedListener</code> to add */ public void addDateSelectedListener(IGSDateSelectedListener listener) { this.listenerList.add(IGSDateSelectedListener.class, listener); } /** * Removes an <code>IGSDateSelectedListener</code> from this <code>IGSCalendar</code>. * @param listener the <code>IGSDateSelectedListener</code> to remove */ public void removeDateSelectedListener(IGSDateSelectedListener listener) { this.listenerList.remove(IGSDateSelectedListener.class, listener); } /** * Returns the displayed <code>Date</code>. * @return the displayed <code>Date</code> */ public Date getDisplayedDate() { return this.displayedCalendar.getTime(); } /** * Returns the selected <code>Date</code>. * @return the selected <code>Date</code> */ public Date getSelectedDate() { return this.selectedCalendar.getTime(); } /** * Sets the value of the selected <code>Date</code> and notifies all * registered <code>IGSDateSelectedListener</code>s of the new value of * the selected <code>Date</code>. * @param date the new selected <code>Date</code> */ public void setSelectedDate(Date date) { this.selectedCalendar.setTime(date); IGSDateSelectedEvent dateEvent = new IGSDateSelectedEvent(this, date); //~1 getListenerList returns a non-null array of // listenerType, listener, listenerType, listener, etc. Object[] listeners = this.listenerList.getListenerList(); //~1 Process the listeners last to first, notifying // those that are interested in this event ChangeEvent changeEvent = new ChangeEvent(this); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == IGSDateSelectedListener.class) { ((IGSDateSelectedListener) listeners[i + 1]).dateSelected(dateEvent); } else if (listeners[i] == ChangeListener.class) { ((ChangeListener) listeners[i + 1]).stateChanged(changeEvent); } } this.displayedCalendar.setTime(this.selectedCalendar.getTime()); updateDisplayedMonth(); } /** * Returns <code>true</code> iff the selected month is the displayed month. * @return <code>true</code> iff the selected month is the displayed month */ public boolean isSelectedMonthDisplayed() { return this.displayedCalendar.get(Calendar.MONTH) == this.selectedCalendar.get(Calendar.MONTH) && this.displayedCalendar.get(Calendar.YEAR) == this.selectedCalendar.get(Calendar.YEAR); } /** * Returns the calendar model index of the selected day of the month. * @return the calendar model index of the selected day of the month */ public int getSelectedDayIndex() { return this.selectedCalendar.get(Calendar.DATE) + this.firstDayColumn - 1; } /** * Returns the day of the month at the specified calendar model <code>index</code>. * @param index the calendar model index * @return the day of the month at the specified calendar model * <code>index</code>. A negative value is returned if the index * does not correspond to a day. */ public int getDayOfMonth(int index) { int day = index - this.firstDayColumn; if (day >= 0 && day < this.numberOfDaysInMonth) { return ++day; //convert from 0 based to 1 based } return -1; } /** * Invoked when an action occurs. * @param ae the <code>ActionEvent</code> */ public void actionPerformed(ActionEvent ae) { String command = ae.getActionCommand(); if (command == null) { return; } if (command.startsWith(CHANGE_SELECTED_DATE)) { try { int dayOfMonth = Integer.parseInt(command.substring(CHANGE_SELECTED_DATE.length())); this.displayedCalendar.set(Calendar.DATE, dayOfMonth); this.setSelectedDate(this.displayedCalendar.getTime()); } catch (NumberFormatException nfe) { //Nothing to do } } else if (command.startsWith(INCREMENT_DISPLAYED_MONTH)) { try { int value = Integer.parseInt(command.substring(INCREMENT_DISPLAYED_MONTH.length())); this.displayedCalendar.add(Calendar.MONTH, value); updateDisplayedMonth(); } catch (NumberFormatException nfe) { //Nothing to do } } } }
UTF-8
Java
8,969
java
IGSCalendar.java
Java
[ { "context": "----------------------\n * 2006-04-20 31214TB R Prechel -Initial version\n * 2006-08-31 35394P", "end": 353, "score": 0.9961751699447632, "start": 344, "tag": "NAME", "value": "R Prechel" }, { "context": " -Initial version\n * 2006-08-31 35394PL R Prechel -Move to client utils project\n * ", "end": 415, "score": 0.995215654373169, "start": 406, "tag": "NAME", "value": "R Prechel" }, { "context": "Fixed compile warnings\n * 2006-09-22 35394PL R Prechel -Rewrite to make IGSCalendar a model only\n", "end": 559, "score": 0.9958082437515259, "start": 550, "tag": "NAME", "value": "R Prechel" }, { "context": "de to IGSCalendarPanel\n * 2006-09-28 ~1 35394PL R Prechel -Add comments\n ***************************", "end": 807, "score": 0.9970741868019104, "start": 798, "tag": "NAME", "value": "R Prechel" } ]
null
[]
/* Dates should follow the ISO 8601 standard YYYY-MM-DD * The @ symbol has a predefined meaning in Java. * Thus, Flags should not start with the @ symbol. Please use ~ instead. * * Date Flag IPSR/PTR Name Details * ---------- ---- -------- ---------------- ---------------------------------- * 2006-04-20 31214TB <NAME> -Initial version * 2006-08-31 35394PL <NAME> -Move to client utils project * -Fixed compile warnings * 2006-09-22 35394PL <NAME> -Rewrite to make IGSCalendar a model only * -Created IGSCalendarPanel and moved * all view code to IGSCalendarPanel * 2006-09-28 ~1 35394PL <NAME> -Add comments ******************************************************************************/ package com.ibm.rchland.mfgapps.client.utils; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Calendar; import java.util.Date; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.EventListenerList; import com.ibm.rchland.mfgapps.client.utils.event.IGSDateSelectedEvent; import com.ibm.rchland.mfgapps.client.utils.event.IGSDateSelectedListener; /** * <code>IGSCalendar</code> is a calendar model designed for views that * display a month at a time. The model remembers the last selected date. * @author The External Fulfillment Client Development Team */ public class IGSCalendar implements ActionListener { /** The action command for changing the selected date. */ public static final String CHANGE_SELECTED_DATE = "changeSelectedDate"; //$NON-NLS-1$ /** The action command for incrementing the displayed month. */ public static final String INCREMENT_DISPLAYED_MONTH = "incrementDisplayedMonth"; //$NON-NLS-1$ /** The <code>Calendar</code> representing the selected date. */ private Calendar selectedCalendar; /** The <code>Calendar</code> representing the month that is displayed. */ private Calendar displayedCalendar; /** The column the first day of the month occupies in the calendar. */ private int firstDayColumn; /** The number of days in the displayed month. */ private int numberOfDaysInMonth; /** Stores the listeners observing this <code>IGSCalendar</code>. */ private EventListenerList listenerList = new EventListenerList(); /** Constructs a new <code>IGSCalendar</code>. */ public IGSCalendar() { this.selectedCalendar = Calendar.getInstance(); this.displayedCalendar = Calendar.getInstance(); updateDisplayedMonth(); //sets firstDayColumn and numberOfDaysInMonth } /** * Sets the date of the <code>displayedCalendar</code> to the first of the * month and then calculates and sets both <code>firstDayColumn</code> and * <code>numberOfDaysInMonth</code>. */ protected final void updateDisplayedMonth() { this.displayedCalendar.set(Calendar.DATE, 1); switch (this.displayedCalendar.get(Calendar.DAY_OF_WEEK)) { case Calendar.SUNDAY: this.firstDayColumn = 0; break; case Calendar.MONDAY: this.firstDayColumn = 1; break; case Calendar.TUESDAY: this.firstDayColumn = 2; break; case Calendar.WEDNESDAY: this.firstDayColumn = 3; break; case Calendar.THURSDAY: this.firstDayColumn = 4; break; case Calendar.FRIDAY: this.firstDayColumn = 5; break; case Calendar.SATURDAY: this.firstDayColumn = 6; break; default: this.firstDayColumn = 0; break; } this.numberOfDaysInMonth = this.displayedCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); ChangeEvent changeEvent = new ChangeEvent(this); //~1 getListenerList returns a non-null array of // listenerType, listener, listenerType, listener, etc. Object[] listeners = this.listenerList.getListenerList(); //~1 Process the listeners last to first, notifying // those that are interested in this event for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { ((ChangeListener) listeners[i + 1]).stateChanged(changeEvent); } } } /** * Adds a <code>ChangeListener</code> to this <code>IGSCalendar</code>. * @param listener the <code>ChangeListener</code> to add */ public void addChangeListener(ChangeListener listener) { this.listenerList.add(ChangeListener.class, listener); } /** * Removes a <code>ChangeListener</code> from this <code>IGSCalendar</code>. * @param listener the <code>ChangeListener</code> to remove */ public void removeChangeListener(ChangeListener listener) { this.listenerList.remove(ChangeListener.class, listener); } /** * Adds an <code>IGSDateSelectedListener</code> to this <code>IGSCalendar</code>. * @param listener the <code>IGSDateSelectedListener</code> to add */ public void addDateSelectedListener(IGSDateSelectedListener listener) { this.listenerList.add(IGSDateSelectedListener.class, listener); } /** * Removes an <code>IGSDateSelectedListener</code> from this <code>IGSCalendar</code>. * @param listener the <code>IGSDateSelectedListener</code> to remove */ public void removeDateSelectedListener(IGSDateSelectedListener listener) { this.listenerList.remove(IGSDateSelectedListener.class, listener); } /** * Returns the displayed <code>Date</code>. * @return the displayed <code>Date</code> */ public Date getDisplayedDate() { return this.displayedCalendar.getTime(); } /** * Returns the selected <code>Date</code>. * @return the selected <code>Date</code> */ public Date getSelectedDate() { return this.selectedCalendar.getTime(); } /** * Sets the value of the selected <code>Date</code> and notifies all * registered <code>IGSDateSelectedListener</code>s of the new value of * the selected <code>Date</code>. * @param date the new selected <code>Date</code> */ public void setSelectedDate(Date date) { this.selectedCalendar.setTime(date); IGSDateSelectedEvent dateEvent = new IGSDateSelectedEvent(this, date); //~1 getListenerList returns a non-null array of // listenerType, listener, listenerType, listener, etc. Object[] listeners = this.listenerList.getListenerList(); //~1 Process the listeners last to first, notifying // those that are interested in this event ChangeEvent changeEvent = new ChangeEvent(this); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == IGSDateSelectedListener.class) { ((IGSDateSelectedListener) listeners[i + 1]).dateSelected(dateEvent); } else if (listeners[i] == ChangeListener.class) { ((ChangeListener) listeners[i + 1]).stateChanged(changeEvent); } } this.displayedCalendar.setTime(this.selectedCalendar.getTime()); updateDisplayedMonth(); } /** * Returns <code>true</code> iff the selected month is the displayed month. * @return <code>true</code> iff the selected month is the displayed month */ public boolean isSelectedMonthDisplayed() { return this.displayedCalendar.get(Calendar.MONTH) == this.selectedCalendar.get(Calendar.MONTH) && this.displayedCalendar.get(Calendar.YEAR) == this.selectedCalendar.get(Calendar.YEAR); } /** * Returns the calendar model index of the selected day of the month. * @return the calendar model index of the selected day of the month */ public int getSelectedDayIndex() { return this.selectedCalendar.get(Calendar.DATE) + this.firstDayColumn - 1; } /** * Returns the day of the month at the specified calendar model <code>index</code>. * @param index the calendar model index * @return the day of the month at the specified calendar model * <code>index</code>. A negative value is returned if the index * does not correspond to a day. */ public int getDayOfMonth(int index) { int day = index - this.firstDayColumn; if (day >= 0 && day < this.numberOfDaysInMonth) { return ++day; //convert from 0 based to 1 based } return -1; } /** * Invoked when an action occurs. * @param ae the <code>ActionEvent</code> */ public void actionPerformed(ActionEvent ae) { String command = ae.getActionCommand(); if (command == null) { return; } if (command.startsWith(CHANGE_SELECTED_DATE)) { try { int dayOfMonth = Integer.parseInt(command.substring(CHANGE_SELECTED_DATE.length())); this.displayedCalendar.set(Calendar.DATE, dayOfMonth); this.setSelectedDate(this.displayedCalendar.getTime()); } catch (NumberFormatException nfe) { //Nothing to do } } else if (command.startsWith(INCREMENT_DISPLAYED_MONTH)) { try { int value = Integer.parseInt(command.substring(INCREMENT_DISPLAYED_MONTH.length())); this.displayedCalendar.add(Calendar.MONTH, value); updateDisplayedMonth(); } catch (NumberFormatException nfe) { //Nothing to do } } } }
8,957
0.691493
0.681904
280
31.032143
28.673576
96
false
false
0
0
0
0
0
0
1.825
false
false
14
66218472539adb624092edac268977dbf7bd4076
20,564,303,433,872
f2e46347b398c08f0939a4424d54c2f9411c8474
/src/pages/CatalogPage.java
b80602cb1dcb8e59581761b9ee67991c5914c398
[]
no_license
AKN053/TestAutomation
https://github.com/AKN053/TestAutomation
fac176e638f2b2fb85092c24758d1bd54c661cab
7316a26142bfdb27359779f6ddecff8f8d9a86ae
refs/heads/master
2020-03-26T01:21:20.938000
2018-09-15T08:34:20
2018-09-15T08:34:20
144,363,631
0
2
null
false
2018-09-15T08:34:22
2018-08-11T07:07:24
2018-09-08T12:11:49
2018-09-15T08:34:21
6,210
0
2
0
Java
false
null
package pages; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import pages.BasePage.MDS_Table; import common.Config; import common.Enumerations.ColumnName; import framework.helpers.Elements; public class CatalogPage extends BasePage{ public static class PageElements{ public static final By SEARCH_TEXTBOX = By.cssSelector("input[id='searchItem']"); public static final By TYPEAHEAD_RESULTLIST = By.cssSelector("ul[class*='typeahead'][role='select']"); //download button public static final By DOWNLOAD_SELECTED_BUTTON = By.cssSelector("div[ng-if='showDownload'] > a[ng-show='showDownload && !masterCheck'][id='downloadSheets'])");//("body > div > div:nth-child(2) > div > div > div.panel-body.itnPanelBody > div:nth-child(3) > div > div > div > div:nth-child(3) > div.col.col-sm-8.col-md-9.col-lg-10 > div:nth-child(2) > div.panel-body.itnPanelBody.itnPanelNoBorder.itnPanelSubBodyNoPadding > div:nth-child(3) > div > div:nth-child(2) > div.col-xs-6 > div > a:nth-child(1)"); public static final By DOWNLOAD_ALL_BUTTON = By.cssSelector("div[ng-if='showDownload'] > a[ng-show='showDownload && masterCheck'][id='downloadSheets']"); public static final By DOWNLOAD_DROPDOWN_BUTTON = By.cssSelector("button[type='button'][data-toggle='dropdown'][aria-expanded='false']"); public static final By DOWNLOAD_ALL_LINK = By.cssSelector("ul[class='dropdown-menu'][role='menu'] > li > a[id='downloadSheetsAll']"); public static final By TABLE_BODY_GRID = By.cssSelector("table[id='itnCatalogTable'] > tbody:nth-child(3)"); //checkboxes public static final By SELECT_CHECKBOXES = By.cssSelector("td > input[type='checkbox'][id*='gtinChk']"); } public static void performSearch(String searchText){ Elements.isEnabled(PageElements.SEARCH_TEXTBOX); Elements.clearAndType(PageElements.SEARCH_TEXTBOX, searchText.substring(0, searchText.length()-1)); Elements.typeIn(PageElements.SEARCH_TEXTBOX, Keys.BACK_SPACE); WebElement typeAheadResultList = Elements.find(PageElements.TYPEAHEAD_RESULTLIST); Elements.selectFromTypeAheadDropdownStart(typeAheadResultList,searchText); } public static void performProductCodeSearch(String searchText){ Elements.isEnabled(PageElements.SEARCH_TEXTBOX); Elements.clearAndType(PageElements.SEARCH_TEXTBOX, searchText.substring(0, 4)); Elements.typeIn(PageElements.SEARCH_TEXTBOX, Keys.BACK_SPACE); WebElement typeAheadResultList = Elements.find(PageElements.TYPEAHEAD_RESULTLIST); Elements.selectFromTypeAheadDropdownMid(typeAheadResultList,searchText); while(IsLoading.isLoading()) Elements.pauseExecution(1500); } public static void performProductDescriptionSearch(String searchText){ Elements.isEnabled(PageElements.SEARCH_TEXTBOX); Elements.clearAndType(PageElements.SEARCH_TEXTBOX, searchText.substring(0, 4)); Elements.typeIn(PageElements.SEARCH_TEXTBOX, Keys.BACK_SPACE); WebElement typeAheadResultList = Elements.find(PageElements.TYPEAHEAD_RESULTLIST); Elements.selectFromTypeAheadDropdownLast(typeAheadResultList,searchText); while(IsLoading.isLoading()) Elements.pauseExecution(1500); } public static void searchFirstGTIN(){ performSearch(getFirstGTIN()); } public static String getFirstGTIN(){ List<String> gtin = MDS_Table.getColumnData(ColumnName.GTIN); if(gtin.get(0).equalsIgnoreCase("--")) return gtin.get(1); return gtin.get(0); } public static String getFirstProductCode(){ List<String> gtin = MDS_Table.getColumnData(ColumnName.PRODUCT_CODE); return gtin.get(0); } public static void searchFirstProductCode(){ performProductCodeSearch(getFirstProductCode()); } public static String getFirstProductDescription(){ List<String> gtin = MDS_Table.getColumnData(ColumnName.ITEM_DESCRIPTION); return gtin.get(0); } public static void searchFirstProductDescription(){ performProductDescriptionSearch(getFirstProductDescription()); } public static void waitForDataLoad(){ /*if(Elements.isVisible(PageElements.TABLE_BODY_GRID)) return true; else return false;*/ while(MDS_Table.getTotalNumberOfRowsFromMDSTable(ColumnName.GTIN)<1){ //System.out.println("waiting for data load"); Elements.pauseExecution(2000); break; } //System.out.println("data loaded"); } public static void clickDownloadButton(){ Elements.isEnabled(PageElements.DOWNLOAD_DROPDOWN_BUTTON); Elements.clickElement(PageElements.DOWNLOAD_DROPDOWN_BUTTON); } public static boolean isDownloadAllClickable(){ if(Elements.isClickable(PageElements.DOWNLOAD_ALL_LINK, Config.wait)) return true; else return false; } public static boolean isDownloadSelectedButtonClickable(){ if(Elements.isClickable(PageElements.DOWNLOAD_SELECTED_BUTTON, Config.wait)) return true; else return false; } public static void clickDownloadSelectedButton(){ Elements.isEnabled(PageElements.DOWNLOAD_SELECTED_BUTTON); Elements.clickElement(PageElements.DOWNLOAD_SELECTED_BUTTON); } public static void clickDownloadAllButton(){ Elements.isEnabled(PageElements.DOWNLOAD_ALL_BUTTON); Elements.clickElement(PageElements.DOWNLOAD_ALL_BUTTON); } public static boolean isDownloadAllButtonClickable(){ if(Elements.isClickable(PageElements.DOWNLOAD_ALL_BUTTON, Config.wait)) return true; else return false; } public static void selectFirstNGTINs(int n){ List<WebElement> data = Elements.findAll(PageElements.SELECT_CHECKBOXES); for(int i=0; i<n; i++){ Elements.clickElement(data.get(i), Config.sleep); if(i>=data.size()) break; } } public static class Filters{ public static class RegistrationStatus{ public static class PageElements{ //public static final By INCOMPLETE_CHECKBOX = By.cssSelector("input[type='checkbox'][id='registrationStatus_Incomplete']"); public static final By NOT_READY_CHECKBOX = By.cssSelector("div[header='Registration Status'] > div[ng-show='showITNPanelContent'] > div:nth-child(3) > div > div > div:nth-child(1) > div[ng-click='addRegistrationStatus(status)'] > div > input[type='checkbox'][id='registrationStatus_Not Ready']"); public static final By IN_PROCESS_CHECKBOX = By.cssSelector("div[header='Registration Status'] > div[ng-show='showITNPanelContent'] > div:nth-child(3) > div > div > div:nth-child(2) > div[ng-click='addRegistrationStatus(status)'] > div > input[type='checkbox'][id='registrationStatus_In Process']"); //public static final By REGISTERED_CHECKBOX = By.cssSelector("input[type='checkbox'][id='registrationStatus_Registered']"); public static final By VALIDATED_CHECKBOX = By.cssSelector("div[header='Registration Status'] > div[ng-show='showITNPanelContent'] > div:nth-child(3) > div > div > div:nth-child(3) >div[ng-click='addRegistrationStatus(status)'] > div > input[type='checkbox'][id='registrationStatus_Validated']"); public static final By FAILED_CHECKBOX = By.cssSelector("div[ng-show*='isNonGdsnOmsUser()'] > div > div:nth-child(2) > div:nth-child(3) > div > div > div:nth-child(4) > div > div > input"); } /*public static void checkIncompleteCheckbox(){ Elements.isEnabled(PageElements.INCOMPLETE_CHECKBOX); Elements.clickElement(PageElements.INCOMPLETE_CHECKBOX); IsLoadin.isLoading(); }*/ public static void checkNotReadyCheckbox(){ List<WebElement> all = Elements.findAll(By.cssSelector("div[ng-click='addRegistrationStatus(status)']")); /*Elements.isEnabled(PageElements.NOT_READY_CHECKBOX); Elements.clickElement(PageElements.NOT_READY_CHECKBOX);*/ WebElement data = Elements.find(all.get(0), By.tagName("input")); data.click(); IsLoading.isLoading(); } public static void checkProcessingCheckbox(){ List<WebElement> all = Elements.findAll(By.cssSelector("div[ng-click='addRegistrationStatus(status)']")); WebElement data = Elements.find(all.get(1), By.tagName("input")); data.click(); /*Elements.isEnabled(PageElements.IN_PROCESS_CHECKBOX); Elements.clickElement(PageElements.IN_PROCESS_CHECKBOX);*/ IsLoading.isLoading(); } /*public static void checkRegisteredCheckbox(){ Elements.isEnabled(PageElements.REGISTERED_CHECKBOX); Elements.clickElement(PageElements.REGISTERED_CHECKBOX); IsLoadin.isLoading(); }*/ public static void checkValidatedCheckbox(){ List<WebElement> all = Elements.findAll(By.cssSelector("div[ng-click='addRegistrationStatus(status)']")); WebElement data = Elements.find(all.get(2), By.tagName("input")); data.click(); /* Elements.isEnabled(PageElements.VALIDATED_CHECKBOX); Elements.clickElement(PageElements.VALIDATED_CHECKBOX);*/ IsLoading.isLoading(); } public static void checkFailedCheckbox(){ List<WebElement> all = Elements.findAll(By.cssSelector("div[ng-click='addRegistrationStatus(status)']")); WebElement data = Elements.find(all.get(3), By.tagName("input")); data.click(); /*Elements.isEnabled(PageElements.FAILED_CHECKBOX); Elements.clickElement(PageElements.FAILED_CHECKBOX);*/ IsLoading.isLoading(); } } } public static class SplitScreen{ public static class PageElements{ public static final By HEADER_STATIC = By.cssSelector("div[ng-show='splitScreen'] > div > div[ng-show='header'] > div > div > h3 > a"); public static final By CLOSE_BUTTON = By.cssSelector("div[ng-show='splitScreen'] > div > div[ng-show='header'] > div > div > h3 > span > span[ng-show='showcloseinheader'] > button"); public static final By GET_PRODUCT_SHEET_BUTTON = By.cssSelector("div[id='itn_Review_Details'] > div > a[id='gtinProductSellSheet']"); } public static String getHeader(){ return Elements.getText(PageElements.HEADER_STATIC); } public static void clickCloseSplitScreen(){ Elements.isEnabled(PageElements.CLOSE_BUTTON); Elements.clickElement(PageElements.CLOSE_BUTTON); } public static boolean verifySplitScreenVisible(){ if(Elements.isVisible(PageElements.HEADER_STATIC)) return true; else return false; } public static boolean verifyGetProductSheetButtonClickable(){ if(Elements.isClickable(PageElements.GET_PRODUCT_SHEET_BUTTON, Config.wait)) return true; else return false; } } }
UTF-8
Java
10,327
java
CatalogPage.java
Java
[]
null
[]
package pages; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebElement; import pages.BasePage.MDS_Table; import common.Config; import common.Enumerations.ColumnName; import framework.helpers.Elements; public class CatalogPage extends BasePage{ public static class PageElements{ public static final By SEARCH_TEXTBOX = By.cssSelector("input[id='searchItem']"); public static final By TYPEAHEAD_RESULTLIST = By.cssSelector("ul[class*='typeahead'][role='select']"); //download button public static final By DOWNLOAD_SELECTED_BUTTON = By.cssSelector("div[ng-if='showDownload'] > a[ng-show='showDownload && !masterCheck'][id='downloadSheets'])");//("body > div > div:nth-child(2) > div > div > div.panel-body.itnPanelBody > div:nth-child(3) > div > div > div > div:nth-child(3) > div.col.col-sm-8.col-md-9.col-lg-10 > div:nth-child(2) > div.panel-body.itnPanelBody.itnPanelNoBorder.itnPanelSubBodyNoPadding > div:nth-child(3) > div > div:nth-child(2) > div.col-xs-6 > div > a:nth-child(1)"); public static final By DOWNLOAD_ALL_BUTTON = By.cssSelector("div[ng-if='showDownload'] > a[ng-show='showDownload && masterCheck'][id='downloadSheets']"); public static final By DOWNLOAD_DROPDOWN_BUTTON = By.cssSelector("button[type='button'][data-toggle='dropdown'][aria-expanded='false']"); public static final By DOWNLOAD_ALL_LINK = By.cssSelector("ul[class='dropdown-menu'][role='menu'] > li > a[id='downloadSheetsAll']"); public static final By TABLE_BODY_GRID = By.cssSelector("table[id='itnCatalogTable'] > tbody:nth-child(3)"); //checkboxes public static final By SELECT_CHECKBOXES = By.cssSelector("td > input[type='checkbox'][id*='gtinChk']"); } public static void performSearch(String searchText){ Elements.isEnabled(PageElements.SEARCH_TEXTBOX); Elements.clearAndType(PageElements.SEARCH_TEXTBOX, searchText.substring(0, searchText.length()-1)); Elements.typeIn(PageElements.SEARCH_TEXTBOX, Keys.BACK_SPACE); WebElement typeAheadResultList = Elements.find(PageElements.TYPEAHEAD_RESULTLIST); Elements.selectFromTypeAheadDropdownStart(typeAheadResultList,searchText); } public static void performProductCodeSearch(String searchText){ Elements.isEnabled(PageElements.SEARCH_TEXTBOX); Elements.clearAndType(PageElements.SEARCH_TEXTBOX, searchText.substring(0, 4)); Elements.typeIn(PageElements.SEARCH_TEXTBOX, Keys.BACK_SPACE); WebElement typeAheadResultList = Elements.find(PageElements.TYPEAHEAD_RESULTLIST); Elements.selectFromTypeAheadDropdownMid(typeAheadResultList,searchText); while(IsLoading.isLoading()) Elements.pauseExecution(1500); } public static void performProductDescriptionSearch(String searchText){ Elements.isEnabled(PageElements.SEARCH_TEXTBOX); Elements.clearAndType(PageElements.SEARCH_TEXTBOX, searchText.substring(0, 4)); Elements.typeIn(PageElements.SEARCH_TEXTBOX, Keys.BACK_SPACE); WebElement typeAheadResultList = Elements.find(PageElements.TYPEAHEAD_RESULTLIST); Elements.selectFromTypeAheadDropdownLast(typeAheadResultList,searchText); while(IsLoading.isLoading()) Elements.pauseExecution(1500); } public static void searchFirstGTIN(){ performSearch(getFirstGTIN()); } public static String getFirstGTIN(){ List<String> gtin = MDS_Table.getColumnData(ColumnName.GTIN); if(gtin.get(0).equalsIgnoreCase("--")) return gtin.get(1); return gtin.get(0); } public static String getFirstProductCode(){ List<String> gtin = MDS_Table.getColumnData(ColumnName.PRODUCT_CODE); return gtin.get(0); } public static void searchFirstProductCode(){ performProductCodeSearch(getFirstProductCode()); } public static String getFirstProductDescription(){ List<String> gtin = MDS_Table.getColumnData(ColumnName.ITEM_DESCRIPTION); return gtin.get(0); } public static void searchFirstProductDescription(){ performProductDescriptionSearch(getFirstProductDescription()); } public static void waitForDataLoad(){ /*if(Elements.isVisible(PageElements.TABLE_BODY_GRID)) return true; else return false;*/ while(MDS_Table.getTotalNumberOfRowsFromMDSTable(ColumnName.GTIN)<1){ //System.out.println("waiting for data load"); Elements.pauseExecution(2000); break; } //System.out.println("data loaded"); } public static void clickDownloadButton(){ Elements.isEnabled(PageElements.DOWNLOAD_DROPDOWN_BUTTON); Elements.clickElement(PageElements.DOWNLOAD_DROPDOWN_BUTTON); } public static boolean isDownloadAllClickable(){ if(Elements.isClickable(PageElements.DOWNLOAD_ALL_LINK, Config.wait)) return true; else return false; } public static boolean isDownloadSelectedButtonClickable(){ if(Elements.isClickable(PageElements.DOWNLOAD_SELECTED_BUTTON, Config.wait)) return true; else return false; } public static void clickDownloadSelectedButton(){ Elements.isEnabled(PageElements.DOWNLOAD_SELECTED_BUTTON); Elements.clickElement(PageElements.DOWNLOAD_SELECTED_BUTTON); } public static void clickDownloadAllButton(){ Elements.isEnabled(PageElements.DOWNLOAD_ALL_BUTTON); Elements.clickElement(PageElements.DOWNLOAD_ALL_BUTTON); } public static boolean isDownloadAllButtonClickable(){ if(Elements.isClickable(PageElements.DOWNLOAD_ALL_BUTTON, Config.wait)) return true; else return false; } public static void selectFirstNGTINs(int n){ List<WebElement> data = Elements.findAll(PageElements.SELECT_CHECKBOXES); for(int i=0; i<n; i++){ Elements.clickElement(data.get(i), Config.sleep); if(i>=data.size()) break; } } public static class Filters{ public static class RegistrationStatus{ public static class PageElements{ //public static final By INCOMPLETE_CHECKBOX = By.cssSelector("input[type='checkbox'][id='registrationStatus_Incomplete']"); public static final By NOT_READY_CHECKBOX = By.cssSelector("div[header='Registration Status'] > div[ng-show='showITNPanelContent'] > div:nth-child(3) > div > div > div:nth-child(1) > div[ng-click='addRegistrationStatus(status)'] > div > input[type='checkbox'][id='registrationStatus_Not Ready']"); public static final By IN_PROCESS_CHECKBOX = By.cssSelector("div[header='Registration Status'] > div[ng-show='showITNPanelContent'] > div:nth-child(3) > div > div > div:nth-child(2) > div[ng-click='addRegistrationStatus(status)'] > div > input[type='checkbox'][id='registrationStatus_In Process']"); //public static final By REGISTERED_CHECKBOX = By.cssSelector("input[type='checkbox'][id='registrationStatus_Registered']"); public static final By VALIDATED_CHECKBOX = By.cssSelector("div[header='Registration Status'] > div[ng-show='showITNPanelContent'] > div:nth-child(3) > div > div > div:nth-child(3) >div[ng-click='addRegistrationStatus(status)'] > div > input[type='checkbox'][id='registrationStatus_Validated']"); public static final By FAILED_CHECKBOX = By.cssSelector("div[ng-show*='isNonGdsnOmsUser()'] > div > div:nth-child(2) > div:nth-child(3) > div > div > div:nth-child(4) > div > div > input"); } /*public static void checkIncompleteCheckbox(){ Elements.isEnabled(PageElements.INCOMPLETE_CHECKBOX); Elements.clickElement(PageElements.INCOMPLETE_CHECKBOX); IsLoadin.isLoading(); }*/ public static void checkNotReadyCheckbox(){ List<WebElement> all = Elements.findAll(By.cssSelector("div[ng-click='addRegistrationStatus(status)']")); /*Elements.isEnabled(PageElements.NOT_READY_CHECKBOX); Elements.clickElement(PageElements.NOT_READY_CHECKBOX);*/ WebElement data = Elements.find(all.get(0), By.tagName("input")); data.click(); IsLoading.isLoading(); } public static void checkProcessingCheckbox(){ List<WebElement> all = Elements.findAll(By.cssSelector("div[ng-click='addRegistrationStatus(status)']")); WebElement data = Elements.find(all.get(1), By.tagName("input")); data.click(); /*Elements.isEnabled(PageElements.IN_PROCESS_CHECKBOX); Elements.clickElement(PageElements.IN_PROCESS_CHECKBOX);*/ IsLoading.isLoading(); } /*public static void checkRegisteredCheckbox(){ Elements.isEnabled(PageElements.REGISTERED_CHECKBOX); Elements.clickElement(PageElements.REGISTERED_CHECKBOX); IsLoadin.isLoading(); }*/ public static void checkValidatedCheckbox(){ List<WebElement> all = Elements.findAll(By.cssSelector("div[ng-click='addRegistrationStatus(status)']")); WebElement data = Elements.find(all.get(2), By.tagName("input")); data.click(); /* Elements.isEnabled(PageElements.VALIDATED_CHECKBOX); Elements.clickElement(PageElements.VALIDATED_CHECKBOX);*/ IsLoading.isLoading(); } public static void checkFailedCheckbox(){ List<WebElement> all = Elements.findAll(By.cssSelector("div[ng-click='addRegistrationStatus(status)']")); WebElement data = Elements.find(all.get(3), By.tagName("input")); data.click(); /*Elements.isEnabled(PageElements.FAILED_CHECKBOX); Elements.clickElement(PageElements.FAILED_CHECKBOX);*/ IsLoading.isLoading(); } } } public static class SplitScreen{ public static class PageElements{ public static final By HEADER_STATIC = By.cssSelector("div[ng-show='splitScreen'] > div > div[ng-show='header'] > div > div > h3 > a"); public static final By CLOSE_BUTTON = By.cssSelector("div[ng-show='splitScreen'] > div > div[ng-show='header'] > div > div > h3 > span > span[ng-show='showcloseinheader'] > button"); public static final By GET_PRODUCT_SHEET_BUTTON = By.cssSelector("div[id='itn_Review_Details'] > div > a[id='gtinProductSellSheet']"); } public static String getHeader(){ return Elements.getText(PageElements.HEADER_STATIC); } public static void clickCloseSplitScreen(){ Elements.isEnabled(PageElements.CLOSE_BUTTON); Elements.clickElement(PageElements.CLOSE_BUTTON); } public static boolean verifySplitScreenVisible(){ if(Elements.isVisible(PageElements.HEADER_STATIC)) return true; else return false; } public static boolean verifyGetProductSheetButtonClickable(){ if(Elements.isClickable(PageElements.GET_PRODUCT_SHEET_BUTTON, Config.wait)) return true; else return false; } } }
10,327
0.738259
0.733127
253
39.81818
54.944012
507
false
false
0
0
0
0
0
0
2.754941
false
false
14
c9c0956c00aae5c06b3d88e4b610439cdb7d0362
18,562,848,675,988
e5724329a0bcfe9ed84ecbf3801d399625c12970
/src/oOPSconcept/Child2.java
9c69d42ef8fe916768190305c2dee8280ab10968
[]
no_license
rabin2004/NovemberBatchClassFiles
https://github.com/rabin2004/NovemberBatchClassFiles
24fdd6e313982b2f8622c81877a68e60dbce6855
d827af061e747e2afaa5826694b3721e51e140d1
refs/heads/master
2023-04-25T01:48:03.852000
2021-05-15T14:12:31
2021-05-15T14:12:31
367,648,440
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package oOPSconcept; public class Child2 extends Parent{ public static void main(String[] args) { System.out.println(b); parentMethod2(); Child2 ch2 = new Child2(); System.out.println(ch2.a); ch2.parentMethod1(); System.out.println(boo); grandParent2(); System.out.println(ch2.d); ch2.grandParent1(); } }
UTF-8
Java
363
java
Child2.java
Java
[]
null
[]
package oOPSconcept; public class Child2 extends Parent{ public static void main(String[] args) { System.out.println(b); parentMethod2(); Child2 ch2 = new Child2(); System.out.println(ch2.a); ch2.parentMethod1(); System.out.println(boo); grandParent2(); System.out.println(ch2.d); ch2.grandParent1(); } }
363
0.628099
0.595041
22
14.5
13.217585
41
false
false
0
0
0
0
0
0
1.727273
false
false
14
cadc967c6486eb1f8660299525414671ea2733ca
21,371,757,292,298
bd02936120bcfdd81d0fbbbc752e89bf49b1cf03
/javassist/bytecode/ExceptionTable1.java
d9f0548bd4a2a053babf8133a7a99b1c529f4d6a
[]
no_license
Tuzakci/ICEHack-0.5-Source
https://github.com/Tuzakci/ICEHack-0.5-Source
f336f2b4e8f0b5ea3462f3f37da14fba7c0a554a
fc347479ce8dddb606d14b4c19dac2e7d446ca20
refs/heads/main
2023-01-09T08:33:56.273000
2020-11-13T21:37:18
2020-11-13T21:37:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package javassist.bytecode; class ExceptionTable1 { int startPc; int endPc; int handlerPc; int catchType; ExceptionTable1(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { this.startPc = paramInt1; this.endPc = paramInt2; this.handlerPc = paramInt3; this.catchType = paramInt4; } }
UTF-8
Java
335
java
ExceptionTable1.java
Java
[]
null
[]
package javassist.bytecode; class ExceptionTable1 { int startPc; int endPc; int handlerPc; int catchType; ExceptionTable1(int paramInt1, int paramInt2, int paramInt3, int paramInt4) { this.startPc = paramInt1; this.endPc = paramInt2; this.handlerPc = paramInt3; this.catchType = paramInt4; } }
335
0.689552
0.659701
18
17.611111
18.687901
79
false
false
0
0
0
0
0
0
0.666667
false
false
14
42f59014231350825269d8e499a5f9a31366e733
3,624,952,422,647
0f150156132890f8cf6dbe59b00ec2ef9dd29dab
/PROGRAMMING_BASIC_MULTIMODULE/CarManagmentApp2/serviceCarApp2/src/main/java/CarService.java
c9593e517860a32a1e25fe4e266b566b34f75edc
[]
no_license
marcinLupa/PROGRAMMING-BASIC
https://github.com/marcinLupa/PROGRAMMING-BASIC
ff1bdaa651246a9296d6d12b0c52b7e6178b72eb
57724710446db566385b4d099d77a0e3507c0424
refs/heads/master
2021-07-23T14:53:30.204000
2019-11-19T21:08:58
2019-11-19T21:08:58
222,784,504
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import com.google.gson.JsonParseException; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; class CarService { private List<Car> cars; CarService(List<String> filenameList) { this.cars = filenameList .stream() .map(CarService::getCarFromFile) .collect(Collectors.toList()); validation(); } private static Car getCarFromFile(String filename) { return new CarConverter(filename) .fromJson() .orElseThrow(() -> new JsonParseException("JSON FILE PARSING EXCEPTION")); } private void validation() { CarValidator carValidator = new CarValidator(); try { cars.forEach(carValidator::validate); }catch (Exception e){ if (carValidator.hasErrors()) { carValidator.getErrors().forEach((k, v) -> System.err.println(v)); throw new MyException(ExceptionCode.VALIDATION,"VALIDATION EXCEPTION "); } } } List<Car> sortingCars(SortingOption option, SortingOption kindOfSorting) { try { if (option == null && SortingOption.DESC != kindOfSorting || kindOfSorting != SortingOption.ASC) { throw new NullPointerException("OPTIONS TO SORT ARE NULL OR NOT SORTING_OPTION CLASS EXCEPTION"); } switch (option) { case COMPONENTS: switch (kindOfSorting) { case ASC: return cars .stream() .sorted(Comparator. comparing(x -> x.getCarBody() .getComponents().size()) ) .collect(Collectors.toList()); case DESC: return cars .stream() .sorted(Comparator.<Car, Integer> comparing(x -> x.getCarBody() .getComponents().size()) .reversed()) .collect(Collectors.toList()); } case POWER_ENGINE: switch (kindOfSorting) { case ASC: return cars .stream() .sorted(Comparator. comparing(x -> x.getEngine().getPower())) .collect(Collectors.toList()); case DESC: return cars .stream() .sorted(Comparator.<Car, BigDecimal> comparing(x -> x.getEngine().getPower()) .reversed()) .collect(Collectors.toList()); } case TIRE_SIZE: switch (kindOfSorting) { case ASC: return cars.stream() .sorted(Comparator. comparing(x -> x.getWheels().getSize())) .collect(Collectors.toList()); case DESC: return cars.stream() .sorted(Comparator.<Car, Integer> comparing(x -> x.getWheels().getSize()) .reversed()) .collect(Collectors.toList()); } } } catch (Exception e) { throw new MyException(ExceptionCode.UNIDENTIFIED, "SERVICE SORTING CARS EXCEPTION" + e.getMessage()); } throw new IllegalArgumentException("PARAMETR TO SORTING EXCEPTION"); } Set<Car> choisingCarByBodyAndPrice(KindOfBody bodyToFind, BigDecimal minPrice, BigDecimal maxPrice) { try { return cars .stream() .filter(x -> x.getCarBody().getType().equals(bodyToFind) && x.getPrice().compareTo(minPrice) > 0 && x.getPrice().compareTo(maxPrice) < 0) .collect(Collectors.toSet()); } catch (Exception e) { throw new MyException(ExceptionCode.UNIDENTIFIED, "SERVICE BODY-PRICE METHOD EXCEPTION" + e.getMessage()); } } Set<Car> choisingCarByEngine(EngineType type) { try { return cars .stream() .filter(x -> x.getEngine().getType().equals(type)) .sorted(Comparator.comparing(Car::getModel)) .collect(Collectors.toCollection(LinkedHashSet::new)); } catch (Exception e) { throw new MyException(ExceptionCode.UNIDENTIFIED, "SERVICE CAR-ENGINE METHOD EXCEPTION" + e.getMessage()); } } String carStatistics(SortingOption option) { try { switch (option) { case PRICE: return "MAX: " + cars .stream() .map(Car::getPrice) .max(Comparator.comparing(Function.identity())) .orElseThrow(() -> new IndexOutOfBoundsException("PRICE MAX STATISTIC EXCEPTION")) + " PLN " + ", MIN: " + cars .stream() .map(Car::getPrice) .min(Comparator.comparing(Function.identity())) .orElseThrow(() -> new IndexOutOfBoundsException("PRICE MIN STATISTIC EXCEPTION")) + " PLN " + ", SREDNIA: " + String.format("%2.2f", cars .stream() .map(Car::getPrice) .reduce(BigDecimal::add) .map(x -> x.divide(new BigDecimal(cars.size()), RoundingMode.UP)) .orElseThrow(() -> new IndexOutOfBoundsException("PRICE AVERAGE STATISTIC EXCEPTION"))) + " PLN "; case MILEAGE: return "MAX: " + cars .stream() .mapToInt(Car::getMileage) .summaryStatistics() .getMax() + " KM " + ", MIN: " + cars .stream().mapToInt(Car::getMileage) .summaryStatistics() .getMin() + " KM " + ", SREDNIA: " + String.format("%2.2f", cars .stream() .mapToInt(Car::getMileage) .summaryStatistics() .getAverage()) + " KM "; case POWER_ENGINE: return "MAX: " + cars .stream() .map(x -> x.getEngine().getPower()) .max(Comparator.comparing(Function.identity())) .orElseThrow(() -> new IndexOutOfBoundsException("POWER MAX STATISTIC EXCEPTION")) + " KW " + ", MIN: " + cars .stream() .map(x -> x.getEngine().getPower()) .min(Comparator.comparing(Function.identity())) .orElseThrow(() -> new IndexOutOfBoundsException("POWER MIN STATISTIC EXCEPTION")) + " KM " + ", SREDNIA: " + String.format("%2.2f", cars .stream() .map(x -> x.getEngine().getPower()) .reduce(BigDecimal::add) .map(x -> x.divide(new BigDecimal(cars.size()), RoundingMode.UP)) .orElseThrow(() -> new IndexOutOfBoundsException("POWER AVERAGE STATISTIC EXCEPTION"))) + " KM "; } } catch (Exception e) { throw new MyException(ExceptionCode.VALIDATION, "CARS STATISTIC EXCEPTION" + e.getMessage()); } throw new IllegalArgumentException("SORTING OPTION OUT OF RANGE"); } Map<Car, Integer> carsMileage() { try { return cars .stream() .sorted(Comparator.comparing(Car::getMileage).reversed()) .collect(Collectors.toMap( Function.identity(), Car::getMileage, (v1, v2) -> v1, LinkedHashMap::new )); } catch (Exception e) { throw new MyException(ExceptionCode.VALIDATION, "CARS STATISTIC EXCEPTION" + e.getMessage()); } } Map<TyreType, List<Car>> tyreTypeCars() { try { return cars .stream() .collect(Collectors.groupingBy( k -> k.getWheels().getType())) .entrySet() .stream() .sorted(Comparator.<Map.Entry<TyreType, List<Car>>, Integer>comparing(x -> x.getValue().size()) .reversed()) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1, LinkedHashMap::new)); } catch (Exception e) { throw new MyException(ExceptionCode.VALIDATION, "CARS AND TYRE TYPES EXCEPTION" + e.getMessage()); } } List<Car> carsComponentsFiltring(List<String> components) { try { return cars.stream() .filter(x -> x.getCarBody() .getComponents() .containsAll(components)) .collect(Collectors.toList()); } catch (Exception e) { throw new MyException(ExceptionCode.VALIDATION, "CARS AND TYRE TYPES EXCEPTION" + e.getMessage()); } } }
UTF-8
Java
10,496
java
CarService.java
Java
[]
null
[]
import com.google.gson.JsonParseException; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; class CarService { private List<Car> cars; CarService(List<String> filenameList) { this.cars = filenameList .stream() .map(CarService::getCarFromFile) .collect(Collectors.toList()); validation(); } private static Car getCarFromFile(String filename) { return new CarConverter(filename) .fromJson() .orElseThrow(() -> new JsonParseException("JSON FILE PARSING EXCEPTION")); } private void validation() { CarValidator carValidator = new CarValidator(); try { cars.forEach(carValidator::validate); }catch (Exception e){ if (carValidator.hasErrors()) { carValidator.getErrors().forEach((k, v) -> System.err.println(v)); throw new MyException(ExceptionCode.VALIDATION,"VALIDATION EXCEPTION "); } } } List<Car> sortingCars(SortingOption option, SortingOption kindOfSorting) { try { if (option == null && SortingOption.DESC != kindOfSorting || kindOfSorting != SortingOption.ASC) { throw new NullPointerException("OPTIONS TO SORT ARE NULL OR NOT SORTING_OPTION CLASS EXCEPTION"); } switch (option) { case COMPONENTS: switch (kindOfSorting) { case ASC: return cars .stream() .sorted(Comparator. comparing(x -> x.getCarBody() .getComponents().size()) ) .collect(Collectors.toList()); case DESC: return cars .stream() .sorted(Comparator.<Car, Integer> comparing(x -> x.getCarBody() .getComponents().size()) .reversed()) .collect(Collectors.toList()); } case POWER_ENGINE: switch (kindOfSorting) { case ASC: return cars .stream() .sorted(Comparator. comparing(x -> x.getEngine().getPower())) .collect(Collectors.toList()); case DESC: return cars .stream() .sorted(Comparator.<Car, BigDecimal> comparing(x -> x.getEngine().getPower()) .reversed()) .collect(Collectors.toList()); } case TIRE_SIZE: switch (kindOfSorting) { case ASC: return cars.stream() .sorted(Comparator. comparing(x -> x.getWheels().getSize())) .collect(Collectors.toList()); case DESC: return cars.stream() .sorted(Comparator.<Car, Integer> comparing(x -> x.getWheels().getSize()) .reversed()) .collect(Collectors.toList()); } } } catch (Exception e) { throw new MyException(ExceptionCode.UNIDENTIFIED, "SERVICE SORTING CARS EXCEPTION" + e.getMessage()); } throw new IllegalArgumentException("PARAMETR TO SORTING EXCEPTION"); } Set<Car> choisingCarByBodyAndPrice(KindOfBody bodyToFind, BigDecimal minPrice, BigDecimal maxPrice) { try { return cars .stream() .filter(x -> x.getCarBody().getType().equals(bodyToFind) && x.getPrice().compareTo(minPrice) > 0 && x.getPrice().compareTo(maxPrice) < 0) .collect(Collectors.toSet()); } catch (Exception e) { throw new MyException(ExceptionCode.UNIDENTIFIED, "SERVICE BODY-PRICE METHOD EXCEPTION" + e.getMessage()); } } Set<Car> choisingCarByEngine(EngineType type) { try { return cars .stream() .filter(x -> x.getEngine().getType().equals(type)) .sorted(Comparator.comparing(Car::getModel)) .collect(Collectors.toCollection(LinkedHashSet::new)); } catch (Exception e) { throw new MyException(ExceptionCode.UNIDENTIFIED, "SERVICE CAR-ENGINE METHOD EXCEPTION" + e.getMessage()); } } String carStatistics(SortingOption option) { try { switch (option) { case PRICE: return "MAX: " + cars .stream() .map(Car::getPrice) .max(Comparator.comparing(Function.identity())) .orElseThrow(() -> new IndexOutOfBoundsException("PRICE MAX STATISTIC EXCEPTION")) + " PLN " + ", MIN: " + cars .stream() .map(Car::getPrice) .min(Comparator.comparing(Function.identity())) .orElseThrow(() -> new IndexOutOfBoundsException("PRICE MIN STATISTIC EXCEPTION")) + " PLN " + ", SREDNIA: " + String.format("%2.2f", cars .stream() .map(Car::getPrice) .reduce(BigDecimal::add) .map(x -> x.divide(new BigDecimal(cars.size()), RoundingMode.UP)) .orElseThrow(() -> new IndexOutOfBoundsException("PRICE AVERAGE STATISTIC EXCEPTION"))) + " PLN "; case MILEAGE: return "MAX: " + cars .stream() .mapToInt(Car::getMileage) .summaryStatistics() .getMax() + " KM " + ", MIN: " + cars .stream().mapToInt(Car::getMileage) .summaryStatistics() .getMin() + " KM " + ", SREDNIA: " + String.format("%2.2f", cars .stream() .mapToInt(Car::getMileage) .summaryStatistics() .getAverage()) + " KM "; case POWER_ENGINE: return "MAX: " + cars .stream() .map(x -> x.getEngine().getPower()) .max(Comparator.comparing(Function.identity())) .orElseThrow(() -> new IndexOutOfBoundsException("POWER MAX STATISTIC EXCEPTION")) + " KW " + ", MIN: " + cars .stream() .map(x -> x.getEngine().getPower()) .min(Comparator.comparing(Function.identity())) .orElseThrow(() -> new IndexOutOfBoundsException("POWER MIN STATISTIC EXCEPTION")) + " KM " + ", SREDNIA: " + String.format("%2.2f", cars .stream() .map(x -> x.getEngine().getPower()) .reduce(BigDecimal::add) .map(x -> x.divide(new BigDecimal(cars.size()), RoundingMode.UP)) .orElseThrow(() -> new IndexOutOfBoundsException("POWER AVERAGE STATISTIC EXCEPTION"))) + " KM "; } } catch (Exception e) { throw new MyException(ExceptionCode.VALIDATION, "CARS STATISTIC EXCEPTION" + e.getMessage()); } throw new IllegalArgumentException("SORTING OPTION OUT OF RANGE"); } Map<Car, Integer> carsMileage() { try { return cars .stream() .sorted(Comparator.comparing(Car::getMileage).reversed()) .collect(Collectors.toMap( Function.identity(), Car::getMileage, (v1, v2) -> v1, LinkedHashMap::new )); } catch (Exception e) { throw new MyException(ExceptionCode.VALIDATION, "CARS STATISTIC EXCEPTION" + e.getMessage()); } } Map<TyreType, List<Car>> tyreTypeCars() { try { return cars .stream() .collect(Collectors.groupingBy( k -> k.getWheels().getType())) .entrySet() .stream() .sorted(Comparator.<Map.Entry<TyreType, List<Car>>, Integer>comparing(x -> x.getValue().size()) .reversed()) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1, LinkedHashMap::new)); } catch (Exception e) { throw new MyException(ExceptionCode.VALIDATION, "CARS AND TYRE TYPES EXCEPTION" + e.getMessage()); } } List<Car> carsComponentsFiltring(List<String> components) { try { return cars.stream() .filter(x -> x.getCarBody() .getComponents() .containsAll(components)) .collect(Collectors.toList()); } catch (Exception e) { throw new MyException(ExceptionCode.VALIDATION, "CARS AND TYRE TYPES EXCEPTION" + e.getMessage()); } } }
10,496
0.437976
0.436643
247
41.48988
30.699255
125
false
false
0
0
0
0
0
0
0.315789
false
false
14
07d7e10a9746a7f71bd457451a2af745df6fe393
9,251,359,583,865
44395a83811518861318fcdcf9ec4337ae2d0692
/app/src/main/java/com/example/nfnt/firebasefcm/DisplayNotification.java
1e2b64106656d972446476556bce095cd05979a6
[]
no_license
nafiantaBp1996/FirebaseFcm
https://github.com/nafiantaBp1996/FirebaseFcm
698d54d43cb597a93e0416265155c169c21b8437
9edba4bd20fa50ec6bb843a8c6db631faa02dd44
refs/heads/master
2020-04-01T14:31:08.625000
2018-10-16T14:13:43
2018-10-16T14:13:43
153,297,445
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.nfnt.firebasefcm; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.media.RingtoneManager; import android.net.Uri; import android.support.v7.app.NotificationCompat; /** * Created by NFNT on 10/16/2018. */ public class DisplayNotification { private Context myCntx ; private static DisplayNotification mInsNotif; private DisplayNotification (Context context) { myCntx = context; } public static synchronized DisplayNotification getMyInstance (Context context) { if (mInsNotif == null) { mInsNotif = new DisplayNotification(context); } return mInsNotif; } public void displayNotif(String title, String body) { String CHANNEL_ID = "my_channel"; Intent theAactivity = new Intent(myCntx,MainActivity.class); PendingIntent pdngIntent = PendingIntent.getActivity(myCntx,0,theAactivity,PendingIntent.FLAG_ONE_SHOT); MainActivity.cont = body; MainActivity.titles = title; Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder myBuildNotif= (NotificationCompat.Builder) new NotificationCompat.Builder(myCntx) .setSmallIcon(R.drawable.flat) .setContentTitle(title) .setContentText(body) .setAutoCancel(true) .setSound(defaultSound) .setContentIntent(pdngIntent); NotificationManager myNotifMgr = (NotificationManager) myCntx.getSystemService(Context.NOTIFICATION_SERVICE); if (myNotifMgr != null) { myNotifMgr.notify(1,myBuildNotif.build()); } } }
UTF-8
Java
1,827
java
DisplayNotification.java
Java
[ { "context": "port.v7.app.NotificationCompat;\n\n/**\n * Created by NFNT on 10/16/2018.\n */\n\npublic class DisplayNotificat", "end": 311, "score": 0.9976586699485779, "start": 307, "tag": "USERNAME", "value": "NFNT" } ]
null
[]
package com.example.nfnt.firebasefcm; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.media.RingtoneManager; import android.net.Uri; import android.support.v7.app.NotificationCompat; /** * Created by NFNT on 10/16/2018. */ public class DisplayNotification { private Context myCntx ; private static DisplayNotification mInsNotif; private DisplayNotification (Context context) { myCntx = context; } public static synchronized DisplayNotification getMyInstance (Context context) { if (mInsNotif == null) { mInsNotif = new DisplayNotification(context); } return mInsNotif; } public void displayNotif(String title, String body) { String CHANNEL_ID = "my_channel"; Intent theAactivity = new Intent(myCntx,MainActivity.class); PendingIntent pdngIntent = PendingIntent.getActivity(myCntx,0,theAactivity,PendingIntent.FLAG_ONE_SHOT); MainActivity.cont = body; MainActivity.titles = title; Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder myBuildNotif= (NotificationCompat.Builder) new NotificationCompat.Builder(myCntx) .setSmallIcon(R.drawable.flat) .setContentTitle(title) .setContentText(body) .setAutoCancel(true) .setSound(defaultSound) .setContentIntent(pdngIntent); NotificationManager myNotifMgr = (NotificationManager) myCntx.getSystemService(Context.NOTIFICATION_SERVICE); if (myNotifMgr != null) { myNotifMgr.notify(1,myBuildNotif.build()); } } }
1,827
0.679256
0.673235
65
27.107693
29.48435
117
false
false
0
0
0
0
0
0
0.430769
false
false
14
f66f2cb9d1bd8258be89e219abc174934f1b4e41
14,525,579,427,778
375c19661cc7352422ee239966e76ec2dc37d0f8
/src/example/java/proxy/identifiers/MethodCallInstructionIdentifier.java
aa02d58f8c5f9de6cf94ee47d6e65cf2c6c7efaf
[ "MIT" ]
permissive
TheCyberBrick/pr0x79
https://github.com/TheCyberBrick/pr0x79
50e9d1a3ba4395476ca3a19bc5b5c55fdd1224fa
334b8d0d5c0b9223e997b6dfaeb73b596cd0682d
refs/heads/master
2020-12-02T19:32:12.363000
2019-08-27T19:46:34
2019-08-27T19:46:34
96,355,606
5
2
null
null
null
null
null
null
null
null
null
null
null
null
null
package proxy.identifiers; import java.util.Iterator; import java.util.List; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import pr0x79.instrumentation.identification.IInstructionIdentifier; import pr0x79.instrumentation.identification.IMethodIdentifier.MethodDescription; public class MethodCallInstructionIdentifier implements IInstructionIdentifier { private final String[] owners; private final MethodDescription[] methods; private final boolean before; public MethodCallInstructionIdentifier(List<String> owners, List<String> methodNames, List<String> methodDescriptors, boolean before) { this.owners = owners.toArray(new String[0]); this.methods = new MethodDescription[methodNames.size()]; for(int i = 0; i < methodNames.size(); i++) { this.methods[i] = new MethodDescription(methodNames.get(i), methodDescriptors.get(i)); } this.before = before; } @Override public InstructionType getType() { return InstructionType.INSTRUCTION; } @Override public int identify(MethodNode method) { Iterator<AbstractInsnNode> it = method.instructions.iterator(); AbstractInsnNode insn; while(it.hasNext()) { insn = it.next(); if(insn instanceof MethodInsnNode) { MethodInsnNode methodNode = (MethodInsnNode) insn; for(int i = 0; i < this.owners.length; i++) { String owner = this.owners[i]; MethodDescription methodDescription = this.methods[i]; if(owner.equals(methodNode.owner) && methodDescription.getName().equals(methodNode.name) && methodDescription.getDescriptor().equals(methodNode.desc)) { return method.instructions.indexOf(methodNode) + (this.before ? 0 : 1); } } } } return -1; } }
UTF-8
Java
1,766
java
MethodCallInstructionIdentifier.java
Java
[]
null
[]
package proxy.identifiers; import java.util.Iterator; import java.util.List; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import pr0x79.instrumentation.identification.IInstructionIdentifier; import pr0x79.instrumentation.identification.IMethodIdentifier.MethodDescription; public class MethodCallInstructionIdentifier implements IInstructionIdentifier { private final String[] owners; private final MethodDescription[] methods; private final boolean before; public MethodCallInstructionIdentifier(List<String> owners, List<String> methodNames, List<String> methodDescriptors, boolean before) { this.owners = owners.toArray(new String[0]); this.methods = new MethodDescription[methodNames.size()]; for(int i = 0; i < methodNames.size(); i++) { this.methods[i] = new MethodDescription(methodNames.get(i), methodDescriptors.get(i)); } this.before = before; } @Override public InstructionType getType() { return InstructionType.INSTRUCTION; } @Override public int identify(MethodNode method) { Iterator<AbstractInsnNode> it = method.instructions.iterator(); AbstractInsnNode insn; while(it.hasNext()) { insn = it.next(); if(insn instanceof MethodInsnNode) { MethodInsnNode methodNode = (MethodInsnNode) insn; for(int i = 0; i < this.owners.length; i++) { String owner = this.owners[i]; MethodDescription methodDescription = this.methods[i]; if(owner.equals(methodNode.owner) && methodDescription.getName().equals(methodNode.name) && methodDescription.getDescriptor().equals(methodNode.desc)) { return method.instructions.indexOf(methodNode) + (this.before ? 0 : 1); } } } } return -1; } }
1,766
0.753114
0.746319
51
33.627453
33.927814
157
false
false
0
0
0
0
0
0
2.254902
false
false
14
986b0bcd5793c3c606a93ae4f6b898acd464e7fa
6,468,220,783,946
795434741bac632b5e98dd34bc27a4851695479d
/tree/BSTIterator.java
5eb81699f7864c16e0bf6790ae5f6f134c171b65
[]
no_license
exmy/Algorithms
https://github.com/exmy/Algorithms
23e34e5051200789a43c914da67f160860b0a421
39123230cadac11d5a819ace6ad9581c6d876c02
refs/heads/master
2020-04-06T14:18:46.950000
2019-04-03T13:35:46
2019-04-03T13:35:46
157,536,191
1
1
null
false
2018-12-21T04:51:21
2018-11-14T11:05:49
2018-12-20T13:23:57
2018-12-20T13:23:55
47
0
0
0
Java
false
null
public class BSTIterator { private LinkedList<TreeNode> stack; public BSTIterator(TreeNode root) { stack = new LinkedList<>(); add(root); } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty(); } /** @return the next smallest number */ public int next() { TreeNode node = stack.pop(); add(node.right); return node.val; } private void add(TreeNode node){ while(node != null){ stack.push(node); node = node.left; } } }
UTF-8
Java
609
java
BSTIterator.java
Java
[]
null
[]
public class BSTIterator { private LinkedList<TreeNode> stack; public BSTIterator(TreeNode root) { stack = new LinkedList<>(); add(root); } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty(); } /** @return the next smallest number */ public int next() { TreeNode node = stack.pop(); add(node.right); return node.val; } private void add(TreeNode node){ while(node != null){ stack.push(node); node = node.left; } } }
609
0.543514
0.543514
27
21.555555
15.729975
57
false
false
0
0
0
0
0
0
0.333333
false
false
14
fa3a0ab4529080e51c64904a0cd58b68eba93373
1,219,770,744,576
a60c908235a07dc46b737ec3e2ee49dcdbcc8268
/Java/src/org/magnos/steer/target/TargetRelative.java
356f637894e793f2b2921ddf17ae5f616e7b0b7a
[]
no_license
kyleburkhardt/steerio
https://github.com/kyleburkhardt/steerio
e5553eed0e58a17c22dbc59da72268203c0a0d67
4b8f8a90dc86a78dfc2c2152c6f7ef6f011e0fbe
refs/heads/master
2021-01-18T06:28:59.118000
2014-08-16T03:32:05
2014-08-16T03:32:05
12,492,225
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.magnos.steer.target; import org.magnos.steer.SteerSubject; import org.magnos.steer.Target; import org.magnos.steer.vec.Vec; // when your target is not relative to you, it's relative to another steer subject. public class TargetRelative<V extends Vec<V>> implements Target<V> { public SteerSubject<V> relativeTo; public Target<V> target; public TargetRelative( SteerSubject<V> relativeTo, Target<V> target ) { this.relativeTo = relativeTo; this.target = target; } @Override public V getTarget( SteerSubject<V> subject ) { return target.getTarget( relativeTo ); } }
UTF-8
Java
650
java
TargetRelative.java
Java
[]
null
[]
package org.magnos.steer.target; import org.magnos.steer.SteerSubject; import org.magnos.steer.Target; import org.magnos.steer.vec.Vec; // when your target is not relative to you, it's relative to another steer subject. public class TargetRelative<V extends Vec<V>> implements Target<V> { public SteerSubject<V> relativeTo; public Target<V> target; public TargetRelative( SteerSubject<V> relativeTo, Target<V> target ) { this.relativeTo = relativeTo; this.target = target; } @Override public V getTarget( SteerSubject<V> subject ) { return target.getTarget( relativeTo ); } }
650
0.689231
0.689231
26
24
24.205849
83
false
false
0
0
0
0
0
0
0.423077
false
false
14
d98b2565072f349db8daa71593d29634c1950c6e
1,039,382,122,884
a0aabbaa605fde80b9bf480b37a2ad688492fbbb
/src/Easy/Factorial.java
d2949445acd4c5772b5743ffaf92fbb2257c16bc
[]
no_license
jejobueno/opdracthen
https://github.com/jejobueno/opdracthen
7a02c41b3da17801feddbcd83b26b4481fcad398
df4c8eee770f4616ae664b035f05ef779d07c37a
refs/heads/master
2022-11-28T05:22:57.895000
2020-08-07T13:36:31
2020-08-07T13:36:31
285,836,077
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Easy; import java.util.Scanner; public class Factorial { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); System.out.println("Introduce a number"); int number = kbd.nextInt(); System.out.println("Factorial: "); System.out.println(factorial(number));; } public static int factorial(int number){ int facto = 1; for (int i = number; i > 0; i--) { facto = i*facto; } return facto; } }
UTF-8
Java
524
java
Factorial.java
Java
[]
null
[]
package Easy; import java.util.Scanner; public class Factorial { public static void main(String[] args) { Scanner kbd = new Scanner(System.in); System.out.println("Introduce a number"); int number = kbd.nextInt(); System.out.println("Factorial: "); System.out.println(factorial(number));; } public static int factorial(int number){ int facto = 1; for (int i = number; i > 0; i--) { facto = i*facto; } return facto; } }
524
0.566794
0.562977
23
21.782608
18.127462
49
false
false
0
0
0
0
0
0
0.565217
false
false
14
dd14819ff9b16281b7642cba89ff0aa4fc63bba1
30,451,318,156,192
c81dd37adb032fb057d194b5383af7aa99f79c6a
/java/com/facebook/ads/redexgen/X/C0390Fg.java
6aac0bbc8f83b5c742a55467b27ee8390a97d531
[]
no_license
hongnam207/pi-network-source
https://github.com/hongnam207/pi-network-source
1415a955e37fe58ca42098967f0b3307ab0dc785
17dc583f08f461d4dfbbc74beb98331bf7f9e5e3
refs/heads/main
2023-03-30T07:49:35.920000
2021-03-28T06:56:24
2021-03-28T06:56:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.facebook.ads.redexgen.X; /* renamed from: com.facebook.ads.redexgen.X.Fg reason: case insensitive filesystem */ public final class C0390Fg extends C0681Qv { public C0390Fg(String str, Throwable th) { super(str, th); } }
UTF-8
Java
250
java
C0390Fg.java
Java
[]
null
[]
package com.facebook.ads.redexgen.X; /* renamed from: com.facebook.ads.redexgen.X.Fg reason: case insensitive filesystem */ public final class C0390Fg extends C0681Qv { public C0390Fg(String str, Throwable th) { super(str, th); } }
250
0.708
0.66
8
30.25
27.729723
87
false
false
0
0
0
0
0
0
0.5
false
false
14
4e875047ff7c8c1599f660bc6c2f57020f72546e
12,610,024,005,710
ef7ea390ecefa3262ccd04eb4d0d69b5c67aaff3
/src/main/java/com/rbkmoney/fraudbusters/listener/events/clickhouse/ChargebackEventListener.java
97c9e1a9f01e71e924881e979c9dad6f595ababb
[ "Apache-2.0" ]
permissive
rbkmoney/fraudbusters
https://github.com/rbkmoney/fraudbusters
e83484e01be74ef05a70baf3478ecb81e44c0c51
8afd73d4b237012a071f6ba7d15ee3922afbce27
refs/heads/master
2023-06-30T11:49:09.023000
2021-12-06T13:41:08
2021-12-06T13:41:08
159,638,539
40
13
Apache-2.0
false
2023-06-14T22:36:43
2018-11-29T09:12:21
2023-01-29T03:19:07
2023-06-14T22:36:43
2,489
39
11
1
Java
false
false
package com.rbkmoney.fraudbusters.listener.events.clickhouse; import com.rbkmoney.damsel.fraudbusters.Chargeback; import com.rbkmoney.fraudbusters.config.service.ListenersConfigurationService; import com.rbkmoney.fraudbusters.repository.Repository; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.kafka.support.KafkaHeaders; import org.springframework.messaging.handler.annotation.Header; import org.springframework.stereotype.Component; import java.util.List; @Slf4j @Component @RequiredArgsConstructor public class ChargebackEventListener { private final Repository<Chargeback> repository; @KafkaListener(topics = "${kafka.topic.event.sink.chargeback}", containerFactory = "kafkaChargebackResultListenerContainerFactory") public void listen( List<Chargeback> chargeback, @Header(KafkaHeaders.RECEIVED_PARTITION_ID) Integer partition, @Header(KafkaHeaders.OFFSET) Long offset) throws InterruptedException { try { log.info( "ChargebackEventListener listen result size: {} partition: {} offset: {}", chargeback.size(), partition, offset ); repository.insertBatch(chargeback); } catch (Exception e) { log.warn("Error when ChargebackEventListener listen e: ", e); Thread.sleep(ListenersConfigurationService.THROTTLING_TIMEOUT); throw e; } } }
UTF-8
Java
1,584
java
ChargebackEventListener.java
Java
[]
null
[]
package com.rbkmoney.fraudbusters.listener.events.clickhouse; import com.rbkmoney.damsel.fraudbusters.Chargeback; import com.rbkmoney.fraudbusters.config.service.ListenersConfigurationService; import com.rbkmoney.fraudbusters.repository.Repository; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.kafka.support.KafkaHeaders; import org.springframework.messaging.handler.annotation.Header; import org.springframework.stereotype.Component; import java.util.List; @Slf4j @Component @RequiredArgsConstructor public class ChargebackEventListener { private final Repository<Chargeback> repository; @KafkaListener(topics = "${kafka.topic.event.sink.chargeback}", containerFactory = "kafkaChargebackResultListenerContainerFactory") public void listen( List<Chargeback> chargeback, @Header(KafkaHeaders.RECEIVED_PARTITION_ID) Integer partition, @Header(KafkaHeaders.OFFSET) Long offset) throws InterruptedException { try { log.info( "ChargebackEventListener listen result size: {} partition: {} offset: {}", chargeback.size(), partition, offset ); repository.insertBatch(chargeback); } catch (Exception e) { log.warn("Error when ChargebackEventListener listen e: ", e); Thread.sleep(ListenersConfigurationService.THROTTLING_TIMEOUT); throw e; } } }
1,584
0.708965
0.707071
41
37.634148
28.729824
103
false
false
0
0
0
0
0
0
0.585366
false
false
14
afc0139abd2554b0dbcbd1f4462f76249cb6dfbf
32,091,995,667,077
5288a521d25dbaa93165069a9524041f93221907
/src/test/java/test/OwnerTest.java
44249e9cf86bb5528f2ab76e2c8ebb2478fe8f6f
[]
no_license
dstumpe264/Lemonade
https://github.com/dstumpe264/Lemonade
e73af0896fb639f17550d28b4e9733874347b512
589f47a79fbc2bb2cda291c3ff4c66ac360d0d83
refs/heads/main
2023-06-18T10:32:09.864000
2021-07-25T08:40:01
2021-07-25T08:40:01
385,455,865
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test; import org.junit.Assert; import static org.junit.Assert.assertEquals; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.PersistenceContext; import org.junit.Before; import org.junit.After; import org.junit.Test; import com.stumpy.lemonade.entities.Owner; import com.stumpy.lemonade.entities.Lemonadestand; import com.stumpy.lemonade.entities.Product; public class OwnerTest { private EntityManager em; private EntityManagerFactory emf; private Lemonadestand stand; private Product product; @Before public void setUp() throws Exception{ emf = Persistence.createEntityManagerFactory("LemonadePU"); em = emf.createEntityManager(); // stand = em.find(Lemonadestand.class, 1); // product = em.find(Product.class, 1); } @After public void tearDown() throws Exception { this.em.close(); this.emf.close(); } @Test public void testingMapping() { Owner owner = em.find(Owner.class, 1); assertEquals("david", owner.getFirstName()); assertEquals("stumpe", owner.getLastName()); assertEquals("stumpy", owner.getUserName()); } }
UTF-8
Java
1,178
java
OwnerTest.java
Java
[ { "context": " owner = em.find(Owner.class, 1);\n\t\tassertEquals(\"david\", owner.getFirstName());\n\t\tassertEquals(\"stumpe\",", "end": 1051, "score": 0.8890732526779175, "start": 1046, "tag": "NAME", "value": "david" }, { "context": "s(\"david\", owner.getFirstName());\n\t\tassertEquals(\"stumpe\", owner.getLastName());\n\t\tassertEquals(\"stumpy\", ", "end": 1099, "score": 0.9929024577140808, "start": 1093, "tag": "NAME", "value": "stumpe" } ]
null
[]
package test; import org.junit.Assert; import static org.junit.Assert.assertEquals; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.PersistenceContext; import org.junit.Before; import org.junit.After; import org.junit.Test; import com.stumpy.lemonade.entities.Owner; import com.stumpy.lemonade.entities.Lemonadestand; import com.stumpy.lemonade.entities.Product; public class OwnerTest { private EntityManager em; private EntityManagerFactory emf; private Lemonadestand stand; private Product product; @Before public void setUp() throws Exception{ emf = Persistence.createEntityManagerFactory("LemonadePU"); em = emf.createEntityManager(); // stand = em.find(Lemonadestand.class, 1); // product = em.find(Product.class, 1); } @After public void tearDown() throws Exception { this.em.close(); this.emf.close(); } @Test public void testingMapping() { Owner owner = em.find(Owner.class, 1); assertEquals("david", owner.getFirstName()); assertEquals("stumpe", owner.getLastName()); assertEquals("stumpy", owner.getUserName()); } }
1,178
0.760611
0.758065
49
23.040817
18.493196
61
false
false
0
0
0
0
0
0
1.44898
false
false
14
e3c5c9d92839cb9cb0026a8e4f542a5966d5be2f
26,405,458,968,039
184d369800382b896a8cf2e890b069cc8e4e5118
/services/messaging/src/main/java/com/github/punchat/messaging/domain/role/RoleFinderImpl.java
9f6c5f703943d1a4e072bf6131ab596c1ee705f5
[ "Apache-2.0" ]
permissive
punchat/punchat
https://github.com/punchat/punchat
839864dfe02c0b1a2ba892791eb288f9649311f2
969f64e12a0ac9357ec693de075c9a928e8a783a
refs/heads/dev
2020-03-07T14:45:21.661000
2018-06-10T05:29:54
2018-06-10T05:29:54
127,534,735
1
0
Apache-2.0
false
2018-06-10T05:29:55
2018-03-31T13:32:09
2018-06-09T21:04:45
2018-06-10T05:29:54
517
0
0
9
Java
false
null
package com.github.punchat.messaging.domain.role; import com.github.punchat.messaging.domain.ResourceNotFoundException; import com.github.punchat.messaging.domain.channel.BroadcastChannel; import org.springframework.stereotype.Service; import java.util.Set; @Service public class RoleFinderImpl implements RoleFinder { private final RoleRepository repository; public RoleFinderImpl(RoleRepository repository) { this.repository = repository; } @Override public Role byId(Long id) { return repository.findById(id).orElseThrow(() -> new ResourceNotFoundException("role", id)); } @Override public Role owner(BroadcastChannel channel) { return repository.findByChannelAndName(channel, DefaultRoles.OWNER).orElseThrow(() -> new RuntimeException("owner role not found")); } @Override public Set<Role> byChannel(BroadcastChannel channel) { return repository.findByChannel(channel); } @Override public Role defaultRole(BroadcastChannel channel) { return repository.findByChannelAndName(channel, DefaultRoles.DEFAULT).orElseThrow(() -> new RuntimeException("default role not found")); } }
UTF-8
Java
1,219
java
RoleFinderImpl.java
Java
[]
null
[]
package com.github.punchat.messaging.domain.role; import com.github.punchat.messaging.domain.ResourceNotFoundException; import com.github.punchat.messaging.domain.channel.BroadcastChannel; import org.springframework.stereotype.Service; import java.util.Set; @Service public class RoleFinderImpl implements RoleFinder { private final RoleRepository repository; public RoleFinderImpl(RoleRepository repository) { this.repository = repository; } @Override public Role byId(Long id) { return repository.findById(id).orElseThrow(() -> new ResourceNotFoundException("role", id)); } @Override public Role owner(BroadcastChannel channel) { return repository.findByChannelAndName(channel, DefaultRoles.OWNER).orElseThrow(() -> new RuntimeException("owner role not found")); } @Override public Set<Role> byChannel(BroadcastChannel channel) { return repository.findByChannel(channel); } @Override public Role defaultRole(BroadcastChannel channel) { return repository.findByChannelAndName(channel, DefaultRoles.DEFAULT).orElseThrow(() -> new RuntimeException("default role not found")); } }
1,219
0.723544
0.723544
38
31.078947
30.38904
100
false
false
0
0
0
0
0
0
0.368421
false
false
14
422ea14734feeea825f2be58bc8bfa2ebbe37a24
26,405,458,965,076
12adc9013be2e2274f837c330471e3c49edbb830
/src/main/java/ca/joyfactory/coims/controller/RestExceptionController.java
55f047c25a8ebc4d11c2a955bfa03b8e33d66469
[]
no_license
johndpope/coims
https://github.com/johndpope/coims
77501b71e58183e09f4c2f3044e814b5f39e4ef0
41218665b211c97d293ecec646212fc475ae00f6
refs/heads/master
2023-06-19T17:45:54.933000
2021-07-19T17:04:01
2021-07-19T17:04:01
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ca.joyfactory.coims.controller; import ca.joyfactory.coims.exception.*; import ca.joyfactory.coims.service.ExceptionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; /** * Created by Joinsu on 2018-07-24. */ @ControllerAdvice public class RestExceptionController { @Autowired private ExceptionService exceptionService; @ExceptionHandler( DuplicateUserException.class) public ResponseEntity duplicateUserException( DuplicateUserException e, WebRequest webRequest){ return new ResponseEntity( exceptionService.executeLogging( e, webRequest), HttpStatus.BAD_REQUEST); } @ExceptionHandler( NotFoundUserException.class) public ResponseEntity notFoundUserException( NotFoundUserException e, WebRequest webRequest){ return new ResponseEntity( exceptionService.executeLogging( e, webRequest), HttpStatus.BAD_REQUEST); } @ExceptionHandler( NotFoundDataException.class) public ResponseEntity notFoundDataException( NotFoundDataException e, WebRequest webRequest){ return new ResponseEntity( exceptionService.executeLogging( e, webRequest), HttpStatus.BAD_REQUEST); } @ExceptionHandler( FileControlException.class) public ResponseEntity fileControlException( FileControlException e, WebRequest webRequest){ return new ResponseEntity( exceptionService.executeLogging( e, webRequest), HttpStatus.BAD_REQUEST); } @ExceptionHandler( ArgumentException.class) public ResponseEntity argumentException( ArgumentException e, WebRequest webRequest){ return new ResponseEntity( exceptionService.executeLogging( e, webRequest), HttpStatus.BAD_REQUEST); } }
UTF-8
Java
1,964
java
RestExceptionController.java
Java
[ { "context": "web.context.request.WebRequest;\n\n/**\n * Created by Joinsu on 2018-07-24.\n */\n@ControllerAdvice\npublic class", "end": 503, "score": 0.9985479116439819, "start": 497, "tag": "USERNAME", "value": "Joinsu" } ]
null
[]
package ca.joyfactory.coims.controller; import ca.joyfactory.coims.exception.*; import ca.joyfactory.coims.service.ExceptionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; /** * Created by Joinsu on 2018-07-24. */ @ControllerAdvice public class RestExceptionController { @Autowired private ExceptionService exceptionService; @ExceptionHandler( DuplicateUserException.class) public ResponseEntity duplicateUserException( DuplicateUserException e, WebRequest webRequest){ return new ResponseEntity( exceptionService.executeLogging( e, webRequest), HttpStatus.BAD_REQUEST); } @ExceptionHandler( NotFoundUserException.class) public ResponseEntity notFoundUserException( NotFoundUserException e, WebRequest webRequest){ return new ResponseEntity( exceptionService.executeLogging( e, webRequest), HttpStatus.BAD_REQUEST); } @ExceptionHandler( NotFoundDataException.class) public ResponseEntity notFoundDataException( NotFoundDataException e, WebRequest webRequest){ return new ResponseEntity( exceptionService.executeLogging( e, webRequest), HttpStatus.BAD_REQUEST); } @ExceptionHandler( FileControlException.class) public ResponseEntity fileControlException( FileControlException e, WebRequest webRequest){ return new ResponseEntity( exceptionService.executeLogging( e, webRequest), HttpStatus.BAD_REQUEST); } @ExceptionHandler( ArgumentException.class) public ResponseEntity argumentException( ArgumentException e, WebRequest webRequest){ return new ResponseEntity( exceptionService.executeLogging( e, webRequest), HttpStatus.BAD_REQUEST); } }
1,964
0.798371
0.794297
45
42.622223
38.113449
108
false
false
0
0
0
0
0
0
0.666667
false
false
14
031b04a92642c24a73ef903b4ec0ae5956e42df2
30,803,505,475,289
c0163d6924d50810d341fe03649acd647a463839
/junit-rule/src/test/java/com/advenoh/rules/SpringContextRule.java
dfce12de4d2be459771c67d8164467a49a13b84e
[]
no_license
legend59/tutorials-java
https://github.com/legend59/tutorials-java
2156d165041d042e23c7106c7ce46ad17e378bc8
783bdf228142fe1a0dc7c06b0d0d20d3101dead5
refs/heads/master
2023-06-26T18:28:46.801000
2021-07-25T01:47:38
2021-07-25T01:47:38
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.advenoh.rules; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringContextRule implements TestRule { /** * A list of class-path contexts. */ private final String[] locations; /** * The target test. */ private final Object target; public SpringContextRule(String[] locations, Object target) { this.locations = locations; this.target = target; } public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( locations); context.getAutowireCapableBeanFactory().autowireBean(target); context.start(); try { base.evaluate(); } finally { context.close(); } } }; } }
UTF-8
Java
1,035
java
SpringContextRule.java
Java
[]
null
[]
package com.advenoh.rules; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringContextRule implements TestRule { /** * A list of class-path contexts. */ private final String[] locations; /** * The target test. */ private final Object target; public SpringContextRule(String[] locations, Object target) { this.locations = locations; this.target = target; } public Statement apply(final Statement base, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( locations); context.getAutowireCapableBeanFactory().autowireBean(target); context.start(); try { base.evaluate(); } finally { context.close(); } } }; } }
1,035
0.738164
0.738164
42
23.666666
23.415163
80
false
false
0
0
0
0
0
0
2.071429
false
false
14
964bcc337b09ecb150c3ce1f60244406b0896987
8,804,682,959,595
c7af8140f796046eb48d0885bf6451ba50a52686
/itemcenter/item-core/src/main/java/com/mockuai/itemcenter/core/dao/ItemExtraInfoDAO.java
104c75ecad9bdb107e1d08e4984917986a38b897
[]
no_license
dijkstr/hzmklearn
https://github.com/dijkstr/hzmklearn
2ad4c3a4a475e92a81a74e7068ea52d660183dea
944cd0ddcc6d1bbcbe8500fdf8722697ec54ea41
refs/heads/master
2018-01-07T09:58:33.373000
2015-08-11T09:29:42
2015-08-11T09:29:42
40,533,315
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mockuai.itemcenter.core.dao; import java.util.List; import org.springframework.stereotype.Service; import com.mockuai.itemcenter.common.domain.qto.ItemExtraInfoQTO; import com.mockuai.itemcenter.core.domain.ItemExtraInfoDO; @Service public interface ItemExtraInfoDAO { /** * 增加商品扩展信息 * * @param itemExtraInfoDO * @return */ Long addItemExtraInfo(ItemExtraInfoDO itemExtraInfoDO); /** * 根据id获取商品扩展信息 * * @param id * @return */ ItemExtraInfoDO getItemExtraInfo(Long id,Long sellerId); /** * 根据id删除商品扩展信息 * * @param sellerId * @param id * @return */ int deleteItemExtraInfo(Long id, Long sellerId); /** * 更新商品扩展信息信息 * * @param itemExtraInfoDO * @return */ int updateItemExtraInfo(ItemExtraInfoDO itemExtraInfoDO); /** * 返回商品扩展信息列表 * * @param itemExtraInfoQTO * @return */ List<ItemExtraInfoDO> queryItemExtraInfo(ItemExtraInfoQTO itemExtraInfoQTO); }
UTF-8
Java
1,085
java
ItemExtraInfoDAO.java
Java
[]
null
[]
package com.mockuai.itemcenter.core.dao; import java.util.List; import org.springframework.stereotype.Service; import com.mockuai.itemcenter.common.domain.qto.ItemExtraInfoQTO; import com.mockuai.itemcenter.core.domain.ItemExtraInfoDO; @Service public interface ItemExtraInfoDAO { /** * 增加商品扩展信息 * * @param itemExtraInfoDO * @return */ Long addItemExtraInfo(ItemExtraInfoDO itemExtraInfoDO); /** * 根据id获取商品扩展信息 * * @param id * @return */ ItemExtraInfoDO getItemExtraInfo(Long id,Long sellerId); /** * 根据id删除商品扩展信息 * * @param sellerId * @param id * @return */ int deleteItemExtraInfo(Long id, Long sellerId); /** * 更新商品扩展信息信息 * * @param itemExtraInfoDO * @return */ int updateItemExtraInfo(ItemExtraInfoDO itemExtraInfoDO); /** * 返回商品扩展信息列表 * * @param itemExtraInfoQTO * @return */ List<ItemExtraInfoDO> queryItemExtraInfo(ItemExtraInfoQTO itemExtraInfoQTO); }
1,085
0.676441
0.676441
54
16.351852
19.903618
77
false
false
0
0
0
0
0
0
0.888889
false
false
14
73773bd9ad06e2c92a7f599ea02c3a1c211b1430
8,804,682,958,984
a55be06e591283070028badd4f85d8252c53571e
/dubbo-serviceinvoke/src/main/java/com/kl/dubbotest/serviceinvoke/provider/DemoServiceImpl.java
4cfcc766a71707cb191106bfdd966ee95556fd94
[]
no_license
number-0/dubbo-test
https://github.com/number-0/dubbo-test
4a386067eda2ed57749d4cd252fbe22f811406cd
b96392c82e041f9c004ce07d9a3a866a90f757b6
refs/heads/master
2022-12-22T07:52:28.739000
2019-07-31T13:49:29
2019-07-31T13:49:29
196,119,313
1
0
null
false
2022-12-16T06:26:43
2019-07-10T02:51:59
2019-07-31T13:49:39
2022-12-16T06:26:40
39
1
0
9
Java
false
false
package com.kl.dubbotest.serviceinvoke.provider; import com.alibaba.dubbo.rpc.RpcContext; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; /** * @author songhengliang * @date 2019/7/29 */ public class DemoServiceImpl implements DemoService { @Override public String sayHello(String name) { Random random = new Random(); try { Thread.sleep(1000 * random.nextInt(6)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( "[" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "] Hello " + name + ", request from consumer: " + RpcContext.getContext().getRemoteAddress()); return "Hello " + name + ", response from provider: " + RpcContext.getContext() .getLocalAddress(); } }
UTF-8
Java
883
java
DemoServiceImpl.java
Java
[ { "context": "til.Date;\nimport java.util.Random;\n\n/**\n * @author songhengliang\n * @date 2019/7/29\n */\npublic class DemoServiceIm", "end": 203, "score": 0.9612371325492859, "start": 190, "tag": "USERNAME", "value": "songhengliang" } ]
null
[]
package com.kl.dubbotest.serviceinvoke.provider; import com.alibaba.dubbo.rpc.RpcContext; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; /** * @author songhengliang * @date 2019/7/29 */ public class DemoServiceImpl implements DemoService { @Override public String sayHello(String name) { Random random = new Random(); try { Thread.sleep(1000 * random.nextInt(6)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println( "[" + new SimpleDateFormat("HH:mm:ss").format(new Date()) + "] Hello " + name + ", request from consumer: " + RpcContext.getContext().getRemoteAddress()); return "Hello " + name + ", response from provider: " + RpcContext.getContext() .getLocalAddress(); } }
883
0.613817
0.600227
28
30.535715
27.252106
100
false
false
0
0
0
0
0
0
0.428571
false
false
14
9dc4308d533e25a053ff89b20e64837940225390
13,211,319,424,561
b5b9ecfedf8fdffc05bd0ceff4609e644e8af977
/Ambulatorio/src/com/digital/business/EmpresaBusiness.java
0fd3a233c2276b62f2c0c5f7365ab1bc8172a7c7
[]
no_license
worlock257/Digital
https://github.com/worlock257/Digital
be73999fe2965d27cd47002d6ba7910ec1a67696
c14c051a76511a466ecc8b6522584e84177b8859
refs/heads/master
2021-03-12T22:51:23.209000
2013-07-10T00:48:16
2013-07-10T00:48:16
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.digital.business; import java.util.List; import com.digital.bean.EmpresaBean; import com.digital.dao.EmpresaDAO; public class EmpresaBusiness { public Boolean salvarAtualizarEmpresa(EmpresaBean bean) { EmpresaDAO dao = new EmpresaDAO(); if(bean.getIdEmpresa() == 0){ if(dao.salvar(bean)){ return true; } }else{ if(dao.atualizar(bean)){ return true; } } return false; } public List<EmpresaBean> listarEmpresasCadastradas() { EmpresaDAO dao = new EmpresaDAO(); return dao.listar(); } }
UTF-8
Java
599
java
EmpresaBusiness.java
Java
[]
null
[]
package com.digital.business; import java.util.List; import com.digital.bean.EmpresaBean; import com.digital.dao.EmpresaDAO; public class EmpresaBusiness { public Boolean salvarAtualizarEmpresa(EmpresaBean bean) { EmpresaDAO dao = new EmpresaDAO(); if(bean.getIdEmpresa() == 0){ if(dao.salvar(bean)){ return true; } }else{ if(dao.atualizar(bean)){ return true; } } return false; } public List<EmpresaBean> listarEmpresasCadastradas() { EmpresaDAO dao = new EmpresaDAO(); return dao.listar(); } }
599
0.632721
0.631052
37
14.189189
16.378691
58
false
false
0
0
0
0
0
0
1.675676
false
false
14
cc40ee3496f2bbc0835917206a5cfa300ae06d94
10,531,259,824,518
bd2102f37843be1a3e9fb9ee4265618c725e7017
/toeic-core-utils/src/main/java/vn/toeiconline/core/utils/CommentBeanUtil.java
75198f49b956ef93bedf498631c998d6c50d5701
[]
no_license
traan88/example-toeic-online
https://github.com/traan88/example-toeic-online
266f9b804b3c0b60863e0ffdd8c504d567d441a7
b3cc73856f7bc6f382a7ef71627126ef20fb12bb
refs/heads/master
2020-04-04T04:54:18.035000
2018-12-04T09:56:50
2018-12-04T09:56:50
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package vn.toeiconline.core.utils; import vn.toeiconline.core.dto.CommentDTO; import vn.toeiconline.core.persistence.entity.CommentEntity; public class CommentBeanUtil { public static CommentDTO entity2Dto(CommentEntity entity) { CommentDTO dto = new CommentDTO(); dto.setCommentId(entity.getCommentId()); dto.setContent(entity.getContent()); dto.setUserDTO(new UserBeanUtil().entity2Dto(entity.getUser())); dto.setListenGuidelineDTO(new ListenGuidelineBeanUtil().entity2Dto(entity.getListenGuidelineEntity())); dto.setCreatedDate(entity.getCreatedDate()); return dto; } public static CommentEntity dto2Entity(CommentDTO dto) { CommentEntity entity = new CommentEntity(); entity.setCommentId(dto.getCommentId()); entity.setContent(dto.getContent()); entity.setUser(new UserBeanUtil().dto2Entity(dto.getUserDTO())); entity.setListenGuidelineEntity(new ListenGuidelineBeanUtil().dto2Entity(dto.getListenGuidelineDTO())); entity.setCreatedDate(dto.getCreatedDate()); return entity; } }
UTF-8
Java
1,113
java
CommentBeanUtil.java
Java
[]
null
[]
package vn.toeiconline.core.utils; import vn.toeiconline.core.dto.CommentDTO; import vn.toeiconline.core.persistence.entity.CommentEntity; public class CommentBeanUtil { public static CommentDTO entity2Dto(CommentEntity entity) { CommentDTO dto = new CommentDTO(); dto.setCommentId(entity.getCommentId()); dto.setContent(entity.getContent()); dto.setUserDTO(new UserBeanUtil().entity2Dto(entity.getUser())); dto.setListenGuidelineDTO(new ListenGuidelineBeanUtil().entity2Dto(entity.getListenGuidelineEntity())); dto.setCreatedDate(entity.getCreatedDate()); return dto; } public static CommentEntity dto2Entity(CommentDTO dto) { CommentEntity entity = new CommentEntity(); entity.setCommentId(dto.getCommentId()); entity.setContent(dto.getContent()); entity.setUser(new UserBeanUtil().dto2Entity(dto.getUserDTO())); entity.setListenGuidelineEntity(new ListenGuidelineBeanUtil().dto2Entity(dto.getListenGuidelineDTO())); entity.setCreatedDate(dto.getCreatedDate()); return entity; } }
1,113
0.72327
0.71788
25
43.52
29.528454
111
false
false
0
0
0
0
0
0
0.68
false
false
14
9f6932815ab03bf79e57b46fea1e4af985483dd7
11,003,706,224,390
eaa1fbb7ac58caab6978e95cddce98ca23cab9b4
/components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/importexport/utils/APIProductExportUtil.java
e4a82888fdc04d08ce73497d2ee45a367114fd2b
[ "Apache-2.0" ]
permissive
dushaniw/carbon-apimgt
https://github.com/dushaniw/carbon-apimgt
e5034e18f685759137f54e2b975d61761580518b
f0e313c5e82e76068cf9f03d36f077bff44ef7df
refs/heads/api-history-2
2023-08-04T15:11:54.824000
2021-01-18T08:10:11
2021-01-18T08:10:11
132,562,145
1
0
Apache-2.0
true
2021-06-29T23:15:31
2018-05-08T06:08:07
2021-01-19T06:41:20
2021-06-29T23:15:28
510,117
0
0
16
Java
false
false
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.apimgt.impl.importexport.utils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIProvider; import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.APIProduct; import org.wso2.carbon.apimgt.api.model.APIProductIdentifier; import org.wso2.carbon.apimgt.api.model.APIProductResource; import org.wso2.carbon.apimgt.api.model.ApiTypeWrapper; import org.wso2.carbon.apimgt.api.model.Documentation; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.definitions.OASParserUtil; import org.wso2.carbon.apimgt.impl.importexport.APIImportExportConstants; import org.wso2.carbon.apimgt.impl.importexport.APIImportExportException; import org.wso2.carbon.apimgt.impl.importexport.ExportFormat; import org.wso2.carbon.apimgt.impl.importexport.APIImportExportManager; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.registry.api.Registry; import org.wso2.carbon.registry.api.RegistryException; import org.wso2.carbon.registry.core.session.UserRegistry; import java.io.File; import java.io.IOException; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * This is the util class which consists of all the functions for exporting API Product. */ public class APIProductExportUtil { private static final Log log = LogFactory.getLog(APIProductExportUtil.class); private APIProductExportUtil() { } /** * This method retrieves all meta information and registry resources required for an API Product to * recreate. * * @param archiveBasePath temp location to save the API Product artifacts * @param apiProductToReturn Exporting API Product * @param userName User name of the requester * @param provider API Product Provider * @param exportFormat Export format of the API Product meta data, could be yaml or json * @param isStatusPreserved Whether API Product status is preserved while export * @throws APIImportExportException If an error occurs while retrieving API Product related resources */ public static void retrieveApiProductToExport(String archiveBasePath, APIProduct apiProductToReturn, APIProvider provider, String userName, boolean isStatusPreserved, ExportFormat exportFormat) throws APIImportExportException { UserRegistry registry; APIProductIdentifier apiProductIdentifier = apiProductToReturn.getId(); String archivePath = archiveBasePath.concat(File.separator + apiProductIdentifier.getName() + "-" + apiProductIdentifier.getVersion()); int tenantId = APIUtil.getTenantId(userName); try { registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(tenantId); // Directory creation CommonUtil.createDirectory(archivePath); // Export thumbnail exportAPIProductThumbnail(archivePath, apiProductIdentifier, registry); // Export documents List<Documentation> docList = provider.getAllDocumentation(apiProductIdentifier); if (!docList.isEmpty()) { exportAPIProductDocumentation(archivePath, docList, apiProductIdentifier, registry, exportFormat); } else if (log.isDebugEnabled()) { log.debug("No documentation found for API Product: " + apiProductIdentifier + ". Skipping API Product documentation export."); } // Export meta information exportAPIProductMetaInformation(archivePath, apiProductToReturn, registry, exportFormat, provider); // Export dependent APIs exportDependentAPIs(archivePath, apiProductToReturn, exportFormat, provider, userName, isStatusPreserved); // Export mTLS authentication related certificates if(provider.isClientCertificateBasedAuthenticationConfigured()) { if (log.isDebugEnabled()) { log.debug("Mutual SSL enabled. Exporting client certificates."); } ApiTypeWrapper apiTypeWrapper = new ApiTypeWrapper(apiProductToReturn); APIAndAPIProductCommonUtil.exportClientCertificates(archivePath, apiTypeWrapper, tenantId, provider, exportFormat); } } catch (APIManagementException e) { String errorMessage = "Unable to retrieve artifacts for API Product: " + apiProductIdentifier.getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + " : " + apiProductIdentifier.getVersion(); throw new APIImportExportException(errorMessage, e); } catch (RegistryException e) { String errorMessage = "Error while getting governance registry for tenant: " + tenantId; throw new APIImportExportException(errorMessage, e); } } /** * Export dependent APIs by checking the resources of the API Product. * * @param archivePath Temp location to save the API artifacts * @param apiProductToReturn API Product which the resources should be considered * @param userName User name of the requester * @param provider API Product Provider * @param exportFormat Export format of the API meta data, could be yaml or json * @param isStatusPreserved Whether API status is preserved while export * @throws APIImportExportException If an error occurs while retrieving API related resources */ private static void exportDependentAPIs(String archivePath, APIProduct apiProductToReturn, ExportFormat exportFormat, APIProvider provider, String userName, Boolean isStatusPreserved) throws APIImportExportException, APIManagementException { String apisDirectoryPath = archivePath + File.separator + APIImportExportConstants.APIS_DIRECTORY; CommonUtil.createDirectory(apisDirectoryPath); List<APIProductResource> apiProductResources = apiProductToReturn.getProductResources(); for (APIProductResource apiProductResource : apiProductResources) { APIIdentifier apiIdentifier = apiProductResource.getApiIdentifier(); API api = provider.getAPI(apiIdentifier); APIExportUtil.retrieveApiToExport(apisDirectoryPath, api, provider, userName, isStatusPreserved, exportFormat); } } /** * Retrieve thumbnail image for the exporting API Product and store it in the archive directory. * * @param apiProductIdentifier ID of the requesting API Product * @param registry Current tenant registry * @throws APIImportExportException If an error occurs while retrieving image from the registry or * storing in the archive directory */ private static void exportAPIProductThumbnail(String archivePath, APIProductIdentifier apiProductIdentifier, Registry registry) throws APIImportExportException { APIAndAPIProductCommonUtil.exportAPIOrAPIProductThumbnail(archivePath, apiProductIdentifier, registry); } /** * Retrieve documentation for the exporting API Product and store it in the archive directory. * FILE, INLINE, MARKDOWN and URL documentations are handled. * * @param apiProductIdentifier ID of the requesting API Product * @param registry Current tenant registry * @param docList Documentation list of the exporting API Product * @param exportFormat Format for export * @throws APIImportExportException If an error occurs while retrieving documents from the * registry or storing in the archive directory */ private static void exportAPIProductDocumentation(String archivePath, List<Documentation> docList, APIProductIdentifier apiProductIdentifier, Registry registry, ExportFormat exportFormat) throws APIImportExportException { APIAndAPIProductCommonUtil.exportAPIOrAPIProductDocumentation(archivePath, docList, apiProductIdentifier, registry, exportFormat); } /** * Retrieve meta information of the API Product to export. * URL template information are stored in swagger.json definition while rest of the required * data are in api.json * * @param apiProductToReturn API Product to be exported * @param registry Current tenant registry * @param exportFormat Export format of file * @param apiProvider API Product Provider * @throws APIImportExportException If an error occurs while exporting meta information * @throws APIManagementException If an error occurs while removing unnecessary data from exported API Product * or while retrieving Swagger definition for API Product */ private static void exportAPIProductMetaInformation(String archivePath, APIProduct apiProductToReturn, Registry registry, ExportFormat exportFormat, APIProvider apiProvider) throws APIImportExportException, APIManagementException { CommonUtil.createDirectory(archivePath + File.separator + APIImportExportConstants.META_INFO_DIRECTORY); // Remove unnecessary data from exported API Product cleanApiProductDataToExport(apiProductToReturn); // Get only the subscription tier names of the API, rather than retrieving the whole object array ApiTypeWrapper apiTypeWrapper = new ApiTypeWrapper(apiProductToReturn); Set<String> availableSubscriptionTierNames = APIAndAPIProductCommonUtil.getAvailableTierNames(apiTypeWrapper); try { Gson gson = new GsonBuilder().setPrettyPrinting().create(); // Swagger.json contains complete details about scopes. Therefore scope details and uri templates // are removed from api.json. apiProductToReturn.setScopes(new LinkedHashSet<>()); String swaggerDefinition = OASParserUtil.getAPIDefinition(apiProductToReturn.getId(), registry); JsonParser parser = new JsonParser(); JsonObject json = parser.parse(swaggerDefinition).getAsJsonObject(); String formattedSwaggerJson = gson.toJson(json); switch (exportFormat) { case YAML: String swaggerInYaml = CommonUtil.jsonToYaml(formattedSwaggerJson); CommonUtil.writeFile(archivePath + APIImportExportConstants.YAML_SWAGGER_DEFINITION_LOCATION, swaggerInYaml); break; case JSON: CommonUtil.writeFile(archivePath + APIImportExportConstants.JSON_SWAGGER_DEFINITION_LOCATION, formattedSwaggerJson); } if (log.isDebugEnabled()) { log.debug("Meta information retrieved successfully for API Product: " + apiProductToReturn.getId().getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + apiProductToReturn.getId().getVersion()); } String apiInJson = gson.toJson(apiProductToReturn); JSONParser jsonParser = new JSONParser(); org.json.simple.JSONObject apiJsonObject = (org.json.simple.JSONObject) jsonParser.parse(apiInJson); apiJsonObject.remove(APIConstants.SUBSCRIPTION_TIERS); apiJsonObject.put(APIConstants.SUBSCRIPTION_TIERS, availableSubscriptionTierNames); apiInJson = gson.toJson(apiJsonObject); switch (exportFormat) { case JSON: CommonUtil.writeFile(archivePath + APIImportExportConstants.JSON_API_FILE_LOCATION, apiInJson); break; case YAML: String apiInYaml = CommonUtil.jsonToYaml(apiInJson); CommonUtil.writeFile(archivePath + APIImportExportConstants.YAML_API_FILE_LOCATION, apiInYaml); break; } } catch (APIManagementException e) { String errorMessage = "Error while retrieving Swagger definition for API Product: " + apiProductToReturn.getId().getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + apiProductToReturn.getId().getVersion(); throw new APIImportExportException(errorMessage, e); } catch (IOException e) { String errorMessage = "Error while retrieving saving as YAML for API Product: " + apiProductToReturn.getId().getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + apiProductToReturn.getId().getVersion(); throw new APIImportExportException(errorMessage, e); } catch (ParseException e) { String msg = "ParseException thrown when parsing API Product config"; throw new APIManagementException(msg, e); } } /** * Clean API Product by removing unnecessary details. * * @param apiProduct API Product to be exported */ private static void cleanApiProductDataToExport(APIProduct apiProduct) { // Thumbnail will be set according to the importing environment. Therefore current URL is removed apiProduct.setThumbnailUrl(null); } /** * Exports an API Product from API Manager for a given API Product ID. Meta information, API icon, documentation, client certificates * and dependent APIs are exported. This service generates a zipped archive which contains all the above mentioned * resources for a given API Product. * * @param apiProvider API provider * @param apiProductIdentifier ID of the requesting API Product * @param userName User name of the user * @param preserveStatus Preserve API status on export * @return Zipped file containing exported API Product * @throws APIImportExportException If an error occurs while exporting the API Product and creating the archive * @throws APIManagementException If an error occurs while retrieving the API Product */ public static File exportApiProduct(APIProvider apiProvider, APIProductIdentifier apiProductIdentifier, String userName, ExportFormat exportFormat, Boolean preserveStatus) throws APIImportExportException, APIManagementException { APIProduct apiProduct; APIImportExportManager apiImportExportManager; boolean isStatusPreserved = preserveStatus == null || preserveStatus; apiProduct = apiProvider.getAPIProduct(apiProductIdentifier); ApiTypeWrapper apiTypeWrapper = new ApiTypeWrapper(apiProduct); apiImportExportManager = new APIImportExportManager(apiProvider, userName); return apiImportExportManager.exportAPIOrAPIProductArchive(apiTypeWrapper, isStatusPreserved, exportFormat); } }
UTF-8
Java
16,415
java
APIProductExportUtil.java
Java
[ { "context": "h the resources should be considered\n * @param userName User name of the requester\n ", "end": 6462, "score": 0.44055917859077454, "start": 6454, "tag": "NAME", "value": "userName" }, { "context": "considered\n * @param userName User name of the requester\n * @param provider API Produ", "end": 6506, "score": 0.9048397541046143, "start": 6480, "tag": "NAME", "value": "User name of the requester" }, { "context": "er ID of the requesting API Product\n * @param userName User name of the user\n * @param ", "end": 15246, "score": 0.9268858432769775, "start": 15238, "tag": "USERNAME", "value": "userName" }, { "context": "ng API Product\n * @param userName User name of the user\n * @param preserveStatus Preserve API ", "end": 15281, "score": 0.9965968132019043, "start": 15260, "tag": "USERNAME", "value": "User name of the user" }, { "context": " APIProductIdentifier apiProductIdentifier, String userName,\n ExportFormat ex", "end": 15744, "score": 0.7683417201042175, "start": 15736, "tag": "USERNAME", "value": "userName" }, { "context": "tManager = new APIImportExportManager(apiProvider, userName);\n return apiImportExportManager.exportAPI", "end": 16287, "score": 0.9463032484054565, "start": 16279, "tag": "USERNAME", "value": "userName" } ]
null
[]
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.apimgt.impl.importexport.utils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIProvider; import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.APIProduct; import org.wso2.carbon.apimgt.api.model.APIProductIdentifier; import org.wso2.carbon.apimgt.api.model.APIProductResource; import org.wso2.carbon.apimgt.api.model.ApiTypeWrapper; import org.wso2.carbon.apimgt.api.model.Documentation; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.definitions.OASParserUtil; import org.wso2.carbon.apimgt.impl.importexport.APIImportExportConstants; import org.wso2.carbon.apimgt.impl.importexport.APIImportExportException; import org.wso2.carbon.apimgt.impl.importexport.ExportFormat; import org.wso2.carbon.apimgt.impl.importexport.APIImportExportManager; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.registry.api.Registry; import org.wso2.carbon.registry.api.RegistryException; import org.wso2.carbon.registry.core.session.UserRegistry; import java.io.File; import java.io.IOException; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * This is the util class which consists of all the functions for exporting API Product. */ public class APIProductExportUtil { private static final Log log = LogFactory.getLog(APIProductExportUtil.class); private APIProductExportUtil() { } /** * This method retrieves all meta information and registry resources required for an API Product to * recreate. * * @param archiveBasePath temp location to save the API Product artifacts * @param apiProductToReturn Exporting API Product * @param userName User name of the requester * @param provider API Product Provider * @param exportFormat Export format of the API Product meta data, could be yaml or json * @param isStatusPreserved Whether API Product status is preserved while export * @throws APIImportExportException If an error occurs while retrieving API Product related resources */ public static void retrieveApiProductToExport(String archiveBasePath, APIProduct apiProductToReturn, APIProvider provider, String userName, boolean isStatusPreserved, ExportFormat exportFormat) throws APIImportExportException { UserRegistry registry; APIProductIdentifier apiProductIdentifier = apiProductToReturn.getId(); String archivePath = archiveBasePath.concat(File.separator + apiProductIdentifier.getName() + "-" + apiProductIdentifier.getVersion()); int tenantId = APIUtil.getTenantId(userName); try { registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(tenantId); // Directory creation CommonUtil.createDirectory(archivePath); // Export thumbnail exportAPIProductThumbnail(archivePath, apiProductIdentifier, registry); // Export documents List<Documentation> docList = provider.getAllDocumentation(apiProductIdentifier); if (!docList.isEmpty()) { exportAPIProductDocumentation(archivePath, docList, apiProductIdentifier, registry, exportFormat); } else if (log.isDebugEnabled()) { log.debug("No documentation found for API Product: " + apiProductIdentifier + ". Skipping API Product documentation export."); } // Export meta information exportAPIProductMetaInformation(archivePath, apiProductToReturn, registry, exportFormat, provider); // Export dependent APIs exportDependentAPIs(archivePath, apiProductToReturn, exportFormat, provider, userName, isStatusPreserved); // Export mTLS authentication related certificates if(provider.isClientCertificateBasedAuthenticationConfigured()) { if (log.isDebugEnabled()) { log.debug("Mutual SSL enabled. Exporting client certificates."); } ApiTypeWrapper apiTypeWrapper = new ApiTypeWrapper(apiProductToReturn); APIAndAPIProductCommonUtil.exportClientCertificates(archivePath, apiTypeWrapper, tenantId, provider, exportFormat); } } catch (APIManagementException e) { String errorMessage = "Unable to retrieve artifacts for API Product: " + apiProductIdentifier.getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + " : " + apiProductIdentifier.getVersion(); throw new APIImportExportException(errorMessage, e); } catch (RegistryException e) { String errorMessage = "Error while getting governance registry for tenant: " + tenantId; throw new APIImportExportException(errorMessage, e); } } /** * Export dependent APIs by checking the resources of the API Product. * * @param archivePath Temp location to save the API artifacts * @param apiProductToReturn API Product which the resources should be considered * @param userName <NAME> * @param provider API Product Provider * @param exportFormat Export format of the API meta data, could be yaml or json * @param isStatusPreserved Whether API status is preserved while export * @throws APIImportExportException If an error occurs while retrieving API related resources */ private static void exportDependentAPIs(String archivePath, APIProduct apiProductToReturn, ExportFormat exportFormat, APIProvider provider, String userName, Boolean isStatusPreserved) throws APIImportExportException, APIManagementException { String apisDirectoryPath = archivePath + File.separator + APIImportExportConstants.APIS_DIRECTORY; CommonUtil.createDirectory(apisDirectoryPath); List<APIProductResource> apiProductResources = apiProductToReturn.getProductResources(); for (APIProductResource apiProductResource : apiProductResources) { APIIdentifier apiIdentifier = apiProductResource.getApiIdentifier(); API api = provider.getAPI(apiIdentifier); APIExportUtil.retrieveApiToExport(apisDirectoryPath, api, provider, userName, isStatusPreserved, exportFormat); } } /** * Retrieve thumbnail image for the exporting API Product and store it in the archive directory. * * @param apiProductIdentifier ID of the requesting API Product * @param registry Current tenant registry * @throws APIImportExportException If an error occurs while retrieving image from the registry or * storing in the archive directory */ private static void exportAPIProductThumbnail(String archivePath, APIProductIdentifier apiProductIdentifier, Registry registry) throws APIImportExportException { APIAndAPIProductCommonUtil.exportAPIOrAPIProductThumbnail(archivePath, apiProductIdentifier, registry); } /** * Retrieve documentation for the exporting API Product and store it in the archive directory. * FILE, INLINE, MARKDOWN and URL documentations are handled. * * @param apiProductIdentifier ID of the requesting API Product * @param registry Current tenant registry * @param docList Documentation list of the exporting API Product * @param exportFormat Format for export * @throws APIImportExportException If an error occurs while retrieving documents from the * registry or storing in the archive directory */ private static void exportAPIProductDocumentation(String archivePath, List<Documentation> docList, APIProductIdentifier apiProductIdentifier, Registry registry, ExportFormat exportFormat) throws APIImportExportException { APIAndAPIProductCommonUtil.exportAPIOrAPIProductDocumentation(archivePath, docList, apiProductIdentifier, registry, exportFormat); } /** * Retrieve meta information of the API Product to export. * URL template information are stored in swagger.json definition while rest of the required * data are in api.json * * @param apiProductToReturn API Product to be exported * @param registry Current tenant registry * @param exportFormat Export format of file * @param apiProvider API Product Provider * @throws APIImportExportException If an error occurs while exporting meta information * @throws APIManagementException If an error occurs while removing unnecessary data from exported API Product * or while retrieving Swagger definition for API Product */ private static void exportAPIProductMetaInformation(String archivePath, APIProduct apiProductToReturn, Registry registry, ExportFormat exportFormat, APIProvider apiProvider) throws APIImportExportException, APIManagementException { CommonUtil.createDirectory(archivePath + File.separator + APIImportExportConstants.META_INFO_DIRECTORY); // Remove unnecessary data from exported API Product cleanApiProductDataToExport(apiProductToReturn); // Get only the subscription tier names of the API, rather than retrieving the whole object array ApiTypeWrapper apiTypeWrapper = new ApiTypeWrapper(apiProductToReturn); Set<String> availableSubscriptionTierNames = APIAndAPIProductCommonUtil.getAvailableTierNames(apiTypeWrapper); try { Gson gson = new GsonBuilder().setPrettyPrinting().create(); // Swagger.json contains complete details about scopes. Therefore scope details and uri templates // are removed from api.json. apiProductToReturn.setScopes(new LinkedHashSet<>()); String swaggerDefinition = OASParserUtil.getAPIDefinition(apiProductToReturn.getId(), registry); JsonParser parser = new JsonParser(); JsonObject json = parser.parse(swaggerDefinition).getAsJsonObject(); String formattedSwaggerJson = gson.toJson(json); switch (exportFormat) { case YAML: String swaggerInYaml = CommonUtil.jsonToYaml(formattedSwaggerJson); CommonUtil.writeFile(archivePath + APIImportExportConstants.YAML_SWAGGER_DEFINITION_LOCATION, swaggerInYaml); break; case JSON: CommonUtil.writeFile(archivePath + APIImportExportConstants.JSON_SWAGGER_DEFINITION_LOCATION, formattedSwaggerJson); } if (log.isDebugEnabled()) { log.debug("Meta information retrieved successfully for API Product: " + apiProductToReturn.getId().getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + apiProductToReturn.getId().getVersion()); } String apiInJson = gson.toJson(apiProductToReturn); JSONParser jsonParser = new JSONParser(); org.json.simple.JSONObject apiJsonObject = (org.json.simple.JSONObject) jsonParser.parse(apiInJson); apiJsonObject.remove(APIConstants.SUBSCRIPTION_TIERS); apiJsonObject.put(APIConstants.SUBSCRIPTION_TIERS, availableSubscriptionTierNames); apiInJson = gson.toJson(apiJsonObject); switch (exportFormat) { case JSON: CommonUtil.writeFile(archivePath + APIImportExportConstants.JSON_API_FILE_LOCATION, apiInJson); break; case YAML: String apiInYaml = CommonUtil.jsonToYaml(apiInJson); CommonUtil.writeFile(archivePath + APIImportExportConstants.YAML_API_FILE_LOCATION, apiInYaml); break; } } catch (APIManagementException e) { String errorMessage = "Error while retrieving Swagger definition for API Product: " + apiProductToReturn.getId().getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + apiProductToReturn.getId().getVersion(); throw new APIImportExportException(errorMessage, e); } catch (IOException e) { String errorMessage = "Error while retrieving saving as YAML for API Product: " + apiProductToReturn.getId().getName() + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + apiProductToReturn.getId().getVersion(); throw new APIImportExportException(errorMessage, e); } catch (ParseException e) { String msg = "ParseException thrown when parsing API Product config"; throw new APIManagementException(msg, e); } } /** * Clean API Product by removing unnecessary details. * * @param apiProduct API Product to be exported */ private static void cleanApiProductDataToExport(APIProduct apiProduct) { // Thumbnail will be set according to the importing environment. Therefore current URL is removed apiProduct.setThumbnailUrl(null); } /** * Exports an API Product from API Manager for a given API Product ID. Meta information, API icon, documentation, client certificates * and dependent APIs are exported. This service generates a zipped archive which contains all the above mentioned * resources for a given API Product. * * @param apiProvider API provider * @param apiProductIdentifier ID of the requesting API Product * @param userName User name of the user * @param preserveStatus Preserve API status on export * @return Zipped file containing exported API Product * @throws APIImportExportException If an error occurs while exporting the API Product and creating the archive * @throws APIManagementException If an error occurs while retrieving the API Product */ public static File exportApiProduct(APIProvider apiProvider, APIProductIdentifier apiProductIdentifier, String userName, ExportFormat exportFormat, Boolean preserveStatus) throws APIImportExportException, APIManagementException { APIProduct apiProduct; APIImportExportManager apiImportExportManager; boolean isStatusPreserved = preserveStatus == null || preserveStatus; apiProduct = apiProvider.getAPIProduct(apiProductIdentifier); ApiTypeWrapper apiTypeWrapper = new ApiTypeWrapper(apiProduct); apiImportExportManager = new APIImportExportManager(apiProvider, userName); return apiImportExportManager.exportAPIOrAPIProductArchive(apiTypeWrapper, isStatusPreserved, exportFormat); } }
16,395
0.696132
0.694121
299
53.899666
39.46172
167
false
false
0
0
0
0
0
0
0.635451
false
false
14
91395b3110d8e47e0db3845bcab4d20563f8e8e4
33,646,773,821,326
acbaab43b3821300a4a721cf68e828b3df551788
/src/test/java/practice/StudentServiceTest.java
f2a2499a59569f53d391c9cf6dbd79cc9020e4f5
[]
no_license
crawford123/lessonthree-SpringBoot
https://github.com/crawford123/lessonthree-SpringBoot
2dfd32d668a794f88aa72f88ebe47817bbdda7dc
9db07aad64bfeb92cc66ea7493bd267dbb4565a7
refs/heads/master
2021-05-05T02:53:03.291000
2018-02-01T02:32:15
2018-02-01T02:32:15
119,771,634
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package practice; import com.paul.entity.Student; import com.paul.service.StudentService; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.*; /** * created with IntelliJ IDEA * User: FengZhi * Date: 1/20/2018 * Time: 4:47 PM * Email:2045532295@qq.com * Addres:zhbit * Description: */ public class StudentServiceTest { private static StudentService studentService; @BeforeClass public static void setup(){ studentService = new StudentService(); } @AfterClass public static void teardown(){ studentService = null; } @Test public void testFindAllStudents(){ List<Student> students = studentService.findAllStudents(); Assert.assertNotNull(students); for (Student student:students) { System.out.println(student); } } @Test public void testFindStudentById() { Student student = studentService.findStudentById(1); Assert.assertNotNull(student); System.out.println(student); } @Test public void testCreateStudent() { Student student = new Student(); int id = 3; student.setName("student_" + id); student.setEmail("student_" + id + "gmail.com"); student.setDob(new Date()); studentService.createStudent(student); Student newStudent = studentService.findStudentById(id); Assert.assertNotNull(newStudent); } }
UTF-8
Java
1,519
java
StudentServiceTest.java
Java
[ { "context": "util.*;\n/**\n * created with IntelliJ IDEA\n * User: FengZhi\n * Date: 1/20/2018\n * Time: 4:47 PM\n * Email:2", "end": 265, "score": 0.7573370933532715, "start": 261, "tag": "NAME", "value": "Feng" }, { "context": "*;\n/**\n * created with IntelliJ IDEA\n * User: FengZhi\n * Date: 1/20/2018\n * Time: 4:47 PM\n * Email:20", "end": 266, "score": 0.5217147469520569, "start": 265, "tag": "USERNAME", "value": "Z" }, { "context": ";\n/**\n * created with IntelliJ IDEA\n * User: FengZhi\n * Date: 1/20/2018\n * Time: 4:47 PM\n * Email:2045", "end": 268, "score": 0.6060658693313599, "start": 266, "tag": "NAME", "value": "hi" }, { "context": "gZhi\n * Date: 1/20/2018\n * Time: 4:47 PM\n * Email:2045532295@qq.com\n * Addres:zhbit\n * Description:\n */\npublic class ", "end": 331, "score": 0.9998193383216858, "start": 314, "tag": "EMAIL", "value": "2045532295@qq.com" } ]
null
[]
package practice; import com.paul.entity.Student; import com.paul.service.StudentService; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.util.*; /** * created with IntelliJ IDEA * User: FengZhi * Date: 1/20/2018 * Time: 4:47 PM * Email:<EMAIL> * Addres:zhbit * Description: */ public class StudentServiceTest { private static StudentService studentService; @BeforeClass public static void setup(){ studentService = new StudentService(); } @AfterClass public static void teardown(){ studentService = null; } @Test public void testFindAllStudents(){ List<Student> students = studentService.findAllStudents(); Assert.assertNotNull(students); for (Student student:students) { System.out.println(student); } } @Test public void testFindStudentById() { Student student = studentService.findStudentById(1); Assert.assertNotNull(student); System.out.println(student); } @Test public void testCreateStudent() { Student student = new Student(); int id = 3; student.setName("student_" + id); student.setEmail("student_" + id + "gmail.com"); student.setDob(new Date()); studentService.createStudent(student); Student newStudent = studentService.findStudentById(id); Assert.assertNotNull(newStudent); } }
1,509
0.649111
0.634628
64
22.734375
17.914068
66
false
false
0
0
0
0
0
0
0.390625
false
false
14
5115f7e6b7a0858159ac14fcfecf52a9153a6cc2
31,327,491,457,397
0aefc430e759fa316ebf4d0c624a79077a60ac4e
/Wanpu_Demo_dex2jar_cfr/cn/waps/cj.java
41d80195ef8296c5ba610bf696feed95381ec9c0
[]
no_license
RyanTech/Wanpu
https://github.com/RyanTech/Wanpu
f27864b817a8e0cd3a6503cc57721857a49b9c8c
5d65afd0ed362da70628aa51588ba354869d5678
refs/heads/master
2018-01-15T13:10:11.800000
2014-12-18T08:42:22
2014-12-18T08:42:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * Decompiled with CFR 0_79. */ package cn.waps; import cn.waps.AdInfo; import cn.waps.bu; import cn.waps.ck; class cj implements Runnable { AdInfo a; final /* synthetic */ bu b; cj(bu bu, AdInfo adInfo) { this.b = bu; this.a = adInfo; } public void run() { new ck(this).start(); } }
UTF-8
Java
341
java
cj.java
Java
[]
null
[]
/* * Decompiled with CFR 0_79. */ package cn.waps; import cn.waps.AdInfo; import cn.waps.bu; import cn.waps.ck; class cj implements Runnable { AdInfo a; final /* synthetic */ bu b; cj(bu bu, AdInfo adInfo) { this.b = bu; this.a = adInfo; } public void run() { new ck(this).start(); } }
341
0.560117
0.55132
23
13.782609
10.930438
31
false
false
0
0
0
0
0
0
0.434783
false
false
14
55c70157d8dcd75bc39dad6c47ac90c5c3e432ef
31,327,491,457,483
ade8f911e9ac2a22566b7fbcb31bae0913716d1b
/Robot.java
fe041a24ca4a7c52e0c20e84ba8b7a0567f4d76b
[]
no_license
prezydium/iSA-second-weekend-exercises
https://github.com/prezydium/iSA-second-weekend-exercises
68ae43ea56dbb4013c491cf0eb64fb4ca89cadeb
8a8b4dde71bb7d2673e90dba12074e539d0e0a22
refs/heads/master
2021-05-08T14:27:51.042000
2018-02-05T06:47:16
2018-02-05T06:47:16
120,086,863
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Robot { private List<String> wordList = new ArrayList<String>(Arrays.asList("thank", "you", "for", "teaching", "me", "i", "already", "know", "the", "word", "do", "not", "understand", "input")); private Pattern pattern = Pattern.compile("[a-z]+"); private boolean checkRepeating(String s){ for(int i =0; i<wordList.size(); i++){ if (wordList.get(i).equals(s)){ return true; } } return false; } public String learnWord(String word) { String wordtolearn = word.toLowerCase(); Matcher matcher = pattern.matcher(wordtolearn); if (!matcher.matches()) { return "I do not understand the input"; } else if (checkRepeating(wordtolearn)) { return "I already know the word " + word; } else { wordList.add(wordtolearn); return "Thank you for teaching me " + word; } } }
UTF-8
Java
1,098
java
Robot.java
Java
[]
null
[]
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Robot { private List<String> wordList = new ArrayList<String>(Arrays.asList("thank", "you", "for", "teaching", "me", "i", "already", "know", "the", "word", "do", "not", "understand", "input")); private Pattern pattern = Pattern.compile("[a-z]+"); private boolean checkRepeating(String s){ for(int i =0; i<wordList.size(); i++){ if (wordList.get(i).equals(s)){ return true; } } return false; } public String learnWord(String word) { String wordtolearn = word.toLowerCase(); Matcher matcher = pattern.matcher(wordtolearn); if (!matcher.matches()) { return "I do not understand the input"; } else if (checkRepeating(wordtolearn)) { return "I already know the word " + word; } else { wordList.add(wordtolearn); return "Thank you for teaching me " + word; } } }
1,098
0.587432
0.586521
33
32.272728
33.444908
189
false
false
0
0
0
0
0
0
0.909091
false
false
14
1d2f7cd441ce310a09efc8e77b79382fb65d80a8
3,109,556,346,308
705994c37940413616a4866ea2fa0608e6d014b1
/src/main/java/com/app/main/dao/WinnerDAO.java
c4dbf13849d316cadbb506c960d867f9b36c5234
[]
no_license
gr1sha/teller-machine
https://github.com/gr1sha/teller-machine
f17c8d00667abeda25069d42615170340885cda3
83be737a3ac803d79e3d0a6dd8ea4e6fe56444be
refs/heads/master
2016-09-16T13:25:21.177000
2014-10-22T18:55:28
2014-10-22T18:55:28
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.app.main.dao; import com.app.main.iWinnerDAO; public class WinnerDAO implements iWinnerDAO { private Integer winner = 1; public Integer getWinner() { return winner; } public void setWinner(Integer winner) { this.winner = winner; } }
UTF-8
Java
258
java
WinnerDAO.java
Java
[]
null
[]
package com.app.main.dao; import com.app.main.iWinnerDAO; public class WinnerDAO implements iWinnerDAO { private Integer winner = 1; public Integer getWinner() { return winner; } public void setWinner(Integer winner) { this.winner = winner; } }
258
0.732558
0.728682
13
18.846153
15.60496
46
false
false
0
0
0
0
0
0
1.153846
false
false
14
b4f25be4f6756bc191dab506a2d78c91cd306f40
18,580,028,548,303
cf8fd42e927a0f016b99e3daf8b1ce4bc122ead1
/Algorithms/src/miscellaneous/BinarySearch.java
ec65315770bf92a21c9d77bea0dbb8efdef7a143
[]
no_license
amitsaroj001/Algorithm_DS_Exercise
https://github.com/amitsaroj001/Algorithm_DS_Exercise
e934a40d059c51d938532fe4a125b6adba56fb45
d1574e00f7a6908e1d4801b2368aa870e40f1f1a
refs/heads/master
2021-01-24T09:39:34.052000
2016-10-11T13:40:23
2016-10-11T13:40:23
69,525,909
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package miscellaneous; import java.util.Scanner; /** * Name : Amit Saroj * Topic : miscellaneous * Subtopic : BinarySearch.java * Complexity : Log n */ public class BinarySearch { public static void main(String[] args) { Scanner n = new Scanner(System.in); System.out.println("Enter the size of Array"); int size = n.nextInt(); System.out.println(); int[] arr = new int[size]; for(int i=0; i<arr.length; i++){ arr[i] = n.nextInt(); } System.out.println(); System.out.println("Enter the element to search in the element"); int element = n.nextInt(); System.out.println(); //Binary Search int max = size -1; int min = 0; int midpoint = (max+min)/2; while(min <= max){ if(arr[midpoint] == element){ System.out.println("Element is present at "+(midpoint+1)+ " position."); break; } else{ if(arr[midpoint]<element){ min = midpoint + 1; midpoint = (max+min)/2; } else{ max = midpoint -1; midpoint = (max+min)/2; } } } if(min>max){ System.out.println("Element not present"); } } }
UTF-8
Java
1,106
java
BinarySearch.java
Java
[ { "context": "neous;\n\nimport java.util.Scanner;\n\n/**\n * Name \t: Amit Saroj\n * Topic \t: miscellaneous\n * Subtopic : BinarySea", "end": 77, "score": 0.9997992515563965, "start": 67, "tag": "NAME", "value": "Amit Saroj" } ]
null
[]
package miscellaneous; import java.util.Scanner; /** * Name : <NAME> * Topic : miscellaneous * Subtopic : BinarySearch.java * Complexity : Log n */ public class BinarySearch { public static void main(String[] args) { Scanner n = new Scanner(System.in); System.out.println("Enter the size of Array"); int size = n.nextInt(); System.out.println(); int[] arr = new int[size]; for(int i=0; i<arr.length; i++){ arr[i] = n.nextInt(); } System.out.println(); System.out.println("Enter the element to search in the element"); int element = n.nextInt(); System.out.println(); //Binary Search int max = size -1; int min = 0; int midpoint = (max+min)/2; while(min <= max){ if(arr[midpoint] == element){ System.out.println("Element is present at "+(midpoint+1)+ " position."); break; } else{ if(arr[midpoint]<element){ min = midpoint + 1; midpoint = (max+min)/2; } else{ max = midpoint -1; midpoint = (max+min)/2; } } } if(min>max){ System.out.println("Element not present"); } } }
1,102
0.597649
0.589512
56
18.75
16.448242
76
false
false
0
0
0
0
0
0
2.517857
false
false
14
6dfd84fd26bcdefe78fde51457fea1ac9967dc2a
24,713,241,847,367
91cd26d5795a3da886a6fd8a924aae1ea32ef52e
/src/main/java/BotFeaturesCodes/testRunBotFeatures.java
a94e0955c907b933324aa34f4ef820781fd89d43
[]
no_license
AryanGitHub/Tercord
https://github.com/AryanGitHub/Tercord
34d7a08324550c67ff95cc63d203a273b245a042
409c8459a20d1635c8dc4a5cda0ccf83a7ad0a20
refs/heads/main
2023-08-28T05:54:27.264000
2021-10-30T03:38:15
2021-10-30T03:38:15
418,938,208
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package BotFeaturesCodes; public class testRunBotFeatures { public static void main(String[] args) { String code = "```c\r\n" + "#include <stdio.h>\r\n" + "\r\n" + "int main (){\r\n" + "\r\n" + "printf(\"%d\",-6/7);\r\n" + "}\r\n" + "```"; System.out.println(CProgramRunner.getCCodeFromArguments(code)); } }
UTF-8
Java
365
java
testRunBotFeatures.java
Java
[]
null
[]
package BotFeaturesCodes; public class testRunBotFeatures { public static void main(String[] args) { String code = "```c\r\n" + "#include <stdio.h>\r\n" + "\r\n" + "int main (){\r\n" + "\r\n" + "printf(\"%d\",-6/7);\r\n" + "}\r\n" + "```"; System.out.println(CProgramRunner.getCCodeFromArguments(code)); } }
365
0.523288
0.517808
18
18.277779
17.387114
65
false
false
0
0
0
0
0
0
2.166667
false
false
14
dd1b098c97f1027b998aa75cd6afcc233e4143b5
2,765,958,979,109
19f7e40c448029530d191a262e5215571382bf9f
/decompiled/instagram/sources/com/fasterxml/jackson/databind/ser/impl/IndexedListSerializer.java
366f8bf0386b07c75c429d5fd7258f6105d2f4b4
[]
no_license
stanvanrooy/decompiled-instagram
https://github.com/stanvanrooy/decompiled-instagram
c1fb553c52e98fd82784a3a8a17abab43b0f52eb
3091a40af7accf6c0a80b9dda608471d503c4d78
refs/heads/master
2022-12-07T22:31:43.155000
2020-08-26T03:42:04
2020-08-26T03:42:04
283,347,288
18
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.fasterxml.jackson.databind.ser.impl; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.annotation.JacksonStdImpl; import com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase; import java.util.List; import p000X.C0L; import p000X.C27148BzD; import p000X.C27204C1t; @JacksonStdImpl public final class IndexedListSerializer extends AsArraySerializerBase { public IndexedListSerializer(C0L c0l, boolean z, C27204C1t c1t, C27148BzD bzD, JsonSerializer jsonSerializer) { super(List.class, c0l, z, c1t, bzD, jsonSerializer); } public IndexedListSerializer(IndexedListSerializer indexedListSerializer, C27148BzD bzD, C27204C1t c1t, JsonSerializer jsonSerializer) { super(indexedListSerializer, bzD, c1t, jsonSerializer); } }
UTF-8
Java
814
java
IndexedListSerializer.java
Java
[]
null
[]
package com.fasterxml.jackson.databind.ser.impl; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.annotation.JacksonStdImpl; import com.fasterxml.jackson.databind.ser.std.AsArraySerializerBase; import java.util.List; import p000X.C0L; import p000X.C27148BzD; import p000X.C27204C1t; @JacksonStdImpl public final class IndexedListSerializer extends AsArraySerializerBase { public IndexedListSerializer(C0L c0l, boolean z, C27204C1t c1t, C27148BzD bzD, JsonSerializer jsonSerializer) { super(List.class, c0l, z, c1t, bzD, jsonSerializer); } public IndexedListSerializer(IndexedListSerializer indexedListSerializer, C27148BzD bzD, C27204C1t c1t, JsonSerializer jsonSerializer) { super(indexedListSerializer, bzD, c1t, jsonSerializer); } }
814
0.80344
0.742015
20
39.700001
38.727379
140
false
false
0
0
0
0
0
0
1.25
false
false
14
0d16490d3ed2c2ec2e3a8b82e9559ddeaad352d9
26,079,041,449,740
6fe337c746a075fe28b958537039f9870daa14ab
/src/checkers/classes/FieldViewControl.java
f2221ed8f142c09cb0abca0ba00ee67c2e3443f1
[]
no_license
Shhatter/Checkers_CS_CLI
https://github.com/Shhatter/Checkers_CS_CLI
fae20d6151b07e2913ce595491272dbc47849863
f11e96020abeec0252903697691de0ec923b1148
refs/heads/master
2021-01-24T06:56:05.110000
2017-07-09T20:56:46
2017-07-09T20:56:46
93,327,508
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package checkers.classes; import checkers.enums.PawnColor; import javafx.scene.image.ImageView; import javafx.scene.layout.StackPane; public class FieldViewControl { StackPane gridField; int n; int m; ImageView viewedImage; PawnColor pawnColor; public FieldViewControl(StackPane gridField, int n, int m, PawnColor pawnColor) { this.gridField = gridField; this.n = n; this.m = m; this.pawnColor = pawnColor; ImageView viewedImage = new ImageView(); } public PawnColor getPawnColor() { return pawnColor; } public void setPawnColor(PawnColor pawnColor) { this.pawnColor = pawnColor; } public StackPane getGridField() { return gridField; } public void setGridField(StackPane gridField) { this.gridField = gridField; } public int getN() { return n; } public void setN(int n) { this.n = n; } public int getM() { return m; } public void setM(int m) { this.m = m; } public ImageView getViewedImage() { return viewedImage; } public void setViewedImage(ImageView viewedImage) { this.viewedImage = viewedImage; } }
UTF-8
Java
1,295
java
FieldViewControl.java
Java
[]
null
[]
package checkers.classes; import checkers.enums.PawnColor; import javafx.scene.image.ImageView; import javafx.scene.layout.StackPane; public class FieldViewControl { StackPane gridField; int n; int m; ImageView viewedImage; PawnColor pawnColor; public FieldViewControl(StackPane gridField, int n, int m, PawnColor pawnColor) { this.gridField = gridField; this.n = n; this.m = m; this.pawnColor = pawnColor; ImageView viewedImage = new ImageView(); } public PawnColor getPawnColor() { return pawnColor; } public void setPawnColor(PawnColor pawnColor) { this.pawnColor = pawnColor; } public StackPane getGridField() { return gridField; } public void setGridField(StackPane gridField) { this.gridField = gridField; } public int getN() { return n; } public void setN(int n) { this.n = n; } public int getM() { return m; } public void setM(int m) { this.m = m; } public ImageView getViewedImage() { return viewedImage; } public void setViewedImage(ImageView viewedImage) { this.viewedImage = viewedImage; } }
1,295
0.594595
0.594595
79
15.392406
16.83984
83
false
false
0
0
0
0
0
0
0.341772
false
false
14
7c014953e909fae69a2611ccc7978486c41eaa02
3,204,045,644,045
5fb73e173381dd13498622763662472327e2b55c
/myapp/WeichatApp/app/src/main/java/org/weishe/weichat/util/SpUtil.java
bc08c5bd6230e2823bd3f7a36bd3dc797e5e6020
[]
no_license
chimuca/myapp
https://github.com/chimuca/myapp
26ba10b07f7eeb3776737f3007fff3f10852ba55
0708180429ee23b2b416560bcac9e0ddd6f934d7
refs/heads/master
2021-01-10T13:40:10.459000
2016-01-03T12:49:49
2016-01-03T12:49:49
48,651,039
3
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.weishe.weichat.util; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class SpUtil { private static final String NAME = "QQ"; private static SpUtil instance; static { instance = new SpUtil(); } public static SpUtil getInstance() { if (instance == null) { instance = new SpUtil(); } return instance; } public static SharedPreferences getSharePerference(Context context) { return context.getSharedPreferences(NAME, Context.MODE_PRIVATE); } public static boolean isFirst(SharedPreferences sp) { return sp.getBoolean("isFirst", true); } public static void setStringSharedPerference(SharedPreferences sp, String key, String value) { Editor editor = sp.edit(); editor.putString(key, value); editor.commit(); } public static void setBooleanSharedPerference(SharedPreferences sp, String key, boolean value) { Editor editor = sp.edit(); editor.putBoolean(key, value); editor.commit(); } }
UTF-8
Java
1,027
java
SpUtil.java
Java
[]
null
[]
package org.weishe.weichat.util; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class SpUtil { private static final String NAME = "QQ"; private static SpUtil instance; static { instance = new SpUtil(); } public static SpUtil getInstance() { if (instance == null) { instance = new SpUtil(); } return instance; } public static SharedPreferences getSharePerference(Context context) { return context.getSharedPreferences(NAME, Context.MODE_PRIVATE); } public static boolean isFirst(SharedPreferences sp) { return sp.getBoolean("isFirst", true); } public static void setStringSharedPerference(SharedPreferences sp, String key, String value) { Editor editor = sp.edit(); editor.putString(key, value); editor.commit(); } public static void setBooleanSharedPerference(SharedPreferences sp, String key, boolean value) { Editor editor = sp.edit(); editor.putBoolean(key, value); editor.commit(); } }
1,027
0.743914
0.743914
42
23.452381
21.157238
70
false
false
0
0
0
0
0
0
1.714286
false
false
14
b551153e632de462beadca7b67c1b2b7f4b6f843
7,249,904,859,024
cfe27887755ce881e7c92e4ffcda258b580e1056
/AngluinImp/src/Main.java
8b4214ca97a9570e016d50f197224d22e785be2d
[]
no_license
ShakeAnApple/active-learning
https://github.com/ShakeAnApple/active-learning
d9c6b51f895f8db03501b3828ca5854ddfce4921
5213be65d954df3d447bf4e19fbdc1c56fb383b3
refs/heads/master
2020-03-15T05:07:43.866000
2019-02-26T13:56:56
2019-02-26T13:56:56
131,982,227
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import automaton.Automaton; import config.*; import connection.matlab.MatlabConnector; import connection.nxt.NxtStudioConnector; import impl.LearningService; import simulation.SimulationService; import utils.AlphabetConstructor; import utils.NusmvConverter; import utils.SerializationUtils; import values.Symbol; import java.util.List; public class Main { public static void main(String[] args) throws Exception { //String path = "C:\\Projects\\Uni\\Active Learning\\BFSLearning\\config.conf"; Config conf = ConfigReader.read(args[1]); //Config conf = ConfigReader.read(path); ConfigParser parser = new ConfigParser(new VariableInfoFabric()); AbstractContext context = parser.parse(conf); boolean isMatlabModel = context instanceof MatlabContext; // Automaton a = SerializationUtils.deserializeAutomaton("automaton_gen.bin"); // NusmvConverter.saveInNusmvFormat(a, "res.txt"); if (isMatlabModel) { processMatlabModel((MatlabContext) context); } else{ processNxtModel((NxtContext) context); } } public static void processMatlabModel(MatlabContext context) throws Exception{ ///////////////////////////// old declarations ////////////////////// // List<BooleanValueHandler> possibleBoolValues = List.of(new BooleanValueHandler(true), new BooleanValueHandler(false)); // // VariableInfo<BooleanValueHandler> inputFwd = new VariableInfo("Fwd", 0, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> inputRetr = new VariableInfo("Retr", 1, possibleBoolValues, BooleanValueHandler::new); // List<VariableInfo> inputVars = List.of(inputFwd,inputRetr); // // VariableInfo<BooleanValueHandler> outputLeft = new VariableInfo("Left", 0, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputRight = new VariableInfo("Right", 1, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputFailure = new VariableInfo("Failure", 2, possibleBoolValues, BooleanValueHandler::new); // List<VariableInfo> outputVars = List.of(outputLeft,outputRight,outputFailure); // // String workingDir = "C:\\Projects\\FCP\\active_learning\\cylinder_simulink"; // String sysName = "Cylinder_simple"; /////////////////////////////////////// List<Symbol> inputAlphabet = AlphabetConstructor.construct(context.generateInputVariablesValues()); List<Symbol> outputAlphabet = AlphabetConstructor.construct(context.generateOutputVariablesValues()); Automaton hypothesis = new Automaton(context.getInputVariablesInfos(), context.getOutputVariablesInfos(), inputAlphabet, outputAlphabet); MatlabConnector connector = new MatlabConnector(context.getWorkingDir(), context.getSysName(), context); SimulationService simulationService = new SimulationService(connector); LearningService ls = new LearningService(simulationService, hypothesis); connector.connect(); connector.loadModelAsync(context.getSysName()); do{ ls.stepForward(); }while((!ls.isReady())); } public static void processNxtModel(NxtContext context) throws Exception { /////////////// old vars declarations //////////////////////////////////////////////////// // List<BooleanValueHandler> possibleBoolValues = List.of(new BooleanValueHandler(true), new BooleanValueHandler(false)); // // VariableInfo<BooleanValueHandler> inputDoor0Open = new VariableInfo("door0", 2, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> inputDoor1Open = new VariableInfo("door1", 3, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> inputDoor2Open = new VariableInfo("door2", 4, possibleBoolValues, BooleanValueHandler::new); // // VariableInfo<BooleanValueHandler> inputDoMotorUp = new VariableInfo("motorUp", 0, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> inputDoMotorDown = new VariableInfo("motorDown", 1, possibleBoolValues, BooleanValueHandler::new); // List<VariableInfo> inputVars = List.of(inputDoMotorDown, inputDoMotorUp, // inputDoor0Open, inputDoor1Open, inputDoor2Open); // // Interval<Double>[] posIntervals = new Interval[]{ // new Interval<>(30.0, 30.5), // new Interval<>(30.5, 224.5), // new Interval<>(224.5, 225.5), // new Interval<>(225.5, 418.5), // new Interval<>(418.5, 419.5) // }; // // List<IntervalValueHandler> possiblePosValues = new ArrayList<>(); // // for (Interval<Double> interval : posIntervals) { // possiblePosValues.add( // new IntervalValueHandler(posIntervals, Double::parseDouble, (Double o1, Double o2) -> { // if (01 > o2) return 1; // if (o1 < o2) return -1; // return 0; // }, interval) // ); // } // // VariableInfo<IntervalValueHandler> outputPos = new VariableInfo("pos", 9, possiblePosValues, () -> new IntervalValueHandler(posIntervals, (String str) -> Double.parseDouble(str), (Double o1, Double o2) -> { // if (01 > o2) return 1; // if (o1 < o2) return -1; // return 0; // }, posIntervals[0])); // VariableInfo<BooleanValueHandler> outputButtonFloor0 = new VariableInfo("buttonFloor0", 0, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputButtonFloor1 = new VariableInfo("buttonFloor1", 1, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputButtonFloor2 = new VariableInfo("buttonFloor2", 2, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputRequestFloor0 = new VariableInfo("requestFloor0", 0, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputRequestFloor1 = new VariableInfo("requestFloor1", 1, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputRequestFloor2 = new VariableInfo("requestFloor2", 2, possibleBoolValues, BooleanValueHandler::new); // // VariableInfo<BooleanValueHandler> outputElevatorAtFloor0 = new VariableInfo("elevatorAtFloor0", 3, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputElevatorAtFloor1 = new VariableInfo("elevatorAtFloor1", 4, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputElevatorAtFloor2 = new VariableInfo("elevatorAtFloor2", 5, possibleBoolValues, BooleanValueHandler::new); // // VariableInfo<BooleanValueHandler> outputDoor0Closed = new VariableInfo("door0Closed", 6, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputDoor1Closed = new VariableInfo("door1Closed", 7, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputDoor2Closed = new VariableInfo("door2Closed", 8, possibleBoolValues, BooleanValueHandler::new); // // List<VariableInfo> outputVars = List.of( // outputDoor0Closed, outputDoor1Closed, outputDoor2Closed, // outputElevatorAtFloor0, outputElevatorAtFloor1, outputElevatorAtFloor2, // outputRequestFloor0, outputRequestFloor1, outputRequestFloor2, // outputPos); ////////////////////////////////////////////////////////////// List<Symbol> inputAlphabet = AlphabetConstructor.construct(context.generateInputVariablesValues()); List<Symbol> outputAlphabet = AlphabetConstructor.construct(context.generateOutputVariablesValues()); Automaton hypothesis = new Automaton(context.getInputVariablesInfos(), context.getOutputVariablesInfos(), inputAlphabet, outputAlphabet); // Automaton a = SerializationUtils.deserializeAutomaton("automaton.bin"); NxtStudioConnector connector = new NxtStudioConnector(context.getInPort(), context.getOutPort(), context); connector.connect(); SimulationService simulationService = new SimulationService(connector); LearningService ls = new LearningService(simulationService, hypothesis); do{ ls.stepForward(); }while((!ls.isReady())); } }
UTF-8
Java
8,605
java
Main.java
Java
[ { "context": "\\\\cylinder_simulink\";\n// String sysName = \"Cylinder_simple\";\n ///////////////////////////////////////", "end": 2389, "score": 0.9337550401687622, "start": 2374, "tag": "USERNAME", "value": "Cylinder_simple" } ]
null
[]
import automaton.Automaton; import config.*; import connection.matlab.MatlabConnector; import connection.nxt.NxtStudioConnector; import impl.LearningService; import simulation.SimulationService; import utils.AlphabetConstructor; import utils.NusmvConverter; import utils.SerializationUtils; import values.Symbol; import java.util.List; public class Main { public static void main(String[] args) throws Exception { //String path = "C:\\Projects\\Uni\\Active Learning\\BFSLearning\\config.conf"; Config conf = ConfigReader.read(args[1]); //Config conf = ConfigReader.read(path); ConfigParser parser = new ConfigParser(new VariableInfoFabric()); AbstractContext context = parser.parse(conf); boolean isMatlabModel = context instanceof MatlabContext; // Automaton a = SerializationUtils.deserializeAutomaton("automaton_gen.bin"); // NusmvConverter.saveInNusmvFormat(a, "res.txt"); if (isMatlabModel) { processMatlabModel((MatlabContext) context); } else{ processNxtModel((NxtContext) context); } } public static void processMatlabModel(MatlabContext context) throws Exception{ ///////////////////////////// old declarations ////////////////////// // List<BooleanValueHandler> possibleBoolValues = List.of(new BooleanValueHandler(true), new BooleanValueHandler(false)); // // VariableInfo<BooleanValueHandler> inputFwd = new VariableInfo("Fwd", 0, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> inputRetr = new VariableInfo("Retr", 1, possibleBoolValues, BooleanValueHandler::new); // List<VariableInfo> inputVars = List.of(inputFwd,inputRetr); // // VariableInfo<BooleanValueHandler> outputLeft = new VariableInfo("Left", 0, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputRight = new VariableInfo("Right", 1, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputFailure = new VariableInfo("Failure", 2, possibleBoolValues, BooleanValueHandler::new); // List<VariableInfo> outputVars = List.of(outputLeft,outputRight,outputFailure); // // String workingDir = "C:\\Projects\\FCP\\active_learning\\cylinder_simulink"; // String sysName = "Cylinder_simple"; /////////////////////////////////////// List<Symbol> inputAlphabet = AlphabetConstructor.construct(context.generateInputVariablesValues()); List<Symbol> outputAlphabet = AlphabetConstructor.construct(context.generateOutputVariablesValues()); Automaton hypothesis = new Automaton(context.getInputVariablesInfos(), context.getOutputVariablesInfos(), inputAlphabet, outputAlphabet); MatlabConnector connector = new MatlabConnector(context.getWorkingDir(), context.getSysName(), context); SimulationService simulationService = new SimulationService(connector); LearningService ls = new LearningService(simulationService, hypothesis); connector.connect(); connector.loadModelAsync(context.getSysName()); do{ ls.stepForward(); }while((!ls.isReady())); } public static void processNxtModel(NxtContext context) throws Exception { /////////////// old vars declarations //////////////////////////////////////////////////// // List<BooleanValueHandler> possibleBoolValues = List.of(new BooleanValueHandler(true), new BooleanValueHandler(false)); // // VariableInfo<BooleanValueHandler> inputDoor0Open = new VariableInfo("door0", 2, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> inputDoor1Open = new VariableInfo("door1", 3, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> inputDoor2Open = new VariableInfo("door2", 4, possibleBoolValues, BooleanValueHandler::new); // // VariableInfo<BooleanValueHandler> inputDoMotorUp = new VariableInfo("motorUp", 0, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> inputDoMotorDown = new VariableInfo("motorDown", 1, possibleBoolValues, BooleanValueHandler::new); // List<VariableInfo> inputVars = List.of(inputDoMotorDown, inputDoMotorUp, // inputDoor0Open, inputDoor1Open, inputDoor2Open); // // Interval<Double>[] posIntervals = new Interval[]{ // new Interval<>(30.0, 30.5), // new Interval<>(30.5, 224.5), // new Interval<>(224.5, 225.5), // new Interval<>(225.5, 418.5), // new Interval<>(418.5, 419.5) // }; // // List<IntervalValueHandler> possiblePosValues = new ArrayList<>(); // // for (Interval<Double> interval : posIntervals) { // possiblePosValues.add( // new IntervalValueHandler(posIntervals, Double::parseDouble, (Double o1, Double o2) -> { // if (01 > o2) return 1; // if (o1 < o2) return -1; // return 0; // }, interval) // ); // } // // VariableInfo<IntervalValueHandler> outputPos = new VariableInfo("pos", 9, possiblePosValues, () -> new IntervalValueHandler(posIntervals, (String str) -> Double.parseDouble(str), (Double o1, Double o2) -> { // if (01 > o2) return 1; // if (o1 < o2) return -1; // return 0; // }, posIntervals[0])); // VariableInfo<BooleanValueHandler> outputButtonFloor0 = new VariableInfo("buttonFloor0", 0, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputButtonFloor1 = new VariableInfo("buttonFloor1", 1, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputButtonFloor2 = new VariableInfo("buttonFloor2", 2, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputRequestFloor0 = new VariableInfo("requestFloor0", 0, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputRequestFloor1 = new VariableInfo("requestFloor1", 1, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputRequestFloor2 = new VariableInfo("requestFloor2", 2, possibleBoolValues, BooleanValueHandler::new); // // VariableInfo<BooleanValueHandler> outputElevatorAtFloor0 = new VariableInfo("elevatorAtFloor0", 3, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputElevatorAtFloor1 = new VariableInfo("elevatorAtFloor1", 4, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputElevatorAtFloor2 = new VariableInfo("elevatorAtFloor2", 5, possibleBoolValues, BooleanValueHandler::new); // // VariableInfo<BooleanValueHandler> outputDoor0Closed = new VariableInfo("door0Closed", 6, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputDoor1Closed = new VariableInfo("door1Closed", 7, possibleBoolValues, BooleanValueHandler::new); // VariableInfo<BooleanValueHandler> outputDoor2Closed = new VariableInfo("door2Closed", 8, possibleBoolValues, BooleanValueHandler::new); // // List<VariableInfo> outputVars = List.of( // outputDoor0Closed, outputDoor1Closed, outputDoor2Closed, // outputElevatorAtFloor0, outputElevatorAtFloor1, outputElevatorAtFloor2, // outputRequestFloor0, outputRequestFloor1, outputRequestFloor2, // outputPos); ////////////////////////////////////////////////////////////// List<Symbol> inputAlphabet = AlphabetConstructor.construct(context.generateInputVariablesValues()); List<Symbol> outputAlphabet = AlphabetConstructor.construct(context.generateOutputVariablesValues()); Automaton hypothesis = new Automaton(context.getInputVariablesInfos(), context.getOutputVariablesInfos(), inputAlphabet, outputAlphabet); // Automaton a = SerializationUtils.deserializeAutomaton("automaton.bin"); NxtStudioConnector connector = new NxtStudioConnector(context.getInPort(), context.getOutPort(), context); connector.connect(); SimulationService simulationService = new SimulationService(connector); LearningService ls = new LearningService(simulationService, hypothesis); do{ ls.stepForward(); }while((!ls.isReady())); } }
8,605
0.68588
0.67147
152
55.611843
52.011013
216
false
false
0
0
0
0
65
0.007554
1.302632
false
false
14
af63a19b433da3965410724f49702751c1b26925
24,610,162,661,028
29a31d7cf03c87976636499cc80f3a939c8b18cb
/core/src/com/mygdx/game/systems/CameraSystem.java
537bd7ba1f23ec87d5c935d55fafbbb881f1ca06
[]
no_license
zolixes/Ashley-LibGdx-Tests-2D
https://github.com/zolixes/Ashley-LibGdx-Tests-2D
c28f8bd7a6e00ef1657726e6eab89993b34e1d16
a947baf70eb3d61fabb0072b712a979ee650bfb9
HEAD
2017-12-07T06:48:13.291000
2017-01-21T14:17:48
2017-01-21T14:17:48
79,649,458
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mygdx.game.systems; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.EntitySystem; import com.badlogic.ashley.core.Family; import com.badlogic.ashley.systems.IteratingSystem; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.math.Vector3; import com.mygdx.game.components.CameraComponent; import com.mygdx.game.components.PositionComponent; import static com.mygdx.game.helpers.Mappers.cameraMapper; import static com.mygdx.game.helpers.Mappers.positionMapper; /** Created by Giuseppe on 1/14/2017. */ public class CameraSystem extends IteratingSystem { public CameraSystem() { super(Family.all(CameraComponent.class).get()); } @Override protected void processEntity(Entity entity, float deltaTime) { CameraComponent camComp = cameraMapper.get(entity); OrthographicCamera camera = camComp.camera; Entity target = camComp.target; PositionComponent pc = positionMapper.get(target); /* float lerp = .1f; camera.position.x += (pc.x - camera.position.x) * lerp * deltaTime; camera.position.y += (pc.y - camera.position.y) * lerp * deltaTime; */ camera.position.set(pc.x, pc.y, 0); camera.update(); } }
UTF-8
Java
1,278
java
CameraSystem.java
Java
[ { "context": "me.helpers.Mappers.positionMapper;\n\n/** Created by Giuseppe on 1/14/2017. */\npublic class CameraSystem extend", "end": 549, "score": 0.9249706268310547, "start": 541, "tag": "USERNAME", "value": "Giuseppe" } ]
null
[]
package com.mygdx.game.systems; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.EntitySystem; import com.badlogic.ashley.core.Family; import com.badlogic.ashley.systems.IteratingSystem; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.math.Vector3; import com.mygdx.game.components.CameraComponent; import com.mygdx.game.components.PositionComponent; import static com.mygdx.game.helpers.Mappers.cameraMapper; import static com.mygdx.game.helpers.Mappers.positionMapper; /** Created by Giuseppe on 1/14/2017. */ public class CameraSystem extends IteratingSystem { public CameraSystem() { super(Family.all(CameraComponent.class).get()); } @Override protected void processEntity(Entity entity, float deltaTime) { CameraComponent camComp = cameraMapper.get(entity); OrthographicCamera camera = camComp.camera; Entity target = camComp.target; PositionComponent pc = positionMapper.get(target); /* float lerp = .1f; camera.position.x += (pc.x - camera.position.x) * lerp * deltaTime; camera.position.y += (pc.y - camera.position.y) * lerp * deltaTime; */ camera.position.set(pc.x, pc.y, 0); camera.update(); } }
1,278
0.715962
0.708138
41
30.170732
24.891867
75
false
false
0
0
0
0
0
0
0.585366
false
false
14
5e231c1a8253cca6c47dce7926560de834286bdb
22,436,909,181,358
538414f61a305cf84e00cbd0f2c154e4fa99ccb7
/modules/org.zsoft.ecommerce/src/org/zsoft/ecommerce/order/client/attends/response/Sv97fehler.java
b5b2067b9db0dc2b9c7fc3fbf4dd5363ae672d79
[]
no_license
q3neeko/openz
https://github.com/q3neeko/openz
4024d007ef2f1094faad8a8c17db8147e689d0f3
050ae0ba7b54ba9276a2fa85ecf5b2ec33954859
refs/heads/master
2020-03-29T21:44:56.783000
2018-09-26T14:34:00
2018-09-26T14:34:00
150,385,120
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.zsoft.ecommerce.order.client.attends.response; public class Sv97fehler { private Fehler fehler; public Fehler getFehler () { return fehler; } public void setFehler (Fehler fehler) { this.fehler = fehler; } }
UTF-8
Java
249
java
Sv97fehler.java
Java
[]
null
[]
package org.zsoft.ecommerce.order.client.attends.response; public class Sv97fehler { private Fehler fehler; public Fehler getFehler () { return fehler; } public void setFehler (Fehler fehler) { this.fehler = fehler; } }
249
0.682731
0.674699
15
15.6
17.098928
58
false
false
0
0
0
0
0
0
0.266667
false
false
14
9ea673b2bd7969c560d29cacfbed43a3c689f775
22,436,909,182,596
2fefbd9b0c1abbfa390f8de8801e8a872837b49c
/src/main/java/in/co/examsadda/service/SectionService.java
f70bdac4c4aa69e96d2e2eea943699d6857b9c48
[]
no_license
SAPDHARMASATYAM/EAS
https://github.com/SAPDHARMASATYAM/EAS
7dfa190023ff086da65511f8b23f947472d88942
6715f982a9521db9ec9640ac90fd0563622c534a
refs/heads/master
2021-04-03T07:02:55.255000
2018-05-06T05:25:36
2018-05-06T05:25:36
123,572,057
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package in.co.examsadda.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import in.co.examsadda.entity.Exam; import in.co.examsadda.entity.Section; import in.co.examsadda.repository.SectionCrudRepository; @Service public class SectionService { //@Autowired //public SectionCrudRepository sectionCurdRepository; }
UTF-8
Java
433
java
SectionService.java
Java
[]
null
[]
package in.co.examsadda.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import in.co.examsadda.entity.Exam; import in.co.examsadda.entity.Section; import in.co.examsadda.repository.SectionCrudRepository; @Service public class SectionService { //@Autowired //public SectionCrudRepository sectionCurdRepository; }
433
0.787529
0.787529
18
22.055555
21.742105
62
false
false
0
0
0
0
0
0
0.611111
false
false
14
52ec7bc9da49529fc9809b1494c28d8a4cf68f9b
22,634,477,684,477
206a650ffcac7214048546200456f7d71c1ba557
/src/com/itbank/model/repository/JdbcAdminDAO.java
dbf6130a0ba2d2829e427108ddd7026d76a7549d
[]
no_license
myungjae18/RestProject
https://github.com/myungjae18/RestProject
0182750679c95d6f8e550345992e3df43587b3d9
3f96ce8598b6bcac8a48c730e2977432172a8168
refs/heads/master
2020-05-07T12:12:00.329000
2019-04-29T00:21:54
2019-04-29T00:21:54
180,492,905
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.itbank.model.repository; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import com.itbank.model.domain.Admin; @Repository public class JdbcAdminDAO implements AdminDAO { @Autowired private JdbcTemplate jdbcTemplate; @Override public List selectAll() { return null; } @Override public Admin select(int admin_id) { return null; } @Override public Admin loginCheck(Admin admin) { Admin obj = null; String sql = "select * from admin where id=? and pass=?"; try { obj = jdbcTemplate.queryForObject(sql, new RowMapper<Admin>() { @Override public Admin mapRow(ResultSet rs, int rowNum) throws SQLException { Admin admin = new Admin(); admin.setAdmin_id(rs.getInt("admin_id")); admin.setId(rs.getString("id")); admin.setPass(rs.getString("pass")); admin.setName(rs.getString("name")); return admin; } }, admin.getId(), admin.getPass()); } catch (DataAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } return obj; } @Override public int insert(Admin admin) { return 0; } @Override public int update(Admin admin) { return 0; } @Override public int delete(int admin_id) { return 0; } }
UTF-8
Java
1,526
java
JdbcAdminDAO.java
Java
[]
null
[]
package com.itbank.model.repository; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import com.itbank.model.domain.Admin; @Repository public class JdbcAdminDAO implements AdminDAO { @Autowired private JdbcTemplate jdbcTemplate; @Override public List selectAll() { return null; } @Override public Admin select(int admin_id) { return null; } @Override public Admin loginCheck(Admin admin) { Admin obj = null; String sql = "select * from admin where id=? and pass=?"; try { obj = jdbcTemplate.queryForObject(sql, new RowMapper<Admin>() { @Override public Admin mapRow(ResultSet rs, int rowNum) throws SQLException { Admin admin = new Admin(); admin.setAdmin_id(rs.getInt("admin_id")); admin.setId(rs.getString("id")); admin.setPass(rs.getString("pass")); admin.setName(rs.getString("name")); return admin; } }, admin.getId(), admin.getPass()); } catch (DataAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } return obj; } @Override public int insert(Admin admin) { return 0; } @Override public int update(Admin admin) { return 0; } @Override public int delete(int admin_id) { return 0; } }
1,526
0.71363
0.711664
76
19.092106
19.453167
71
false
false
0
0
0
0
0
0
1.671053
false
false
14
1731a7ab2ae338e0ea3c25f8de4ff1dd87f44f3c
7,155,415,554,937
474c27f3f42aa5deffece3a4a8895e785f2adc93
/lang/java/reef-io/src/main/java/org/apache/reef/io/data/loading/impl/DistributedDataSetPartition.java
a9de6f3f963c3d9edbcd5cc88b86fbc8b1709378
[ "Apache-2.0" ]
permissive
apache/reef
https://github.com/apache/reef
7a886e62b065bddc7271ea967ddec3984dc7f48e
b621659dbffc4e7826d618f0f0359c0a6e597b97
refs/heads/master
2023-08-26T04:58:03.787000
2021-05-26T15:06:07
2021-05-26T15:06:07
25,623,941
87
104
Apache-2.0
false
2022-07-06T19:58:15
2014-10-23T07:00:10
2022-06-28T02:13:38
2022-07-06T19:58:15
40,243
95
104
8
Java
false
false
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.reef.io.data.loading.impl; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.reef.annotations.Unstable; /** * POJO that represents a distributed data set partition. Basically, it contains the path where * the data files are located for this partition, and the location where we want * this data to be loaded into. * */ @Unstable public final class DistributedDataSetPartition { /** * The path of the distributed data set partition. If we use HDFS, it will be the * hdfs path. */ private final String path; /** * The location (either a rackName or a nodeName) where we want the data in * this distributed partition to be loaded into. It can contain a wildcard at * the end, for example /datacenter1/*. */ private final String location; /** * Number of desired splits for this partition. */ private final int desiredSplits; DistributedDataSetPartition(final String path, final String location, final int desiredSplits) { this.path = path; this.location = location; this.desiredSplits = desiredSplits; } /** * Returns the path to the distributed data partition. * * @return the path of the distributed data partition */ String getPath() { return path; } /** * Returns the location where we want the data in this partition to be loaded * into. * * @return the location where to load this data into. */ String getLocation() { return location; } /** * Returns the number of desired splits for this data partition. * * @return the number of desired splits */ int getDesiredSplits() { return desiredSplits; } /** * @return a new DistributedDataSetPartition Builder. */ public static Builder newBuilder() { return new Builder(); } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof DistributedDataSetPartition)) { return false; } final DistributedDataSetPartition that = (DistributedDataSetPartition) obj; return new EqualsBuilder().append(this.path, that.path).append(this.location, that.location) .append(this.desiredSplits, that.desiredSplits).isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37).append(this.path).append(this.location).append(this.desiredSplits).toHashCode(); } @Override public String toString() { return "{" + this.path + "," + this.location + "," + this.desiredSplits + "}"; } /** * {@link DistributedDataSetPartition}s are build using this Builder. */ public static final class Builder implements org.apache.reef.util.Builder<DistributedDataSetPartition> { private String path; private String location; private int desiredSplits; private Builder() { } /** * Sets the path of the distributed data set partition. * * @param path * the path to set * @return this */ public Builder setPath(final String path) { this.path = path; return this; } /** * Sets the location where we want the data in this partition to be loaded * into. * * @param location * the location to set * @return this */ public Builder setLocation(final String location) { this.location = location; return this; } /** * Sets the desired number of splits for this partition. * @param desiredSplits * the number of desired splits * @return this */ public Builder setDesiredSplits(final int desiredSplits) { this.desiredSplits = desiredSplits; return this; } /** * Builds the {@link DistributedDataSetPartition}. */ @Override public DistributedDataSetPartition build() { return new DistributedDataSetPartition(this.path, this.location, this.desiredSplits); } } }
UTF-8
Java
4,822
java
DistributedDataSetPartition.java
Java
[]
null
[]
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.reef.io.data.loading.impl; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.reef.annotations.Unstable; /** * POJO that represents a distributed data set partition. Basically, it contains the path where * the data files are located for this partition, and the location where we want * this data to be loaded into. * */ @Unstable public final class DistributedDataSetPartition { /** * The path of the distributed data set partition. If we use HDFS, it will be the * hdfs path. */ private final String path; /** * The location (either a rackName or a nodeName) where we want the data in * this distributed partition to be loaded into. It can contain a wildcard at * the end, for example /datacenter1/*. */ private final String location; /** * Number of desired splits for this partition. */ private final int desiredSplits; DistributedDataSetPartition(final String path, final String location, final int desiredSplits) { this.path = path; this.location = location; this.desiredSplits = desiredSplits; } /** * Returns the path to the distributed data partition. * * @return the path of the distributed data partition */ String getPath() { return path; } /** * Returns the location where we want the data in this partition to be loaded * into. * * @return the location where to load this data into. */ String getLocation() { return location; } /** * Returns the number of desired splits for this data partition. * * @return the number of desired splits */ int getDesiredSplits() { return desiredSplits; } /** * @return a new DistributedDataSetPartition Builder. */ public static Builder newBuilder() { return new Builder(); } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof DistributedDataSetPartition)) { return false; } final DistributedDataSetPartition that = (DistributedDataSetPartition) obj; return new EqualsBuilder().append(this.path, that.path).append(this.location, that.location) .append(this.desiredSplits, that.desiredSplits).isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37).append(this.path).append(this.location).append(this.desiredSplits).toHashCode(); } @Override public String toString() { return "{" + this.path + "," + this.location + "," + this.desiredSplits + "}"; } /** * {@link DistributedDataSetPartition}s are build using this Builder. */ public static final class Builder implements org.apache.reef.util.Builder<DistributedDataSetPartition> { private String path; private String location; private int desiredSplits; private Builder() { } /** * Sets the path of the distributed data set partition. * * @param path * the path to set * @return this */ public Builder setPath(final String path) { this.path = path; return this; } /** * Sets the location where we want the data in this partition to be loaded * into. * * @param location * the location to set * @return this */ public Builder setLocation(final String location) { this.location = location; return this; } /** * Sets the desired number of splits for this partition. * @param desiredSplits * the number of desired splits * @return this */ public Builder setDesiredSplits(final int desiredSplits) { this.desiredSplits = desiredSplits; return this; } /** * Builds the {@link DistributedDataSetPartition}. */ @Override public DistributedDataSetPartition build() { return new DistributedDataSetPartition(this.path, this.location, this.desiredSplits); } } }
4,822
0.678971
0.676898
173
26.872833
27.744833
119
false
false
0
0
0
0
0
0
0.283237
false
false
14
b54ca7aa903f0e8e168751fd6476e9d85138aa90
31,911,607,073,261
9b50de7215344cc3bbf988168180ee11a4669f52
/src/main/java/com/lanu/user_front_online_banking/UserFrontOnlineBankingApplication.java
8c4b9fb370e85e54feb6c5f762e80a30c37cc70c
[]
no_license
mrlanu/user-front-online-banking
https://github.com/mrlanu/user-front-online-banking
d82099624e491b5dd0705480fd7b644406488e29
51cec4ce5e6b05f823ae131b3829b8a4428eebfb
refs/heads/master
2021-05-02T08:55:41.536000
2018-02-17T23:56:36
2018-02-17T23:56:36
120,816,471
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lanu.user_front_online_banking; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class UserFrontOnlineBankingApplication { public static void main(String[] args) { SpringApplication.run(UserFrontOnlineBankingApplication.class, args); } }
UTF-8
Java
358
java
UserFrontOnlineBankingApplication.java
Java
[]
null
[]
package com.lanu.user_front_online_banking; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class UserFrontOnlineBankingApplication { public static void main(String[] args) { SpringApplication.run(UserFrontOnlineBankingApplication.class, args); } }
358
0.837989
0.837989
12
28.833334
26.632792
71
false
false
0
0
0
0
0
0
0.75
false
false
14
7284900aa6438ee2f4d595fb8d8ac87998be6cbb
7,086,696,067,348
c156463cf82d43fff75cd484b0884a6b99404aa2
/ZeroToHero1/src/WrapperClasses/TESTING_MY_KNOWLADGE.java
3973739932be6559f9d3303d204484588d3d5e54
[]
no_license
bamboo1991/ZeroToHero1
https://github.com/bamboo1991/ZeroToHero1
39d71380d5e8f96beb4c4301cb3571b759d48a55
84402e09e63e176d5129f0460fd6087d218dabd8
refs/heads/master
2022-07-10T19:30:33.958000
2020-04-04T04:33:01
2020-04-04T04:33:01
241,712,319
0
1
null
false
2020-10-13T20:23:23
2020-02-19T19:56:37
2020-04-04T04:33:56
2020-10-13T20:23:22
2,828
0
0
2
Java
false
false
package WrapperClasses; import java.util.Arrays; import java.util.List; public class TESTING_MY_KNOWLADGE { public static void main(String[] args) { List<String> drinks = Arrays.asList("Coffee $2.20","Tea $2.75", "cappuccino $4.5", "latte $2.75"); for (int i =0; i<drinks.size(); i++){ int indexOf$ = drinks.get(i).indexOf("$"); String priceFromString = drinks.get(i).substring( indexOf$+1); double price = Double.parseDouble(priceFromString); double newPrice = price*1.1; String newValue = drinks.get(i).substring(0,indexOf$+1)+newPrice; drinks.set(i, newValue); } System.out.println(drinks); } }
UTF-8
Java
721
java
TESTING_MY_KNOWLADGE.java
Java
[]
null
[]
package WrapperClasses; import java.util.Arrays; import java.util.List; public class TESTING_MY_KNOWLADGE { public static void main(String[] args) { List<String> drinks = Arrays.asList("Coffee $2.20","Tea $2.75", "cappuccino $4.5", "latte $2.75"); for (int i =0; i<drinks.size(); i++){ int indexOf$ = drinks.get(i).indexOf("$"); String priceFromString = drinks.get(i).substring( indexOf$+1); double price = Double.parseDouble(priceFromString); double newPrice = price*1.1; String newValue = drinks.get(i).substring(0,indexOf$+1)+newPrice; drinks.set(i, newValue); } System.out.println(drinks); } }
721
0.596394
0.572816
21
33.333332
29.187952
106
false
false
0
0
0
0
0
0
0.857143
false
false
14
c7fdbefddc4fc164ac16653a3b416638041911b9
28,930,899,768,172
6a61e393dfad6a6cefdf4f06798917c3a7aee971
/tests/43_method_access_mode/m_access_02_override_2.java/A.java
022df90bc0cda472fba2f5dc710bf2c8136e2a01
[]
no_license
kframework/java-semantics
https://github.com/kframework/java-semantics
388bead15b594f3b2478441a5d95c02d7a0ccbf6
f27067ee7a38d236499992eed1b48064e70680fa
refs/heads/master
2021-09-22T20:42:43.662000
2021-09-15T19:53:33
2021-09-15T19:53:33
11,711,471
14
7
null
false
2016-03-16T22:03:02
2013-07-27T21:42:38
2016-03-15T08:31:11
2016-03-16T22:03:02
46,173
4
5
3
Java
null
null
/* - a.A: - private f11() - private f12() - private f13() - package g21() - package g22() - package g23() - protected h33() - public call() - calls all the methods. */ package a; public class A { private void f11() { System.out.println("A.f11()"); } private void f12() { System.out.println("A.f12()"); } private void f13() { System.out.println("A.f13()"); } void g21() { System.out.println("A.g21()"); } void g22() { System.out.println("A.g22()"); } void g23() { System.out.println("A.g23()"); } protected void h33() { System.out.println("A.h33()"); } public void call() { System.out.println("Calling from " + getClass().getName()); f11(); f12(); f13(); g21(); g22(); g23(); h33(); System.out.println(); } }
UTF-8
Java
849
java
A.java
Java
[]
null
[]
/* - a.A: - private f11() - private f12() - private f13() - package g21() - package g22() - package g23() - protected h33() - public call() - calls all the methods. */ package a; public class A { private void f11() { System.out.println("A.f11()"); } private void f12() { System.out.println("A.f12()"); } private void f13() { System.out.println("A.f13()"); } void g21() { System.out.println("A.g21()"); } void g22() { System.out.println("A.g22()"); } void g23() { System.out.println("A.g23()"); } protected void h33() { System.out.println("A.h33()"); } public void call() { System.out.println("Calling from " + getClass().getName()); f11(); f12(); f13(); g21(); g22(); g23(); h33(); System.out.println(); } }
849
0.51119
0.44523
57
13.894737
13.588803
63
false
false
0
0
0
0
0
0
0.298246
false
false
14
2150a2fec788eeb894c35847bdb3e5a48e7fd0d3
3,624,952,426,723
ccb4bca48c49be19fa00f63369286bef89c106bf
/ShoesManagement/src/main/java/com/example/shoesmanagement/model/Brand.java
fc9536f32bba4465b8d076939ad558c108340f02
[]
no_license
hoangld17/ShoesBack-end
https://github.com/hoangld17/ShoesBack-end
7b11a385af30f69f6312bfcfa6cb765c06ae396a
b80bc47f9bee5274f29384566fb9c8498d326dfc
refs/heads/master
2023-07-04T20:30:02.138000
2021-07-24T04:17:16
2021-07-24T04:17:16
388,996,904
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.shoesmanagement.model; import com.example.shoesmanagement.model.enums.AppStatus; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import javax.persistence.*; import java.io.Serializable; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @DynamicInsert @DynamicUpdate @Entity @Table(name = "brand") @JsonInclude(JsonInclude.Include.NON_EMPTY) public class Brand extends AuditableDomain implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private AppStatus status; }
UTF-8
Java
792
java
Brand.java
Java
[]
null
[]
package com.example.shoesmanagement.model; import com.example.shoesmanagement.model.enums.AppStatus; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import javax.persistence.*; import java.io.Serializable; @Getter @Setter @NoArgsConstructor @AllArgsConstructor @DynamicInsert @DynamicUpdate @Entity @Table(name = "brand") @JsonInclude(JsonInclude.Include.NON_EMPTY) public class Brand extends AuditableDomain implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private AppStatus status; }
792
0.815657
0.815657
30
25.4
18.584223
68
false
false
0
0
0
0
0
0
0.466667
false
false
14
fa4700966788577d2e901da750738b6197ed75e6
11,768,210,419,442
b254eff7ad2d528e2395615e2245c6fbe41941a2
/src/main/java/pages/HomePage.java
d9e837209a831bf80ca4d047650fe7f2fab49327
[]
no_license
TheStalkerStatic/samuilau-autotest
https://github.com/TheStalkerStatic/samuilau-autotest
d886e5f29b3a40f561e6d4cce93898514c767a6c
151dc9988e26f19afc82c197ffbbd2fc2d88d4d6
refs/heads/master
2023-06-08T17:00:13.418000
2021-07-01T11:03:44
2021-07-01T11:03:44
375,938,882
0
0
null
false
2021-07-01T11:12:55
2021-06-11T07:19:42
2021-07-01T11:03:49
2021-07-01T11:11:10
150
0
0
1
Java
false
false
package pages; import io.qameta.allure.Step; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.testng.Assert; public class HomePage extends BasePage { @FindBy(id = "login") public WebElement logInButton; @FindBy(id = "search-form-btn") public WebElement searchButton; @FindBy(id = "search-form-field") public WebElement searchField; @FindBy(css = "button.btn_navbar_user-dropdown") public WebElement profile; @FindBy(css = ".page-header.page-header_110") public WebElement headerText; @FindBy(css = "button.btn.btn_medium.btn_navbar_lang.js-show_lang_settings") public WebElement langButton; @FindBy(xpath = "//label[text()='English']") public WebElement eng; @FindBy(css = "button.btn.btn_blue.btn_huge.btn_full-width.js-popup_save_btn") public WebElement changeLang; @FindBy(xpath = "//*[@role='menu']/ul/li[7]") public WebElement exitProfile; public HomePage(WebDriver driver) { super(driver); } @Step("Open the login page.") public LoginPage logInButtonClick() { logInButton.click(); return new LoginPage(driver); } @Step("Open the search bar.") public HomePage searchButtonClick() { searchButton.click(); return this; } @Step("Select the search bar and enter the desired word.") public SearchPage searchFieldSend(String searchWord) { searchField.sendKeys(searchWord, Keys.ENTER); return new SearchPage(driver); } @Step("Open a user profile.") public void profileEnabled() { Assert.assertTrue(profile.isEnabled()); } @Step("The text in the title on the main page.") public String headerTextGet() { return headerText.getText(); } @Step("Go to the language selection.") public HomePage langButtonClick() { langButton.click(); return this; } @Step("Select \"English\" language") public HomePage engClick() { eng.click(); return this; } @Step("Apply language changes") public HomePage changeLangClick() { changeLang.click(); return this; } @Step("Log out of the profile") public HomePage exitProf() { exitProfile.click(); return this; } @Step("Open a profile") public HomePage openProfile() { profile.click(); return this; } @Step("Checking the successful exit from the profile") public void checkExit() { Assert.assertTrue(logInButton.isDisplayed()); } }
UTF-8
Java
2,667
java
HomePage.java
Java
[]
null
[]
package pages; import io.qameta.allure.Step; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.testng.Assert; public class HomePage extends BasePage { @FindBy(id = "login") public WebElement logInButton; @FindBy(id = "search-form-btn") public WebElement searchButton; @FindBy(id = "search-form-field") public WebElement searchField; @FindBy(css = "button.btn_navbar_user-dropdown") public WebElement profile; @FindBy(css = ".page-header.page-header_110") public WebElement headerText; @FindBy(css = "button.btn.btn_medium.btn_navbar_lang.js-show_lang_settings") public WebElement langButton; @FindBy(xpath = "//label[text()='English']") public WebElement eng; @FindBy(css = "button.btn.btn_blue.btn_huge.btn_full-width.js-popup_save_btn") public WebElement changeLang; @FindBy(xpath = "//*[@role='menu']/ul/li[7]") public WebElement exitProfile; public HomePage(WebDriver driver) { super(driver); } @Step("Open the login page.") public LoginPage logInButtonClick() { logInButton.click(); return new LoginPage(driver); } @Step("Open the search bar.") public HomePage searchButtonClick() { searchButton.click(); return this; } @Step("Select the search bar and enter the desired word.") public SearchPage searchFieldSend(String searchWord) { searchField.sendKeys(searchWord, Keys.ENTER); return new SearchPage(driver); } @Step("Open a user profile.") public void profileEnabled() { Assert.assertTrue(profile.isEnabled()); } @Step("The text in the title on the main page.") public String headerTextGet() { return headerText.getText(); } @Step("Go to the language selection.") public HomePage langButtonClick() { langButton.click(); return this; } @Step("Select \"English\" language") public HomePage engClick() { eng.click(); return this; } @Step("Apply language changes") public HomePage changeLangClick() { changeLang.click(); return this; } @Step("Log out of the profile") public HomePage exitProf() { exitProfile.click(); return this; } @Step("Open a profile") public HomePage openProfile() { profile.click(); return this; } @Step("Checking the successful exit from the profile") public void checkExit() { Assert.assertTrue(logInButton.isDisplayed()); } }
2,667
0.644544
0.643045
106
24.160378
19.481068
82
false
false
0
0
0
0
0
0
0.349057
false
false
14
af568569872a6284edfefb7c50faf98c94d2c5bd
5,798,205,881,232
dba24495e0f799093ea088a462fb737cdd026235
/src/sort/MergeSort.java
11d3e8e1a20f56695d45f165144a2af9afa24152
[]
no_license
fivemoons/DataStructure
https://github.com/fivemoons/DataStructure
b6794b3a5bac3c539b922fdfdbe1b29df3f607aa
1c999c5239ab22c0a737809d2e7a035debe4225e
refs/heads/master
2020-04-15T23:51:19.723000
2016-12-04T10:30:32
2016-12-04T10:30:32
40,639,877
0
1
null
false
2016-04-28T01:45:12
2015-08-13T05:03:51
2016-01-29T03:10:28
2016-04-28T01:45:12
141
0
0
0
Java
null
null
package sort; public class MergeSort { private static void merge(int[] a, int[] tmp, int l, int m, int r){ int ll = l; int rr = m + 1; int cc = l; while((ll <= m) && (rr <= r)){ if(a[ll] < a[rr]){ tmp[cc++] = a[ll++]; }else{ tmp[cc++] = a[rr++]; } } while(ll<=m) tmp[cc++] = a[ll++]; while(rr<=r) tmp[cc++] = a[rr++]; for(int i=l; i<=r; i++){ a[i] = tmp[i]; } } private static void mergeSort(int[] a, int[] tmp, int l, int r){ if(l<r){ int m = (l + (r - l) / 2); mergeSort(a, tmp, l, m); mergeSort(a, tmp, m+1, r); merge(a, tmp, l, m, r); } } public static void Sort(int[] a){ int[] tmp = new int[a.length]; //归并a 存放缓存tmpArray 从0到a.length-1 mergeSort(a, tmp, 0, a.length-1); } public static void main(String[] args) { int[] a = new int[]{2,3,4,8,6,7,2}; Sort(a); for(int i:a){ System.out.print(i+" "); } System.out.println(); } }
UTF-8
Java
979
java
MergeSort.java
Java
[]
null
[]
package sort; public class MergeSort { private static void merge(int[] a, int[] tmp, int l, int m, int r){ int ll = l; int rr = m + 1; int cc = l; while((ll <= m) && (rr <= r)){ if(a[ll] < a[rr]){ tmp[cc++] = a[ll++]; }else{ tmp[cc++] = a[rr++]; } } while(ll<=m) tmp[cc++] = a[ll++]; while(rr<=r) tmp[cc++] = a[rr++]; for(int i=l; i<=r; i++){ a[i] = tmp[i]; } } private static void mergeSort(int[] a, int[] tmp, int l, int r){ if(l<r){ int m = (l + (r - l) / 2); mergeSort(a, tmp, l, m); mergeSort(a, tmp, m+1, r); merge(a, tmp, l, m, r); } } public static void Sort(int[] a){ int[] tmp = new int[a.length]; //归并a 存放缓存tmpArray 从0到a.length-1 mergeSort(a, tmp, 0, a.length-1); } public static void main(String[] args) { int[] a = new int[]{2,3,4,8,6,7,2}; Sort(a); for(int i:a){ System.out.print(i+" "); } System.out.println(); } }
979
0.480789
0.466251
44
19.886364
16.200752
68
false
false
0
0
0
0
0
0
2.954545
false
false
14
af4a3801fc0c53ada234cad39bce031243e16e17
26,955,214,790,265
7e554235d8f3d21a7ec70c2ad8070222c24ba6c2
/src/main/java/com/github/bcap/trafficmonitor/business/RoadWayExtractor.java
c50c6e43ad6480d01d15b7dff7690abe75e46f5c
[]
no_license
bcap/TrafficMonitor
https://github.com/bcap/TrafficMonitor
8a3a53607169c3a7e9f528658d0481f352a54b0d
4396be98cf843f91c2e99a41b1c701106ba4415d
refs/heads/master
2020-05-29T16:43:20.046000
2010-09-15T21:11:19
2010-09-15T21:11:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.github.bcap.trafficmonitor.business; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.xpath.XPathExpressionException; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.SAXException; import com.github.bcap.trafficmonitor.entity.Road; import com.github.bcap.trafficmonitor.entity.RoadWay; import com.github.bcap.trafficmonitor.entity.RoadWayMark; import com.github.bcap.trafficmonitor.entity.RoadWayTraffic; import com.github.bcap.trafficmonitor.entity.TrafficCondition; import com.github.bcap.trafficmonitor.exception.ExtractorException; public class RoadWayExtractor extends Extractor { private static final String ROADWAY_NAME_XPATH = "/html/body//div[@id='principal']/h3[${id}]/text()"; private static final String ROADMARK_NAME_XPATH = "/html/body//div[${id}]/table[@class='corredores']//td[1]/a/text()"; private static final String ROADMARK_CONDITION_XPATH = "/html/body//div[${id}]/table[@class='corredores']//td[2]/span/text()"; public void extractRoadWays(final Road road) throws ExtractorException { try { final Document htmlDoc = this.htmlParser.parseHtml(new URL(road.getLink())); final RoadWay outgoingRoadWay = this.extractFullRoadWay(htmlDoc, 1, 3); final RoadWay incomingRoadWay = this.extractFullRoadWay(htmlDoc, 2, 5); if (outgoingRoadWay != null) { outgoingRoadWay.setRoad(road); } if (incomingRoadWay != null) { incomingRoadWay.setRoad(road); } road.setOutgoingRoadWay(outgoingRoadWay); road.setIncomingRoadWay(incomingRoadWay); } catch (final MalformedURLException e) { throw new ExtractorException("configured road url is wrong: " + road.getLink(), e); } catch (final URISyntaxException e) { throw new ExtractorException("configured road url is wrong: " + road.getLink(), e); } catch (final SAXException e) { throw new ExtractorException("Could not parse html on this url: " + road.getLink(), e); } catch (final IOException e) { throw new ExtractorException("IOException while trying to parse the html on this url: " + road.getLink(), e); } } private RoadWay extractFullRoadWay(final Document htmlDoc, final Integer roadWayNameId, final Integer roadWayMarksId) throws ExtractorException { final RoadWay roadWay = this.extractRoadWay(htmlDoc, roadWayNameId); if (roadWay != null) { roadWay.setRoadWayMarks(this.extractRoadWayMarks(htmlDoc, roadWay, roadWayMarksId)); } return roadWay; } protected RoadWay extractRoadWay(final Document htmlDoc, final Integer roadWayNameId) throws ExtractorException { try { final Map<String, Object> variables = new HashMap<String, Object>(); variables.put("id", roadWayNameId); RoadWay roadWay = null; final NodeList nodes = this.selectNodes(htmlDoc, ROADWAY_NAME_XPATH, variables); if (nodes.getLength() > 0) { final String roadWayName = ((Text) nodes.item(0)).getWholeText().trim(); roadWay = new RoadWay(); roadWay.setName(roadWayName); } return roadWay; } catch (final XPathExpressionException e) { throw new ExtractorException("Road way xpath expression " + ROADWAY_NAME_XPATH + " is wrong!", e); } } protected List<RoadWayMark> extractRoadWayMarks(final Document htmlDoc, final RoadWay roadWay, final Integer roadWayMarksId) throws ExtractorException { final Map<String, Object> variables = new HashMap<String, Object>(); variables.put("id", roadWayMarksId); NodeList roadWayMarkNames; NodeList roadWayMarkConditions; try { roadWayMarkNames = this.selectNodes(htmlDoc, ROADMARK_NAME_XPATH, variables); } catch (final XPathExpressionException e) { throw new ExtractorException("RoadWayMark xpath expression " + ROADWAY_NAME_XPATH + " is wrong!", e); } try { roadWayMarkConditions = this.selectNodes(htmlDoc, ROADMARK_CONDITION_XPATH, variables); } catch (final XPathExpressionException e) { throw new ExtractorException("RoadWayMark xpath expression " + ROADMARK_CONDITION_XPATH + " is wrong!", e); } final List<RoadWayMark> result = new ArrayList<RoadWayMark>(); for (int i = 0; i < roadWayMarkNames.getLength(); i++) { final String roadWayName = ((Text) roadWayMarkNames.item(i)).getWholeText().trim(); final String roadWayCondition = ((Text) roadWayMarkConditions.item(i)).getWholeText().trim(); final RoadWayMark mark = new RoadWayMark(); mark.setName(roadWayName); mark.setRoadWay(roadWay); final RoadWayTraffic traffic = new RoadWayTraffic(); traffic.setTrafficCondition(TrafficCondition.getBySiteString(roadWayCondition)); traffic.setMeasuredTime(Calendar.getInstance().getTime()); traffic.setRoadWayMark(mark); final List<RoadWayTraffic> measuredTraffics = new ArrayList<RoadWayTraffic>(); measuredTraffics.add(traffic); mark.setMeasuredTraffics(measuredTraffics); result.add(mark); } return result; } }
UTF-8
Java
5,079
java
RoadWayExtractor.java
Java
[]
null
[]
package com.github.bcap.trafficmonitor.business; import java.io.IOException; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.xpath.XPathExpressionException; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.SAXException; import com.github.bcap.trafficmonitor.entity.Road; import com.github.bcap.trafficmonitor.entity.RoadWay; import com.github.bcap.trafficmonitor.entity.RoadWayMark; import com.github.bcap.trafficmonitor.entity.RoadWayTraffic; import com.github.bcap.trafficmonitor.entity.TrafficCondition; import com.github.bcap.trafficmonitor.exception.ExtractorException; public class RoadWayExtractor extends Extractor { private static final String ROADWAY_NAME_XPATH = "/html/body//div[@id='principal']/h3[${id}]/text()"; private static final String ROADMARK_NAME_XPATH = "/html/body//div[${id}]/table[@class='corredores']//td[1]/a/text()"; private static final String ROADMARK_CONDITION_XPATH = "/html/body//div[${id}]/table[@class='corredores']//td[2]/span/text()"; public void extractRoadWays(final Road road) throws ExtractorException { try { final Document htmlDoc = this.htmlParser.parseHtml(new URL(road.getLink())); final RoadWay outgoingRoadWay = this.extractFullRoadWay(htmlDoc, 1, 3); final RoadWay incomingRoadWay = this.extractFullRoadWay(htmlDoc, 2, 5); if (outgoingRoadWay != null) { outgoingRoadWay.setRoad(road); } if (incomingRoadWay != null) { incomingRoadWay.setRoad(road); } road.setOutgoingRoadWay(outgoingRoadWay); road.setIncomingRoadWay(incomingRoadWay); } catch (final MalformedURLException e) { throw new ExtractorException("configured road url is wrong: " + road.getLink(), e); } catch (final URISyntaxException e) { throw new ExtractorException("configured road url is wrong: " + road.getLink(), e); } catch (final SAXException e) { throw new ExtractorException("Could not parse html on this url: " + road.getLink(), e); } catch (final IOException e) { throw new ExtractorException("IOException while trying to parse the html on this url: " + road.getLink(), e); } } private RoadWay extractFullRoadWay(final Document htmlDoc, final Integer roadWayNameId, final Integer roadWayMarksId) throws ExtractorException { final RoadWay roadWay = this.extractRoadWay(htmlDoc, roadWayNameId); if (roadWay != null) { roadWay.setRoadWayMarks(this.extractRoadWayMarks(htmlDoc, roadWay, roadWayMarksId)); } return roadWay; } protected RoadWay extractRoadWay(final Document htmlDoc, final Integer roadWayNameId) throws ExtractorException { try { final Map<String, Object> variables = new HashMap<String, Object>(); variables.put("id", roadWayNameId); RoadWay roadWay = null; final NodeList nodes = this.selectNodes(htmlDoc, ROADWAY_NAME_XPATH, variables); if (nodes.getLength() > 0) { final String roadWayName = ((Text) nodes.item(0)).getWholeText().trim(); roadWay = new RoadWay(); roadWay.setName(roadWayName); } return roadWay; } catch (final XPathExpressionException e) { throw new ExtractorException("Road way xpath expression " + ROADWAY_NAME_XPATH + " is wrong!", e); } } protected List<RoadWayMark> extractRoadWayMarks(final Document htmlDoc, final RoadWay roadWay, final Integer roadWayMarksId) throws ExtractorException { final Map<String, Object> variables = new HashMap<String, Object>(); variables.put("id", roadWayMarksId); NodeList roadWayMarkNames; NodeList roadWayMarkConditions; try { roadWayMarkNames = this.selectNodes(htmlDoc, ROADMARK_NAME_XPATH, variables); } catch (final XPathExpressionException e) { throw new ExtractorException("RoadWayMark xpath expression " + ROADWAY_NAME_XPATH + " is wrong!", e); } try { roadWayMarkConditions = this.selectNodes(htmlDoc, ROADMARK_CONDITION_XPATH, variables); } catch (final XPathExpressionException e) { throw new ExtractorException("RoadWayMark xpath expression " + ROADMARK_CONDITION_XPATH + " is wrong!", e); } final List<RoadWayMark> result = new ArrayList<RoadWayMark>(); for (int i = 0; i < roadWayMarkNames.getLength(); i++) { final String roadWayName = ((Text) roadWayMarkNames.item(i)).getWholeText().trim(); final String roadWayCondition = ((Text) roadWayMarkConditions.item(i)).getWholeText().trim(); final RoadWayMark mark = new RoadWayMark(); mark.setName(roadWayName); mark.setRoadWay(roadWay); final RoadWayTraffic traffic = new RoadWayTraffic(); traffic.setTrafficCondition(TrafficCondition.getBySiteString(roadWayCondition)); traffic.setMeasuredTime(Calendar.getInstance().getTime()); traffic.setRoadWayMark(mark); final List<RoadWayTraffic> measuredTraffics = new ArrayList<RoadWayTraffic>(); measuredTraffics.add(traffic); mark.setMeasuredTraffics(measuredTraffics); result.add(mark); } return result; } }
5,079
0.750935
0.748376
131
37.778625
36.29739
153
false
false
0
0
0
0
0
0
2.328244
false
false
14
ca1574669f132ce38ec632bbb6f0d58d5a27b2b5
27,427,661,188,981
8460f104842057e869062d53e0e0878b05868e5a
/DocteurWho/src/test/java/com/wildcodeschool/DocteurWho/DocteurWhoApplicationTests.java
650c53c91c187da36e9eaf43e1d60bc3d68c5503
[]
no_license
mixheaven/java-Aware
https://github.com/mixheaven/java-Aware
edf185f545e169ffeea1a94dd031c2d4604c0596
39a1517b102e893adc140d62971fcfddb591a928
refs/heads/master
2020-08-22T14:51:35.950000
2019-11-03T13:42:50
2019-11-03T13:42:50
216,420,152
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.wildcodeschool.DocteurWho; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class DocteurWhoApplicationTests { @Test void contextLoads() { } }
UTF-8
Java
225
java
DocteurWhoApplicationTests.java
Java
[]
null
[]
package com.wildcodeschool.DocteurWho; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class DocteurWhoApplicationTests { @Test void contextLoads() { } }
225
0.8
0.8
13
16.307692
18.910252
60
false
false
0
0
0
0
0
0
0.461538
false
false
14
1d8c3412d6e5da76f2ec71d6352eb59d2dfbe5e9
26,869,315,432,613
430c5db069af711590a25c2084592783b2735ef2
/app/src/main/java/com/android/erp/CategoriesActivity.java
3f7dd5e6b771692fb96a13e25fc010da5554914f
[]
no_license
mirzemehdi/smmerp
https://github.com/mirzemehdi/smmerp
ebe57c0175eb42978d0f71eaa1d9cdcf8c103870
4dfc6779c86a5c9fa55517da19d89ebf5dc26d33
refs/heads/master
2020-07-09T15:05:25.917000
2019-08-23T13:34:36
2019-08-23T13:34:36
204,004,804
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.android.erp; import android.animation.ArgbEvaluator; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Typeface; import android.support.design.widget.AppBarLayout; import android.support.design.widget.FloatingActionButton; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.PopupMenu; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.android.erp.Adapter.AllDataAdapter; import com.android.erp.Models.AllDataModel; import com.android.erp.Models.PagerModel; import com.android.erp.Models.TitleChild; import com.android.erp.Network.ApiService; import com.android.erp.Network.Response.CategoriesResponse; import com.android.erp.Network.Response.HomeResponse; import com.android.erp.Network.RetrofitClient; import com.android.erp.Utils.CardPagerAdapter; import com.android.erp.Utils.GeneralUtils; import com.android.erp.Utils.ShadowTransformer; import com.whiteelephant.monthpicker.MonthPickerDialog; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; public class CategoriesActivity extends AppCompatActivity { private AppBarLayout appBarLayout; private Toolbar toolbar; private ImageButton back; private TextView title,packet,lang,date,static_date; private RecyclerView recyclerView; private AllDataAdapter allDataAdapter; private List<CategoriesResponse> list; private ViewPager viewPager; private CardPagerAdapter mCardAdapter; private ArgbEvaluator argbEvaluator = new ArgbEvaluator(); private ProgressBar categoriesProgress; private FloatingActionButton fab; private PopupMenu p; private String month,year,day; private Calendar now; private String userId,categoryId; private Disposable disposable; private static int currentItem; private boolean checkAz,checkEn,checkRu,isAdmin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_categories); Intent intent = getIntent(); userId = intent.getStringExtra("userId"); categoryId = intent.getStringExtra("categoryId"); isAdmin=getSharedPreferences("USER",MODE_PRIVATE).getBoolean("isAdmin",false); checkAz = intent.getBooleanExtra("checkAz",false); checkEn = intent.getBooleanExtra("checkEn",false); checkRu = intent.getBooleanExtra("checkRu",false); currentItem=Integer.parseInt(categoryId); now = Calendar.getInstance(); day = String.valueOf(now.get(Calendar.DATE)); year = String.valueOf(now.get(Calendar.YEAR)); month = String.valueOf(now.get(Calendar.MONTH) + 1); initData(); setClicks(); initViewPager(); if (now.get(Calendar.MONTH) == 0 ){ date.setText(getResources().getString(R.string.janury)); }else if (now.get(Calendar.MONTH) == 1){ date.setText(getResources().getString(R.string.february)); }else if (now.get(Calendar.MONTH) == 2){ date.setText(getResources().getString(R.string.march)); }else if (now.get(Calendar.MONTH) == 3){ date.setText(getResources().getString(R.string.april)); }else if (now.get(Calendar.MONTH) == 4){ date.setText(getResources().getString(R.string.may)); }else if (now.get(Calendar.MONTH) == 5){ date.setText(getResources().getString(R.string.june)); }else if (now.get(Calendar.MONTH) == 6){ date.setText(getResources().getString(R.string.july)); }else if (now.get(Calendar.MONTH) == 7){ date.setText(getResources().getString(R.string.august)); }else if (now.get(Calendar.MONTH) == 8){ date.setText(getResources().getString(R.string.september)); }else if (now.get(Calendar.MONTH) == 9){ date.setText(getResources().getString(R.string.october)); }else if (now.get(Calendar.MONTH) == 10){ date.setText(getResources().getString(R.string.november)); }else if (now.get(Calendar.MONTH) == 11){ date.setText(getResources().getString(R.string.december)); } categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); fetchData(categoryId,month,year); } private void initViewPager() { ArrayList<TitleChild> list = new ArrayList<>(); // ArrayList<String> lists = new ArrayList<>(); list=getIntent().getParcelableArrayListExtra("childList"); // list = (ArrayList<String>)getIntent().getSerializableExtra("myList"); // lists = (ArrayList<String>)getIntent().getSerializableExtra("myLists"); List<PagerModel> pagerModels = new ArrayList<>(); for (int i = 0;i<list.size();i++){ Log.d("listSize",list.size()+" "); TitleChild child=list.get(i); pagerModels.add(new PagerModel(child.getName(),child.getImgurl())); } // pagerModels.add(new PagerModel("Twitter","https://images.vexels.com/media/users/3/137419/isolated/preview/b1a3fab214230557053ed1c4bf17b46c-twitter-icon-logo-by-vexels.png")); // pagerModels.add(new PagerModel("Instagram","http://pluspng.com/img-png/instagram-png-instagram-png-logo-1455.png")); // pagerModels.add(new PagerModel("Facebook","https://images.vexels.com/media/users/3/137253/isolated/preview/90dd9f12fdd1eefb8c8976903944c026-facebook-icon-logo-by-vexels.png")); // pagerModels.add(new PagerModel("Linkedin","https://images.vexels.com/media/users/3/137382/isolated/preview/c59b2807ea44f0d70f41ca73c61d281d-linkedin-icon-logo-by-vexels.png")); //fetchData(String.valueOf(categoryId),month,year); if (currentItem<5){ currentItem-=1; } else { if (currentItem<8) currentItem-=6; else currentItem-=9; } mCardAdapter = new CardPagerAdapter(currentItem); for (PagerModel mservice :pagerModels){ mCardAdapter.addCardItem(mservice,getApplicationContext(), GeneralUtils.convertDpToPixel(2)); } ShadowTransformer fragmentCardShadowTransformer = new ShadowTransformer(viewPager, mCardAdapter,this); fragmentCardShadowTransformer.enableScaling(true); viewPager.setAdapter(mCardAdapter); viewPager.setPageTransformer(true, fragmentCardShadowTransformer); viewPager.setOffscreenPageLimit(4); viewPager.setCurrentItem(currentItem,true); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int i) { //categoryId=getIntent().getStringExtra("categoryId"); Log.d("categoryIdI",categoryId); if (categoryId.equals("1") || categoryId.equals("2") || categoryId.equals("4") || categoryId.equals("3")){ categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); /*if (categoryId.equals("1")){ fetchData("3"); }else if (categoryId.equals("2")){ fetchData("1"); }*/ switch (i){ case 0: currentItem =1; categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); fetchData(String.valueOf(currentItem),month,year); break; case 1: currentItem =2; categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); fetchData(String.valueOf(currentItem),month,year); break; case 2: currentItem =3; categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); fetchData(String.valueOf(currentItem),month,year); break; case 3: currentItem =4; categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); fetchData(String.valueOf(currentItem),month,year); break; } } else if (categoryId.equals("6") || categoryId.equals("7")){ categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); /* if (categoryId.equals("6")){ fetchData("6"); } else if (categoryId.equals("7")) { fetchData("7"); }*/ switch (i){ case 0: currentItem =6; categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); fetchData(String.valueOf(currentItem),month,year); break; case 1: categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); currentItem =7; fetchData(String.valueOf(currentItem),month,year); break; } } else if (categoryId.equals("9")){ Log.d("SmsClicked","Yes"); categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); currentItem = 9; fetchData(String.valueOf(currentItem),month,year); } categoryId=String.valueOf(currentItem); } @Override public void onPageScrollStateChanged(int i) { } }); } private String capitalize(String word){ return word.substring(0,1).toUpperCase() + word.substring(1); } private void fetchData(String categoryId,String month,String year) { ApiService service = new RetrofitClient().create(); Observable<List<CategoriesResponse>> get = null; get = service.getPosts(userId,categoryId,month,year); disposable = get .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnError(error -> GeneralUtils.largeLog("doOnErrorEventsFragmentCall", error.getMessage())) .doOnComplete(() -> { categoriesProgress.setVisibility(View.GONE); recyclerView.setVisibility(View.VISIBLE); allDataAdapter.notifyDataSetChanged(); }) .subscribe(this::initRecycler, Throwable::getMessage); } private void setClicks(){ p = new PopupMenu(CategoriesActivity.this,lang); p.getMenuInflater().inflate(R.menu.main_menu,p.getMenu()); MenuItem az = p.getMenu().findItem(R.id.az); MenuItem en = p.getMenu().findItem(R.id.en); MenuItem ru = p.getMenu().findItem(R.id.ru); az.setVisible(false); en.setVisible(false); ru.setVisible(false); SharedPreferences prefs = getSharedPreferences("LANG", MODE_PRIVATE); String langs = prefs.getString("lang", ""); if (checkAz){ if (langs.equals("AZ")){ az.setVisible(false); }else { az.setVisible(true); } } if (checkEn){ if (langs.equals("EN")){ en.setVisible(false); }else { en.setVisible(true); } } if (checkRu){ if (langs.equals("RU")){ ru.setVisible(false); }else { ru.setVisible(true); } } lang.setText(langs.toUpperCase()); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(CategoriesActivity.this, PostDetailsActivity.class); intent.putExtra("userId",userId); intent.putExtra("categoryId",categoryId); intent.putExtra("checkAz",checkAz); intent.putExtra("checkEn",checkEn); intent.putExtra("checkRu",checkRu); startActivity(intent); } }); lang.setOnClickListener(v -> { p.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { SharedPreferences.Editor editor = getSharedPreferences("LANG", MODE_PRIVATE).edit(); editor.putString("lang",String.valueOf(menuItem.getTitle())); editor.apply(); SharedPreferences prefs = getSharedPreferences("LANG", MODE_PRIVATE); String langss = prefs.getString("lang", ""); lang.setText(langss.toUpperCase()); if (langss.equals("AZ")){ az.setVisible(false); if (checkEn){ en.setVisible(true); } if (checkRu){ ru.setVisible(true); } }else if (langss.equals("EN")){ en.setVisible(false); if (checkAz){ az.setVisible(true); } if (checkRu){ ru.setVisible(true); } }else if (langss.equals("RU")){ ru.setVisible(false); if (checkAz){ az.setVisible(true); } if (checkEn){ en.setVisible(true); } } return true; } }); p.show(); }); back.setOnClickListener(v -> finish()); date.setOnClickListener(v -> { MonthPickerDialog.Builder builder = new MonthPickerDialog.Builder(CategoriesActivity.this, new MonthPickerDialog.OnDateSetListener() { @Override public void onDateSet(int selectedMonth, int selectedYear) { Log.d("sddsad",selectedMonth + " " + selectedYear); month = String.valueOf(selectedMonth+1); year = String.valueOf(selectedYear); if (selectedMonth == 0 ){ date.setText(getResources().getString(R.string.janury)); }else if (selectedMonth == 1){ date.setText(getResources().getString(R.string.february)); }else if (selectedMonth == 2){ date.setText(getResources().getString(R.string.march)); }else if (selectedMonth == 3){ date.setText(getResources().getString(R.string.april)); }else if (selectedMonth == 4){ date.setText(getResources().getString(R.string.may)); }else if (selectedMonth == 5){ date.setText(getResources().getString(R.string.june)); }else if (selectedMonth == 6){ date.setText(getResources().getString(R.string.july)); }else if (selectedMonth == 7){ date.setText(getResources().getString(R.string.august)); }else if (selectedMonth == 8){ date.setText(getResources().getString(R.string.september)); }else if (selectedMonth == 9){ date.setText(getResources().getString(R.string.october)); }else if (selectedMonth == 10){ date.setText(getResources().getString(R.string.november)); }else if (selectedMonth == 11){ date.setText(getResources().getString(R.string.december)); } categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); fetchData(String.valueOf(currentItem),month,year); Log.d("sf",month + " " + selectedYear); } }, now.get(Calendar.YEAR), now.get(Calendar.MONTH)); builder.setActivatedMonth(Calendar.JULY) .setMinYear((now.get(Calendar.YEAR)-10)) .setActivatedYear(Integer.parseInt(year)) .setMaxYear((now.get(Calendar.YEAR)+10)) .setTitle("Select trading month") // .setMaxMonth(Calendar.OCTOBER) // .setYearRange(1890, 1890) // .setMonthAndYearRange(Calendar.FEBRUARY, Calendar.OCTOBER, 1890, 1890) //.showMonthOnly() // .showYearOnly() .setOnMonthChangedListener(new MonthPickerDialog.OnMonthChangedListener() { @Override public void onMonthChanged(int selectedMonth) { // month = String.valueOf(selectedMonth+1); // if (selectedMonth == 0 ){ // date.setText(getResources().getString(R.string.janury)); // }else if (selectedMonth == 1){ // date.setText(getResources().getString(R.string.february)); // }else if (selectedMonth == 2){ // date.setText(getResources().getString(R.string.march)); // }else if (selectedMonth == 3){ // date.setText(getResources().getString(R.string.april)); // }else if (selectedMonth == 4){ // date.setText(getResources().getString(R.string.may)); // }else if (selectedMonth == 5){ // date.setText(getResources().getString(R.string.june)); // }else if (selectedMonth == 6){ // date.setText(getResources().getString(R.string.july)); // }else if (selectedMonth == 7){ // date.setText(getResources().getString(R.string.august)); // }else if (selectedMonth == 8){ // date.setText(getResources().getString(R.string.september)); // }else if (selectedMonth == 9){ // date.setText(getResources().getString(R.string.october)); // }else if (selectedMonth == 10){ // date.setText(getResources().getString(R.string.november)); // }else if (selectedMonth == 11){ // date.setText(getResources().getString(R.string.december)); // } // progressBar.setVisibility(View.VISIBLE); // main_recycler.setVisibility(View.INVISIBLE); // fetchData(month,year); } }) .setOnYearChangedListener(new MonthPickerDialog.OnYearChangedListener() { @Override public void onYearChanged(int selectedYear) { // year = String.valueOf(selectedYear); // fetchData(month,year); } }) .build() .show(); //showDialog(DATE_DIALOG_ID); //calendarShow(); // PopupMenu p = new PopupMenu(HomeActivity.this,date); // p.getMenuInflater().inflate(R.menu.date_menu,p.getMenu()); // p.setOnMenuItemClickListener(item -> { // date.setText(item.getTitle()); // return true; // }); // p.show(); }); } private void initData(){ fab = findViewById(R.id.postAddFab); viewPager = findViewById(R.id.viewPager); categoriesProgress = findViewById(R.id.categoriesProgress); recyclerView = findViewById(R.id.categories_recycler); appBarLayout = findViewById(R.id.appBarLayCategories); toolbar = findViewById(R.id.toolbarCategories); back = findViewById(R.id.tb_back_categories); title = findViewById(R.id.toolbar_categories_title); packet = findViewById(R.id.packet_text_categories); lang = findViewById(R.id.lang_categories); date = findViewById(R.id.date_categories); static_date = findViewById(R.id.static_date_categories); setSupportActionBar(toolbar); Typeface avenir_light = Typeface.createFromAsset(getAssets(),"fonts/AvenirLight.ttf"); Typeface avenir_black = Typeface.createFromAsset(getAssets(),"fonts/AvenirBlack.ttf"); Typeface avenir_medium = Typeface.createFromAsset(getAssets(),"fonts/AvenirMedium.ttf"); date.setTypeface(avenir_medium); static_date.setTypeface(avenir_light); title.setTypeface(avenir_light); packet.setTypeface(avenir_black); lang.setTypeface(avenir_light); if (!isAdmin) fab.hide(); } @Override protected void onResume() { super.onResume(); //fetchData(String.valueOf(currentItem),month,year); Log.d("dsa","resune"); } @Override protected void onRestart() { super.onRestart(); categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); if (currentItem ==0){ currentItem = 1; } fetchData(String.valueOf(currentItem),month,year); Log.d("dasdas",String.valueOf(currentItem)); } private void initRecycler(List<CategoriesResponse> response){ recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setHasFixedSize(true); list = new ArrayList<>(); list = response; // for (int i =0;i<response.size();i++){ // boolean check = false; // if (response.get(i).getChecking().equals("0")){ // check =false; // }else { // check = true; // } // list.add(new AllDataModel(response.get(i).getDate(),check)); // } allDataAdapter = new AllDataAdapter(this,list,checkAz,checkEn,checkRu); recyclerView.setAdapter(allDataAdapter); categoriesProgress.setVisibility(View.GONE); recyclerView.setVisibility(View.VISIBLE); } @Override protected void onDestroy() { super.onDestroy(); if (disposable != null) disposable.dispose(); } }
UTF-8
Java
24,816
java
CategoriesActivity.java
Java
[]
null
[]
package com.android.erp; import android.animation.ArgbEvaluator; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Typeface; import android.support.design.widget.AppBarLayout; import android.support.design.widget.FloatingActionButton; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.PopupMenu; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.android.erp.Adapter.AllDataAdapter; import com.android.erp.Models.AllDataModel; import com.android.erp.Models.PagerModel; import com.android.erp.Models.TitleChild; import com.android.erp.Network.ApiService; import com.android.erp.Network.Response.CategoriesResponse; import com.android.erp.Network.Response.HomeResponse; import com.android.erp.Network.RetrofitClient; import com.android.erp.Utils.CardPagerAdapter; import com.android.erp.Utils.GeneralUtils; import com.android.erp.Utils.ShadowTransformer; import com.whiteelephant.monthpicker.MonthPickerDialog; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; public class CategoriesActivity extends AppCompatActivity { private AppBarLayout appBarLayout; private Toolbar toolbar; private ImageButton back; private TextView title,packet,lang,date,static_date; private RecyclerView recyclerView; private AllDataAdapter allDataAdapter; private List<CategoriesResponse> list; private ViewPager viewPager; private CardPagerAdapter mCardAdapter; private ArgbEvaluator argbEvaluator = new ArgbEvaluator(); private ProgressBar categoriesProgress; private FloatingActionButton fab; private PopupMenu p; private String month,year,day; private Calendar now; private String userId,categoryId; private Disposable disposable; private static int currentItem; private boolean checkAz,checkEn,checkRu,isAdmin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_categories); Intent intent = getIntent(); userId = intent.getStringExtra("userId"); categoryId = intent.getStringExtra("categoryId"); isAdmin=getSharedPreferences("USER",MODE_PRIVATE).getBoolean("isAdmin",false); checkAz = intent.getBooleanExtra("checkAz",false); checkEn = intent.getBooleanExtra("checkEn",false); checkRu = intent.getBooleanExtra("checkRu",false); currentItem=Integer.parseInt(categoryId); now = Calendar.getInstance(); day = String.valueOf(now.get(Calendar.DATE)); year = String.valueOf(now.get(Calendar.YEAR)); month = String.valueOf(now.get(Calendar.MONTH) + 1); initData(); setClicks(); initViewPager(); if (now.get(Calendar.MONTH) == 0 ){ date.setText(getResources().getString(R.string.janury)); }else if (now.get(Calendar.MONTH) == 1){ date.setText(getResources().getString(R.string.february)); }else if (now.get(Calendar.MONTH) == 2){ date.setText(getResources().getString(R.string.march)); }else if (now.get(Calendar.MONTH) == 3){ date.setText(getResources().getString(R.string.april)); }else if (now.get(Calendar.MONTH) == 4){ date.setText(getResources().getString(R.string.may)); }else if (now.get(Calendar.MONTH) == 5){ date.setText(getResources().getString(R.string.june)); }else if (now.get(Calendar.MONTH) == 6){ date.setText(getResources().getString(R.string.july)); }else if (now.get(Calendar.MONTH) == 7){ date.setText(getResources().getString(R.string.august)); }else if (now.get(Calendar.MONTH) == 8){ date.setText(getResources().getString(R.string.september)); }else if (now.get(Calendar.MONTH) == 9){ date.setText(getResources().getString(R.string.october)); }else if (now.get(Calendar.MONTH) == 10){ date.setText(getResources().getString(R.string.november)); }else if (now.get(Calendar.MONTH) == 11){ date.setText(getResources().getString(R.string.december)); } categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); fetchData(categoryId,month,year); } private void initViewPager() { ArrayList<TitleChild> list = new ArrayList<>(); // ArrayList<String> lists = new ArrayList<>(); list=getIntent().getParcelableArrayListExtra("childList"); // list = (ArrayList<String>)getIntent().getSerializableExtra("myList"); // lists = (ArrayList<String>)getIntent().getSerializableExtra("myLists"); List<PagerModel> pagerModels = new ArrayList<>(); for (int i = 0;i<list.size();i++){ Log.d("listSize",list.size()+" "); TitleChild child=list.get(i); pagerModels.add(new PagerModel(child.getName(),child.getImgurl())); } // pagerModels.add(new PagerModel("Twitter","https://images.vexels.com/media/users/3/137419/isolated/preview/b1a3fab214230557053ed1c4bf17b46c-twitter-icon-logo-by-vexels.png")); // pagerModels.add(new PagerModel("Instagram","http://pluspng.com/img-png/instagram-png-instagram-png-logo-1455.png")); // pagerModels.add(new PagerModel("Facebook","https://images.vexels.com/media/users/3/137253/isolated/preview/90dd9f12fdd1eefb8c8976903944c026-facebook-icon-logo-by-vexels.png")); // pagerModels.add(new PagerModel("Linkedin","https://images.vexels.com/media/users/3/137382/isolated/preview/c59b2807ea44f0d70f41ca73c61d281d-linkedin-icon-logo-by-vexels.png")); //fetchData(String.valueOf(categoryId),month,year); if (currentItem<5){ currentItem-=1; } else { if (currentItem<8) currentItem-=6; else currentItem-=9; } mCardAdapter = new CardPagerAdapter(currentItem); for (PagerModel mservice :pagerModels){ mCardAdapter.addCardItem(mservice,getApplicationContext(), GeneralUtils.convertDpToPixel(2)); } ShadowTransformer fragmentCardShadowTransformer = new ShadowTransformer(viewPager, mCardAdapter,this); fragmentCardShadowTransformer.enableScaling(true); viewPager.setAdapter(mCardAdapter); viewPager.setPageTransformer(true, fragmentCardShadowTransformer); viewPager.setOffscreenPageLimit(4); viewPager.setCurrentItem(currentItem,true); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int i) { //categoryId=getIntent().getStringExtra("categoryId"); Log.d("categoryIdI",categoryId); if (categoryId.equals("1") || categoryId.equals("2") || categoryId.equals("4") || categoryId.equals("3")){ categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); /*if (categoryId.equals("1")){ fetchData("3"); }else if (categoryId.equals("2")){ fetchData("1"); }*/ switch (i){ case 0: currentItem =1; categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); fetchData(String.valueOf(currentItem),month,year); break; case 1: currentItem =2; categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); fetchData(String.valueOf(currentItem),month,year); break; case 2: currentItem =3; categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); fetchData(String.valueOf(currentItem),month,year); break; case 3: currentItem =4; categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); fetchData(String.valueOf(currentItem),month,year); break; } } else if (categoryId.equals("6") || categoryId.equals("7")){ categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); /* if (categoryId.equals("6")){ fetchData("6"); } else if (categoryId.equals("7")) { fetchData("7"); }*/ switch (i){ case 0: currentItem =6; categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); fetchData(String.valueOf(currentItem),month,year); break; case 1: categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); currentItem =7; fetchData(String.valueOf(currentItem),month,year); break; } } else if (categoryId.equals("9")){ Log.d("SmsClicked","Yes"); categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); currentItem = 9; fetchData(String.valueOf(currentItem),month,year); } categoryId=String.valueOf(currentItem); } @Override public void onPageScrollStateChanged(int i) { } }); } private String capitalize(String word){ return word.substring(0,1).toUpperCase() + word.substring(1); } private void fetchData(String categoryId,String month,String year) { ApiService service = new RetrofitClient().create(); Observable<List<CategoriesResponse>> get = null; get = service.getPosts(userId,categoryId,month,year); disposable = get .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnError(error -> GeneralUtils.largeLog("doOnErrorEventsFragmentCall", error.getMessage())) .doOnComplete(() -> { categoriesProgress.setVisibility(View.GONE); recyclerView.setVisibility(View.VISIBLE); allDataAdapter.notifyDataSetChanged(); }) .subscribe(this::initRecycler, Throwable::getMessage); } private void setClicks(){ p = new PopupMenu(CategoriesActivity.this,lang); p.getMenuInflater().inflate(R.menu.main_menu,p.getMenu()); MenuItem az = p.getMenu().findItem(R.id.az); MenuItem en = p.getMenu().findItem(R.id.en); MenuItem ru = p.getMenu().findItem(R.id.ru); az.setVisible(false); en.setVisible(false); ru.setVisible(false); SharedPreferences prefs = getSharedPreferences("LANG", MODE_PRIVATE); String langs = prefs.getString("lang", ""); if (checkAz){ if (langs.equals("AZ")){ az.setVisible(false); }else { az.setVisible(true); } } if (checkEn){ if (langs.equals("EN")){ en.setVisible(false); }else { en.setVisible(true); } } if (checkRu){ if (langs.equals("RU")){ ru.setVisible(false); }else { ru.setVisible(true); } } lang.setText(langs.toUpperCase()); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(CategoriesActivity.this, PostDetailsActivity.class); intent.putExtra("userId",userId); intent.putExtra("categoryId",categoryId); intent.putExtra("checkAz",checkAz); intent.putExtra("checkEn",checkEn); intent.putExtra("checkRu",checkRu); startActivity(intent); } }); lang.setOnClickListener(v -> { p.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { SharedPreferences.Editor editor = getSharedPreferences("LANG", MODE_PRIVATE).edit(); editor.putString("lang",String.valueOf(menuItem.getTitle())); editor.apply(); SharedPreferences prefs = getSharedPreferences("LANG", MODE_PRIVATE); String langss = prefs.getString("lang", ""); lang.setText(langss.toUpperCase()); if (langss.equals("AZ")){ az.setVisible(false); if (checkEn){ en.setVisible(true); } if (checkRu){ ru.setVisible(true); } }else if (langss.equals("EN")){ en.setVisible(false); if (checkAz){ az.setVisible(true); } if (checkRu){ ru.setVisible(true); } }else if (langss.equals("RU")){ ru.setVisible(false); if (checkAz){ az.setVisible(true); } if (checkEn){ en.setVisible(true); } } return true; } }); p.show(); }); back.setOnClickListener(v -> finish()); date.setOnClickListener(v -> { MonthPickerDialog.Builder builder = new MonthPickerDialog.Builder(CategoriesActivity.this, new MonthPickerDialog.OnDateSetListener() { @Override public void onDateSet(int selectedMonth, int selectedYear) { Log.d("sddsad",selectedMonth + " " + selectedYear); month = String.valueOf(selectedMonth+1); year = String.valueOf(selectedYear); if (selectedMonth == 0 ){ date.setText(getResources().getString(R.string.janury)); }else if (selectedMonth == 1){ date.setText(getResources().getString(R.string.february)); }else if (selectedMonth == 2){ date.setText(getResources().getString(R.string.march)); }else if (selectedMonth == 3){ date.setText(getResources().getString(R.string.april)); }else if (selectedMonth == 4){ date.setText(getResources().getString(R.string.may)); }else if (selectedMonth == 5){ date.setText(getResources().getString(R.string.june)); }else if (selectedMonth == 6){ date.setText(getResources().getString(R.string.july)); }else if (selectedMonth == 7){ date.setText(getResources().getString(R.string.august)); }else if (selectedMonth == 8){ date.setText(getResources().getString(R.string.september)); }else if (selectedMonth == 9){ date.setText(getResources().getString(R.string.october)); }else if (selectedMonth == 10){ date.setText(getResources().getString(R.string.november)); }else if (selectedMonth == 11){ date.setText(getResources().getString(R.string.december)); } categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); fetchData(String.valueOf(currentItem),month,year); Log.d("sf",month + " " + selectedYear); } }, now.get(Calendar.YEAR), now.get(Calendar.MONTH)); builder.setActivatedMonth(Calendar.JULY) .setMinYear((now.get(Calendar.YEAR)-10)) .setActivatedYear(Integer.parseInt(year)) .setMaxYear((now.get(Calendar.YEAR)+10)) .setTitle("Select trading month") // .setMaxMonth(Calendar.OCTOBER) // .setYearRange(1890, 1890) // .setMonthAndYearRange(Calendar.FEBRUARY, Calendar.OCTOBER, 1890, 1890) //.showMonthOnly() // .showYearOnly() .setOnMonthChangedListener(new MonthPickerDialog.OnMonthChangedListener() { @Override public void onMonthChanged(int selectedMonth) { // month = String.valueOf(selectedMonth+1); // if (selectedMonth == 0 ){ // date.setText(getResources().getString(R.string.janury)); // }else if (selectedMonth == 1){ // date.setText(getResources().getString(R.string.february)); // }else if (selectedMonth == 2){ // date.setText(getResources().getString(R.string.march)); // }else if (selectedMonth == 3){ // date.setText(getResources().getString(R.string.april)); // }else if (selectedMonth == 4){ // date.setText(getResources().getString(R.string.may)); // }else if (selectedMonth == 5){ // date.setText(getResources().getString(R.string.june)); // }else if (selectedMonth == 6){ // date.setText(getResources().getString(R.string.july)); // }else if (selectedMonth == 7){ // date.setText(getResources().getString(R.string.august)); // }else if (selectedMonth == 8){ // date.setText(getResources().getString(R.string.september)); // }else if (selectedMonth == 9){ // date.setText(getResources().getString(R.string.october)); // }else if (selectedMonth == 10){ // date.setText(getResources().getString(R.string.november)); // }else if (selectedMonth == 11){ // date.setText(getResources().getString(R.string.december)); // } // progressBar.setVisibility(View.VISIBLE); // main_recycler.setVisibility(View.INVISIBLE); // fetchData(month,year); } }) .setOnYearChangedListener(new MonthPickerDialog.OnYearChangedListener() { @Override public void onYearChanged(int selectedYear) { // year = String.valueOf(selectedYear); // fetchData(month,year); } }) .build() .show(); //showDialog(DATE_DIALOG_ID); //calendarShow(); // PopupMenu p = new PopupMenu(HomeActivity.this,date); // p.getMenuInflater().inflate(R.menu.date_menu,p.getMenu()); // p.setOnMenuItemClickListener(item -> { // date.setText(item.getTitle()); // return true; // }); // p.show(); }); } private void initData(){ fab = findViewById(R.id.postAddFab); viewPager = findViewById(R.id.viewPager); categoriesProgress = findViewById(R.id.categoriesProgress); recyclerView = findViewById(R.id.categories_recycler); appBarLayout = findViewById(R.id.appBarLayCategories); toolbar = findViewById(R.id.toolbarCategories); back = findViewById(R.id.tb_back_categories); title = findViewById(R.id.toolbar_categories_title); packet = findViewById(R.id.packet_text_categories); lang = findViewById(R.id.lang_categories); date = findViewById(R.id.date_categories); static_date = findViewById(R.id.static_date_categories); setSupportActionBar(toolbar); Typeface avenir_light = Typeface.createFromAsset(getAssets(),"fonts/AvenirLight.ttf"); Typeface avenir_black = Typeface.createFromAsset(getAssets(),"fonts/AvenirBlack.ttf"); Typeface avenir_medium = Typeface.createFromAsset(getAssets(),"fonts/AvenirMedium.ttf"); date.setTypeface(avenir_medium); static_date.setTypeface(avenir_light); title.setTypeface(avenir_light); packet.setTypeface(avenir_black); lang.setTypeface(avenir_light); if (!isAdmin) fab.hide(); } @Override protected void onResume() { super.onResume(); //fetchData(String.valueOf(currentItem),month,year); Log.d("dsa","resune"); } @Override protected void onRestart() { super.onRestart(); categoriesProgress.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.INVISIBLE); if (currentItem ==0){ currentItem = 1; } fetchData(String.valueOf(currentItem),month,year); Log.d("dasdas",String.valueOf(currentItem)); } private void initRecycler(List<CategoriesResponse> response){ recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setHasFixedSize(true); list = new ArrayList<>(); list = response; // for (int i =0;i<response.size();i++){ // boolean check = false; // if (response.get(i).getChecking().equals("0")){ // check =false; // }else { // check = true; // } // list.add(new AllDataModel(response.get(i).getDate(),check)); // } allDataAdapter = new AllDataAdapter(this,list,checkAz,checkEn,checkRu); recyclerView.setAdapter(allDataAdapter); categoriesProgress.setVisibility(View.GONE); recyclerView.setVisibility(View.VISIBLE); } @Override protected void onDestroy() { super.onDestroy(); if (disposable != null) disposable.dispose(); } }
24,816
0.547792
0.539773
573
42.308899
28.820995
186
false
false
0
0
0
0
74
0.008946
0.73822
false
false
14
948d6d0f37cbebb274c09bcf32165915335cdde7
15,049,565,435,867
3a517f7cf8e9183cde34f345459a6828c15c3317
/src/test/java/ch/alpine/tensor/mat/ev/TestHelper.java
e1beef54dbf213eb19725d24bd21f72eafdc6405
[]
no_license
datahaki/tensor
https://github.com/datahaki/tensor
766b3f8ad6bc0756edfd2e0f10ecbc27fa7cefa2
8b29f8c43ed8305accf0a6a5378213f38adb0a61
refs/heads/master
2023-09-03T05:51:04.681000
2023-08-24T11:04:53
2023-08-24T11:04:53
294,003,258
23
1
null
false
2022-09-15T00:43:39
2020-09-09T04:34:22
2022-06-24T17:11:43
2022-09-15T00:19:39
43,744
10
1
1
Java
false
false
// code by jph package ch.alpine.tensor.mat.ev; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertTrue; import ch.alpine.tensor.Tensor; import ch.alpine.tensor.alg.Dot; import ch.alpine.tensor.alg.Transpose; import ch.alpine.tensor.ext.Serialization; import ch.alpine.tensor.mat.Tolerance; import ch.alpine.tensor.sca.Chop; /* package */ enum TestHelper { ; public static void checkEquation(Tensor matrix, Eigensystem eigensystem) { checkEquation(matrix, eigensystem, Tolerance.CHOP); } public static void checkEquation(Tensor matrix, Eigensystem eigensystem, Chop chop) { assertDoesNotThrow(() -> Serialization.copy(eigensystem)); Tensor v = Transpose.of(eigensystem.vectors()); Tensor d = eigensystem.diagonalMatrix(); Tensor lhs = Dot.of(matrix, v); Tensor rhs = Dot.of(v, d); chop.requireClose(lhs, rhs); assertTrue(eigensystem.toString().startsWith("Eigensystem[")); } }
UTF-8
Java
992
java
TestHelper.java
Java
[ { "context": "// code by jph\npackage ch.alpine.tensor.mat.ev;\n\nimport static o", "end": 14, "score": 0.9965199828147888, "start": 11, "tag": "USERNAME", "value": "jph" } ]
null
[]
// code by jph package ch.alpine.tensor.mat.ev; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertTrue; import ch.alpine.tensor.Tensor; import ch.alpine.tensor.alg.Dot; import ch.alpine.tensor.alg.Transpose; import ch.alpine.tensor.ext.Serialization; import ch.alpine.tensor.mat.Tolerance; import ch.alpine.tensor.sca.Chop; /* package */ enum TestHelper { ; public static void checkEquation(Tensor matrix, Eigensystem eigensystem) { checkEquation(matrix, eigensystem, Tolerance.CHOP); } public static void checkEquation(Tensor matrix, Eigensystem eigensystem, Chop chop) { assertDoesNotThrow(() -> Serialization.copy(eigensystem)); Tensor v = Transpose.of(eigensystem.vectors()); Tensor d = eigensystem.diagonalMatrix(); Tensor lhs = Dot.of(matrix, v); Tensor rhs = Dot.of(v, d); chop.requireClose(lhs, rhs); assertTrue(eigensystem.toString().startsWith("Eigensystem[")); } }
992
0.748992
0.748992
29
33.206898
24.867065
87
false
false
0
0
0
0
0
0
0.896552
false
false
14
85ba08d6e23dbe3074ceecf3162abed6125052f1
9,002,251,487,947
ecd6c337a624772ef37ed72868cd6b7c28851a46
/util/src/test/java/edu/ucdenver/ccp/nlp/util/SpacedProperties_Test.java
7b43522dcd60fb807c778a779642ef39aad83e81
[]
no_license
croeder/ccp_nlp
https://github.com/croeder/ccp_nlp
78f71d445011a92c9ec0fcc56e79d538eaeb4e52
b93dc23c7700b35ee7d87a9c5631d173edecefbd
refs/heads/master
2016-09-06T14:58:25.449000
2014-08-20T20:24:45
2014-08-20T20:24:45
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Copyright (c) 2013, Regents of the University of Colorado All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Colorado nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.ucdenver.ccp.nlp.util; import static org.junit.Assert.assertEquals; import java.io.File; import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; import org.junit.Test; import org.junit.Before; import org.junit.After; public class SpacedProperties_Test { SpacedProperties sProps = null; @Before public void setup() { BasicConfigurator.configure(); sProps = new SpacedProperties("/connection.properties", "conn.ag"); } @Test public void test_1() { //conn.ag.reponame, medline-dev assertEquals("medline-dev", sProps.get("reponame")); //conn.ag.vendor, AG assertEquals("AG", sProps.get("vendor")); //conn.ag.username, roederc assertEquals("roederc", sProps.get("username")); //conn.ag.uri, http://192.168.167.128:10035 assertEquals("http://192.168.167.128:10035", sProps.get("uri")); //conn.ag.password, Anschutz09 assertEquals("PASSWORD", sProps.get("password")); } @After public void teardown() { } }
UTF-8
Java
2,534
java
SpacedProperties_Test.java
Java
[ { "context": "AG\", sProps.get(\"vendor\"));\n\n\t\t//conn.ag.username, roederc\n\t\tassertEquals(\"roederc\", sProps.get(\"username\"))", "end": 2239, "score": 0.9996922612190247, "start": 2232, "tag": "USERNAME", "value": "roederc" }, { "context": ");\n\n\t\t//conn.ag.username, roederc\n\t\tassertEquals(\"roederc\", sProps.get(\"username\"));\n\n\t\t//conn.ag.uri, http", "end": 2263, "score": 0.9997034072875977, "start": 2256, "tag": "USERNAME", "value": "roederc" }, { "context": "sProps.get(\"username\"));\n\n\t\t//conn.ag.uri, http://192.168.167.128:10035\n\t\tassertEquals(\"http://192.168.167.128:1003", "end": 2331, "score": 0.999664843082428, "start": 2316, "tag": "IP_ADDRESS", "value": "192.168.167.128" }, { "context": "tp://192.168.167.128:10035\n\t\tassertEquals(\"http://192.168.167.128:10035\", sProps.get(\"uri\"));\n\n\t\t//conn.ag.password", "end": 2376, "score": 0.9996480345726013, "start": 2361, "tag": "IP_ADDRESS", "value": "192.168.167.128" }, { "context": "10035\", sProps.get(\"uri\"));\n\n\t\t//conn.ag.password, Anschutz09\n\t\tassertEquals(\"PASSWORD\", sProps.get(\"password\")", "end": 2438, "score": 0.9958900213241577, "start": 2428, "tag": "PASSWORD", "value": "Anschutz09" } ]
null
[]
/* Copyright (c) 2013, Regents of the University of Colorado All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Colorado nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package edu.ucdenver.ccp.nlp.util; import static org.junit.Assert.assertEquals; import java.io.File; import org.apache.log4j.Logger; import org.apache.log4j.BasicConfigurator; import org.junit.Test; import org.junit.Before; import org.junit.After; public class SpacedProperties_Test { SpacedProperties sProps = null; @Before public void setup() { BasicConfigurator.configure(); sProps = new SpacedProperties("/connection.properties", "conn.ag"); } @Test public void test_1() { //conn.ag.reponame, medline-dev assertEquals("medline-dev", sProps.get("reponame")); //conn.ag.vendor, AG assertEquals("AG", sProps.get("vendor")); //conn.ag.username, roederc assertEquals("roederc", sProps.get("username")); //conn.ag.uri, http://192.168.167.128:10035 assertEquals("http://192.168.167.128:10035", sProps.get("uri")); //conn.ag.password, <PASSWORD> assertEquals("PASSWORD", sProps.get("password")); } @After public void teardown() { } }
2,534
0.762826
0.745856
74
33.243244
29.666985
81
false
false
0
0
0
0
0
0
1.148649
false
false
14
54b4d76b1ce071b2a9caf96ccaad1196868edb53
33,285,996,573,911
182e840b9f00a9313ea1b445a01b152e5f832c24
/src/com/company/NumberConverter.java
24373059610bd5169214fa6d86a0ef1803b65db2
[]
no_license
artemiy86/calc
https://github.com/artemiy86/calc
ce3e96655087dce1b343ed312ee42b3d982358ac
88542f9cd10db83aca2da37d10a6302453b94f02
refs/heads/master
2023-03-04T16:26:01.374000
2021-02-20T15:36:23
2021-02-20T15:36:23
340,688,872
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.company; import java.util.TreeMap; public class NumberConverter { private static String[] romanNumber = {"","I","II","III","IV","V","VI","VII","VIII","IX","X"}; private final static TreeMap<Integer, String> map = new TreeMap<Integer, String>(); static { map.put(100, "C"); map.put(90, "XC"); map.put(50, "L"); map.put(40, "XL"); map.put(10, "X"); map.put(9, "IX"); map.put(5, "V"); map.put(4, "IV"); map.put(1, "I"); } public static int toArabicNumber(String number){ for(int i=0;i<romanNumber.length;i++) { if (romanNumber[i].equals(number)) { return i; } } return 0; } public static String toRomanNumber(int number){ int numb = Math.abs(number); int i = map.floorKey(numb); if(numb == i) return map.get(numb); return map.get(i) + toRomanNumber(numb - i); } }
UTF-8
Java
991
java
NumberConverter.java
Java
[]
null
[]
package com.company; import java.util.TreeMap; public class NumberConverter { private static String[] romanNumber = {"","I","II","III","IV","V","VI","VII","VIII","IX","X"}; private final static TreeMap<Integer, String> map = new TreeMap<Integer, String>(); static { map.put(100, "C"); map.put(90, "XC"); map.put(50, "L"); map.put(40, "XL"); map.put(10, "X"); map.put(9, "IX"); map.put(5, "V"); map.put(4, "IV"); map.put(1, "I"); } public static int toArabicNumber(String number){ for(int i=0;i<romanNumber.length;i++) { if (romanNumber[i].equals(number)) { return i; } } return 0; } public static String toRomanNumber(int number){ int numb = Math.abs(number); int i = map.floorKey(numb); if(numb == i) return map.get(numb); return map.get(i) + toRomanNumber(numb - i); } }
991
0.512614
0.495459
39
24.435898
22.33061
98
false
false
0
0
0
0
0
0
1.076923
false
false
14
801dedeb8803d90636bd3624debd3258e0014f75
35,854,387,022,486
2288829dc114466d783d872dabb2c0a5ec99f12c
/src/test/java/pt/arquivo/tests/api/pagesearch/params/FromAndToTest.java
081498af646a26eec9549d716bca5da4a83162a1
[ "Apache-2.0" ]
permissive
arquivo/functional-tests
https://github.com/arquivo/functional-tests
e490866a56fac16bb54e3fcb953f25f42e78dabb
c248ceaaa39d74d1c6ba705d7645511821238309
refs/heads/master
2023-04-27T05:59:03.237000
2023-03-24T13:57:41
2023-03-24T13:57:41
59,486,942
0
4
Apache-2.0
false
2023-04-14T17:46:52
2016-05-23T13:54:14
2021-11-29T11:31:50
2023-04-14T17:46:52
145,234
0
4
3
Java
false
false
package pt.arquivo.tests.api.pagesearch.params; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.HttpURLConnection; import org.apache.commons.io.IOUtils; import org.json.JSONObject; import org.junit.Test; import java.util.Scanner; import org.json.JSONArray; import org.json.JSONTokener; import pt.arquivo.selenium.Retry; import pt.arquivo.utils.AppendableErrorsBaseTest; /** * * @author pedro.gomes.fccn@gmail.com * */ public class FromAndToTest extends AppendableErrorsBaseTest { private String testURL; public FromAndToTest() { this.testURL = System.getProperty("test.url"); } @Test @Retry public void pageSearchAPITest() { URL url; JSONTokener tokener; JSONObject reply; JSONArray apiResults; String timestamp; String fromAPI = this.testURL + "/textsearch?q=fccn&from=20000101000000"; try { url = new URL(fromAPI); } catch (MalformedURLException e) { throw new RuntimeException( "Error generating URL to a Page Search API", e); } try{ tokener = new JSONTokener(url.openStream()); } catch (IOException e) { throw new RuntimeException( "Error starting a request to the Page Search API", e); } reply = new JSONObject(tokener); apiResults = reply.getJSONArray("response_items"); assertEquals("Verify that the API reply isn't empty", true, apiResults.length() > 0); for(int i=0;i<apiResults.length();i++){ timestamp = apiResults.getJSONObject(i).getString("tstamp"); assertEquals("Verify 'tstamp' parameter of API " +String.valueOf(i) + "th reply is later than 2000/01/01", timestamp.substring(0,1) , "2"); } String toAPI = this.testURL + "/textsearch?q=fccn&to=19991231000000"; try { url = new URL(toAPI); } catch (MalformedURLException e) { throw new RuntimeException( "Error generating URL to a Page Search API", e); } try{ tokener = new JSONTokener(url.openStream()); } catch (IOException e) { throw new RuntimeException( "Error starting a request to the Page Search API", e); } reply = new JSONObject(tokener); apiResults = reply.getJSONArray("response_items"); assertEquals("Verify that the API reply isn't empty", true, apiResults.length() > 0); for(int i=0;i<apiResults.length();i++){ timestamp = apiResults.getJSONObject(i).getString("tstamp"); assertEquals("Verify 'tstamp' parameter of API " +String.valueOf(i) + "th reply is before 2000/01/01", timestamp.substring(0,1) , "1"); } } }
UTF-8
Java
2,596
java
FromAndToTest.java
Java
[ { "context": "tils.AppendableErrorsBaseTest;\n\n/**\n * \n * @author pedro.gomes.fccn@gmail.com\n *\n */\n\npublic class FromAndToTest extends Append", "end": 549, "score": 0.9887621402740479, "start": 523, "tag": "EMAIL", "value": "pedro.gomes.fccn@gmail.com" } ]
null
[]
package pt.arquivo.tests.api.pagesearch.params; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.HttpURLConnection; import org.apache.commons.io.IOUtils; import org.json.JSONObject; import org.junit.Test; import java.util.Scanner; import org.json.JSONArray; import org.json.JSONTokener; import pt.arquivo.selenium.Retry; import pt.arquivo.utils.AppendableErrorsBaseTest; /** * * @author <EMAIL> * */ public class FromAndToTest extends AppendableErrorsBaseTest { private String testURL; public FromAndToTest() { this.testURL = System.getProperty("test.url"); } @Test @Retry public void pageSearchAPITest() { URL url; JSONTokener tokener; JSONObject reply; JSONArray apiResults; String timestamp; String fromAPI = this.testURL + "/textsearch?q=fccn&from=20000101000000"; try { url = new URL(fromAPI); } catch (MalformedURLException e) { throw new RuntimeException( "Error generating URL to a Page Search API", e); } try{ tokener = new JSONTokener(url.openStream()); } catch (IOException e) { throw new RuntimeException( "Error starting a request to the Page Search API", e); } reply = new JSONObject(tokener); apiResults = reply.getJSONArray("response_items"); assertEquals("Verify that the API reply isn't empty", true, apiResults.length() > 0); for(int i=0;i<apiResults.length();i++){ timestamp = apiResults.getJSONObject(i).getString("tstamp"); assertEquals("Verify 'tstamp' parameter of API " +String.valueOf(i) + "th reply is later than 2000/01/01", timestamp.substring(0,1) , "2"); } String toAPI = this.testURL + "/textsearch?q=fccn&to=19991231000000"; try { url = new URL(toAPI); } catch (MalformedURLException e) { throw new RuntimeException( "Error generating URL to a Page Search API", e); } try{ tokener = new JSONTokener(url.openStream()); } catch (IOException e) { throw new RuntimeException( "Error starting a request to the Page Search API", e); } reply = new JSONObject(tokener); apiResults = reply.getJSONArray("response_items"); assertEquals("Verify that the API reply isn't empty", true, apiResults.length() > 0); for(int i=0;i<apiResults.length();i++){ timestamp = apiResults.getJSONObject(i).getString("tstamp"); assertEquals("Verify 'tstamp' parameter of API " +String.valueOf(i) + "th reply is before 2000/01/01", timestamp.substring(0,1) , "1"); } } }
2,577
0.706472
0.68567
101
24.702971
27.372583
142
false
false
0
0
0
0
0
0
2.049505
false
false
14
6b3b43307dd20df3e27a681d0f62f4cdf5a62d52
39,092,792,337,364
faef60cb385c067d0d8f59a4bf8de1e04ae9e372
/test/testUser.java
4627aec7ecae3f2fa2eb580d58e7f23ec3637d63
[ "CC0-1.0" ]
permissive
vasichkin/java-store
https://github.com/vasichkin/java-store
2c7d7ea20ed71637662358ceb9599e8c9a9b944c
54eea46854a989d4796443aaf2ee51dc76202528
refs/heads/master
2020-04-18T08:38:40.927000
2019-01-24T18:02:39
2019-01-24T18:02:39
167,403,386
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.junit.After; import org.junit.Before; import org.junit.Test; import play.libs.Json; import play.libs.Time; import play.mvc.Http; import play.mvc.Result; import play.test.WithApplication; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static play.test.Helpers.*; public class testUser extends WithApplication { public static ObjectNode fixtureUser() { ObjectNode data = Json.newObject(); data.put("email", "test@email.com"); data.put("password", "test"); return data; } @Before public void fixture() { Http.RequestBuilder request = new Http.RequestBuilder() .method(POST) .bodyJson(fixtureUser()) .uri("/register"); route(app, request); } /* Register new user. Example request: {“email”:”my@email.com”, “password”:”123”} Respond with an appropriate HTTP codes (200 for ok, 409 for existing user) */ @Test public void userCouldBeRegistered() { ObjectNode data = Json.newObject(); data.put("email", "my@email.com"); data.put("password", "123"); Http.RequestBuilder request = new Http.RequestBuilder() .method(POST) .bodyJson(data) .uri("/register"); Result result = route(app, request); assertThat(contentAsString(result), containsString("User my@email.com registered")); } @Test public void registeringExistingUserGivesError() { ObjectNode data = Json.newObject(); data.put("email", "user1@email.com"); data.put("password", "123"); Http.RequestBuilder request = new Http.RequestBuilder() .method(POST) .bodyJson(data) .uri("/register"); Result result = route(app, request); assertThat(contentAsString(result), containsString("User user1@email.com registered")); request = new Http.RequestBuilder() .method(POST) .bodyJson(data) .uri("/register"); result = route(app, request); assertThat(contentAsString(result), containsString("User exists")); } /* Login into system. Example request: {“email”:”my@email.com”, “password”:”123”} Respond with JSON containing sessionId. */ @Test public void userCouldLogin() { Http.RequestBuilder request = new Http.RequestBuilder() .method(POST) .bodyJson(fixtureUser()) .uri("/login"); Result result = route(app, request); JsonNode response = Json.parse(contentAsString(result)); assertThat(response.get("username").asText(), equalTo("test@email.com")); } /* Think about preventing an intruder from bruteforcing */ @Test public void bruteForceProtection() { ObjectNode data = Json.newObject(); data.put("email", "non-existent@email.com"); data.put("password", "123"); Http.RequestBuilder request = new Http.RequestBuilder() .method(POST) .bodyJson(data) .uri("/login"); Result result = route(app, request); route(app, request); route(app, request); result = route(app, request); assertThat(contentAsString(result), containsString("Bruteforce protection activated")); result = route(app, request); assertThat(contentAsString(result), containsString("Bruteforce protection active")); } /* Reset password. */ @Test public void passwordReset() { } }
UTF-8
Java
3,911
java
testUser.java
Java
[ { "context": "ta = Json.newObject();\n data.put(\"email\", \"test@email.com\");\n data.put(\"password\", \"test\");\n ", "end": 708, "score": 0.9999235272407532, "start": 694, "tag": "EMAIL", "value": "test@email.com" }, { "context": " \"test@email.com\");\n data.put(\"password\", \"test\");\n return data;\n }\n\n @Before\n pu", "end": 746, "score": 0.9994599223136902, "start": 742, "tag": "PASSWORD", "value": "test" }, { "context": " Register new user. Example request: {“email”:”my@email.com”, “password”:”123”}\n Respond with an appropria", "end": 1094, "score": 0.9999152421951294, "start": 1082, "tag": "EMAIL", "value": "my@email.com" }, { "context": "ple request: {“email”:”my@email.com”, “password”:”123”}\n Respond with an appropriate HTTP codes (200", "end": 1112, "score": 0.9994993209838867, "start": 1109, "tag": "PASSWORD", "value": "123" }, { "context": "ta = Json.newObject();\n data.put(\"email\", \"my@email.com\");\n data.put(\"password\", \"123\");\n\n ", "end": 1337, "score": 0.9999254941940308, "start": 1325, "tag": "EMAIL", "value": "my@email.com" }, { "context": "\", \"my@email.com\");\n data.put(\"password\", \"123\");\n\n Http.RequestBuilder request = new Htt", "end": 1374, "score": 0.9995095729827881, "start": 1371, "tag": "PASSWORD", "value": "123" }, { "context": "That(contentAsString(result), containsString(\"User my@email.com registered\"));\n }\n\n @Test\n public void r", "end": 1662, "score": 0.9999257326126099, "start": 1650, "tag": "EMAIL", "value": "my@email.com" }, { "context": "ta = Json.newObject();\n data.put(\"email\", \"user1@email.com\");\n data.put(\"password\", \"123\");\n\n ", "end": 1835, "score": 0.9999144673347473, "start": 1820, "tag": "EMAIL", "value": "user1@email.com" }, { "context": "\"user1@email.com\");\n data.put(\"password\", \"123\");\n\n Http.RequestBuilder request = new Htt", "end": 1872, "score": 0.9995110034942627, "start": 1869, "tag": "PASSWORD", "value": "123" }, { "context": "That(contentAsString(result), containsString(\"User user1@email.com registered\"));\n\n\n request = new Http.Reque", "end": 2163, "score": 0.9999168515205383, "start": 2148, "tag": "EMAIL", "value": "user1@email.com" }, { "context": " Login into system. Example request: {“email”:”my@email.com”, “password”:”123”}\n Respond with JSON contain", "end": 2512, "score": 0.9999200105667114, "start": 2500, "tag": "EMAIL", "value": "my@email.com" }, { "context": "ple request: {“email”:”my@email.com”, “password”:”123”}\n Respond with JSON containing sessionId.\n ", "end": 2530, "score": 0.999457061290741, "start": 2527, "tag": "PASSWORD", "value": "123" }, { "context": "tThat(response.get(\"username\").asText(), equalTo(\"test@email.com\"));\n }\n\n\n /*\n Think about preventing an ", "end": 2985, "score": 0.999911904335022, "start": 2971, "tag": "EMAIL", "value": "test@email.com" }, { "context": "ta = Json.newObject();\n data.put(\"email\", \"non-existent@email.com\");\n data.put(\"password\", \"123\");\n H", "end": 3213, "score": 0.9999110102653503, "start": 3191, "tag": "EMAIL", "value": "non-existent@email.com" }, { "context": "istent@email.com\");\n data.put(\"password\", \"123\");\n Http.RequestBuilder request = new Http", "end": 3250, "score": 0.9994269013404846, "start": 3247, "tag": "PASSWORD", "value": "123" } ]
null
[]
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.junit.After; import org.junit.Before; import org.junit.Test; import play.libs.Json; import play.libs.Time; import play.mvc.Http; import play.mvc.Result; import play.test.WithApplication; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static play.test.Helpers.*; public class testUser extends WithApplication { public static ObjectNode fixtureUser() { ObjectNode data = Json.newObject(); data.put("email", "<EMAIL>"); data.put("password", "<PASSWORD>"); return data; } @Before public void fixture() { Http.RequestBuilder request = new Http.RequestBuilder() .method(POST) .bodyJson(fixtureUser()) .uri("/register"); route(app, request); } /* Register new user. Example request: {“email”:”<EMAIL>”, “password”:”123”} Respond with an appropriate HTTP codes (200 for ok, 409 for existing user) */ @Test public void userCouldBeRegistered() { ObjectNode data = Json.newObject(); data.put("email", "<EMAIL>"); data.put("password", "123"); Http.RequestBuilder request = new Http.RequestBuilder() .method(POST) .bodyJson(data) .uri("/register"); Result result = route(app, request); assertThat(contentAsString(result), containsString("User <EMAIL> registered")); } @Test public void registeringExistingUserGivesError() { ObjectNode data = Json.newObject(); data.put("email", "<EMAIL>"); data.put("password", "123"); Http.RequestBuilder request = new Http.RequestBuilder() .method(POST) .bodyJson(data) .uri("/register"); Result result = route(app, request); assertThat(contentAsString(result), containsString("User <EMAIL> registered")); request = new Http.RequestBuilder() .method(POST) .bodyJson(data) .uri("/register"); result = route(app, request); assertThat(contentAsString(result), containsString("User exists")); } /* Login into system. Example request: {“email”:”<EMAIL>”, “password”:”123”} Respond with JSON containing sessionId. */ @Test public void userCouldLogin() { Http.RequestBuilder request = new Http.RequestBuilder() .method(POST) .bodyJson(fixtureUser()) .uri("/login"); Result result = route(app, request); JsonNode response = Json.parse(contentAsString(result)); assertThat(response.get("username").asText(), equalTo("<EMAIL>")); } /* Think about preventing an intruder from bruteforcing */ @Test public void bruteForceProtection() { ObjectNode data = Json.newObject(); data.put("email", "<EMAIL>"); data.put("password", "123"); Http.RequestBuilder request = new Http.RequestBuilder() .method(POST) .bodyJson(data) .uri("/login"); Result result = route(app, request); route(app, request); route(app, request); result = route(app, request); assertThat(contentAsString(result), containsString("Bruteforce protection activated")); result = route(app, request); assertThat(contentAsString(result), containsString("Bruteforce protection active")); } /* Reset password. */ @Test public void passwordReset() { } }
3,852
0.61356
0.607631
127
29.543306
24.347469
95
false
false
0
0
0
0
0
0
0.614173
false
false
14
c416418a2cf1f0f548868f9eb3d989957da5a6b3
35,210,141,936,703
d59659decc96ff98f3ac12eade4c211d743e7265
/AppLibrary/src/main/java/com/example/applibrary/entity/FootPrint.java
cfc76ea1a797804f39752c6665beacaac5e63eb5
[]
no_license
chentt521520/Hss_FuLi_full
https://github.com/chentt521520/Hss_FuLi_full
7a76b2fa78bc3f6776a2e81730a0276fdc5dcf95
cf926c4bbe5065409b722348ae4285b72b4994bb
refs/heads/master
2020-07-03T03:31:51
2019-09-20T08:46:17
2019-09-20T08:46:17
201,770,085
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.applibrary.entity; public class FootPrint { /** * id : 317 * uid : 37 * product_id : 3098 * add_time : 2019-07-28 11:01:58 * is_del : 0 * store_name : 广西巴马沙地番薯 农家自种植红心小香薯地瓜新鲜巴马红薯8斤 * image : http://py.haoshusi.com/py0709/80ebbb3e69d77a095bc757dbe2990639.jpg * price : 40.69 * ficti : 0 */ private int id; private int uid; private int product_id; private String add_time; private int is_del; private String store_name; private String image; private String price; private int ficti; private boolean isCheck; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public int getProduct_id() { return product_id; } public void setProduct_id(int product_id) { this.product_id = product_id; } public String getAdd_time() { return add_time; } public void setAdd_time(String add_time) { this.add_time = add_time; } public int getIs_del() { return is_del; } public void setIs_del(int is_del) { this.is_del = is_del; } public String getStore_name() { return store_name; } public void setStore_name(String store_name) { this.store_name = store_name; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public int getFicti() { return ficti; } public void setFicti(int ficti) { this.ficti = ficti; } public boolean isCheck() { return isCheck; } public void setCheck(boolean check) { isCheck = check; } }
UTF-8
Java
2,063
java
FootPrint.java
Java
[]
null
[]
package com.example.applibrary.entity; public class FootPrint { /** * id : 317 * uid : 37 * product_id : 3098 * add_time : 2019-07-28 11:01:58 * is_del : 0 * store_name : 广西巴马沙地番薯 农家自种植红心小香薯地瓜新鲜巴马红薯8斤 * image : http://py.haoshusi.com/py0709/80ebbb3e69d77a095bc757dbe2990639.jpg * price : 40.69 * ficti : 0 */ private int id; private int uid; private int product_id; private String add_time; private int is_del; private String store_name; private String image; private String price; private int ficti; private boolean isCheck; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public int getProduct_id() { return product_id; } public void setProduct_id(int product_id) { this.product_id = product_id; } public String getAdd_time() { return add_time; } public void setAdd_time(String add_time) { this.add_time = add_time; } public int getIs_del() { return is_del; } public void setIs_del(int is_del) { this.is_del = is_del; } public String getStore_name() { return store_name; } public void setStore_name(String store_name) { this.store_name = store_name; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public int getFicti() { return ficti; } public void setFicti(int ficti) { this.ficti = ficti; } public boolean isCheck() { return isCheck; } public void setCheck(boolean check) { isCheck = check; } }
2,063
0.563464
0.536585
107
17.775702
15.612306
81
false
false
0
0
0
0
0
0
0.28972
false
false
14
241d09b3683b8a2ddcc3fdd949fab272ac614781
35,845,797,091,600
55dca62e858f1a44c2186774339823a301b48dc7
/code/my-app/functions/3/unspecificMigrantSlot_Europe.java
b650cdebf20205a948e7e24fea6d3b49c4c6b667
[]
no_license
jwiszowata/code_reaper
https://github.com/jwiszowata/code_reaper
4fff256250299225879d1412eb1f70b136d7a174
17dde61138cec117047a6ebb412ee1972886f143
refs/heads/master
2022-12-15T14:46:30.640000
2022-02-10T14:02:45
2022-02-10T14:02:45
84,747,455
0
0
null
false
2022-12-07T23:48:18
2017-03-12T18:26:11
2022-02-10T14:00:02
2022-12-07T23:48:18
16,770
0
0
24
Java
false
false
public static boolean unspecificMigrantSlot(int x) { return CHOOSE_MIGRANT_SLOT == x; }
UTF-8
Java
91
java
unspecificMigrantSlot_Europe.java
Java
[]
null
[]
public static boolean unspecificMigrantSlot(int x) { return CHOOSE_MIGRANT_SLOT == x; }
91
0.747253
0.747253
3
29.666666
21.296844
52
false
false
0
0
0
0
0
0
0.333333
false
false
14
06d486da97615619e3a0cc0d1d3850703339803a
34,359,738,424,948
d23ecc01fa86b70e6fb4405d86b1e52a16fda976
/src/Exam/NetherRealms.java
751b15ae13f49743699a846fc4edae0ea231aab0
[ "MIT" ]
permissive
VladimirMetodiev/JavaFundamentals
https://github.com/VladimirMetodiev/JavaFundamentals
09df800430ab06e59b8823b845359f64a26d44ec
5061bd45d42c0465421a2ae5faf382f012d5e627
refs/heads/main
2023-03-05T22:24:11.820000
2021-02-19T09:25:08
2021-02-19T09:25:08
340,016,711
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Exam; import java.util.Scanner; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NetherRealms { public static void main(String[] args){ Scanner input = new Scanner(System.in); String[] data = input.nextLine().split(",\\s*"); TreeMap<String, Integer> demonHealth = new TreeMap<>(); TreeMap<String, Double> demonDamage = new TreeMap<>(); for (int z = 0; z < data.length; z++) { data[z] = data[z].replaceAll("\\s", ""); } for (String demon : data) { demonHealth.put(demon, 0); demonDamage.put(demon, 0.0); } int currentHealth = 0; double currentDamage = 0.0; Pattern pattern1 = Pattern.compile("([^0-9\\.\\+\\-\\*\\/])"); Pattern pattern2 = Pattern.compile("([+-]?\\d+\\.?\\d*)"); for (String demon : data) { Matcher health = pattern1.matcher(demon); while(health.find()){ currentHealth += (int)health.group().charAt(0); } demonHealth.put(demon, currentHealth); currentHealth = 0; } for(String demon : data){ Matcher damage = pattern2.matcher(demon); while (damage.find()){ currentDamage += Double.parseDouble(damage.group()); } for (int a = 0; a < demon.length(); a++) { if(("" + demon.charAt(a)).equals("/")){ currentDamage /= 2; } if(("" + demon.charAt(a)).equals("*")){ currentDamage *= 2; } } demonDamage.put(demon, currentDamage); currentDamage = 0.0; } demonHealth .entrySet() .stream() .forEach(a -> System.out.printf("%s - %d health, %.2f damage%n", a.getKey(), a.getValue(), demonDamage.get(a.getKey()))); } } //Exam Preparation II
UTF-8
Java
2,030
java
NetherRealms.java
Java
[]
null
[]
package Exam; import java.util.Scanner; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NetherRealms { public static void main(String[] args){ Scanner input = new Scanner(System.in); String[] data = input.nextLine().split(",\\s*"); TreeMap<String, Integer> demonHealth = new TreeMap<>(); TreeMap<String, Double> demonDamage = new TreeMap<>(); for (int z = 0; z < data.length; z++) { data[z] = data[z].replaceAll("\\s", ""); } for (String demon : data) { demonHealth.put(demon, 0); demonDamage.put(demon, 0.0); } int currentHealth = 0; double currentDamage = 0.0; Pattern pattern1 = Pattern.compile("([^0-9\\.\\+\\-\\*\\/])"); Pattern pattern2 = Pattern.compile("([+-]?\\d+\\.?\\d*)"); for (String demon : data) { Matcher health = pattern1.matcher(demon); while(health.find()){ currentHealth += (int)health.group().charAt(0); } demonHealth.put(demon, currentHealth); currentHealth = 0; } for(String demon : data){ Matcher damage = pattern2.matcher(demon); while (damage.find()){ currentDamage += Double.parseDouble(damage.group()); } for (int a = 0; a < demon.length(); a++) { if(("" + demon.charAt(a)).equals("/")){ currentDamage /= 2; } if(("" + demon.charAt(a)).equals("*")){ currentDamage *= 2; } } demonDamage.put(demon, currentDamage); currentDamage = 0.0; } demonHealth .entrySet() .stream() .forEach(a -> System.out.printf("%s - %d health, %.2f damage%n", a.getKey(), a.getValue(), demonDamage.get(a.getKey()))); } } //Exam Preparation II
2,030
0.495567
0.485222
75
26.066668
25.460209
137
false
false
0
0
0
0
0
0
0.573333
false
false
14
7ed2ec3ad4a536b055f67f0ca120be12cd09fbb6
34,342,558,558,542
37d83b3c2a06f0ac4ac3bb6731dbd45702ddbf6f
/Spring040_Layering/src/main/java/com/cg/java/services/EmpService.java
e9db847e7fb6fd94a979cdab01724513b5adcc94
[]
no_license
shivamsingh361/spring
https://github.com/shivamsingh361/spring
cd0a8a9cd65e9e9fb8910b23b6cd8574b07dd761
e13ccf7f7f82d78eb3c7ffac1589cb7e8ceaeda5
refs/heads/master
2021-03-14T21:36:36.768000
2020-03-12T09:44:24
2020-03-12T09:44:24
246,796,010
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cg.java.services; import java.util.List; import com.cg.java.dto.Emp; import com.cg.java.exceptions.EmpException; public interface EmpService { public List<Emp> getEmpList() throws EmpException; }
UTF-8
Java
225
java
EmpService.java
Java
[]
null
[]
package com.cg.java.services; import java.util.List; import com.cg.java.dto.Emp; import com.cg.java.exceptions.EmpException; public interface EmpService { public List<Emp> getEmpList() throws EmpException; }
225
0.737778
0.737778
11
18.454546
18.346977
52
false
false
0
0
0
0
0
0
0.545455
false
false
14
763cc6facd07fe251ee5c422375b53f6f2664690
4,818,953,327,949
90ace79b8b6f56777d759a036aaf02dda9e970c7
/src/Servlets/AdminAppointDeleteHandler.java
1ec5d52f8d4c8598587e1278c73c113cdccf3b02
[]
no_license
Thavananthan/Hospitality-Management-----Web-Based-Application
https://github.com/Thavananthan/Hospitality-Management-----Web-Based-Application
a26cee5f05af87c34d7318dba5f3e464a46a1709
160c6d63efeff6fbae7d29966527005787e61a39
refs/heads/master
2020-07-06T03:43:15.355000
2019-08-17T12:21:18
2019-08-17T12:21:18
202,877,383
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Servlets; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import ServiceFiles.AdminAppointDeleteService; /** * Servlet implementation class AdminAppointDeleteHandler */ @WebServlet("/AdminAppointDeleteHandler") public class AdminAppointDeleteHandler extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public AdminAppointDeleteHandler() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String UserName=request.getParameter("id"); AdminAppointDeleteService ad=new AdminAppointDeleteService(); if(ad.deleteUser(UserName)) response.sendRedirect("admin/adminappointview.jsp"); } }
UTF-8
Java
1,163
java
AdminAppointDeleteHandler.java
Java
[]
null
[]
package Servlets; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import ServiceFiles.AdminAppointDeleteService; /** * Servlet implementation class AdminAppointDeleteHandler */ @WebServlet("/AdminAppointDeleteHandler") public class AdminAppointDeleteHandler extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public AdminAppointDeleteHandler() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String UserName=request.getParameter("id"); AdminAppointDeleteService ad=new AdminAppointDeleteService(); if(ad.deleteUser(UserName)) response.sendRedirect("admin/adminappointview.jsp"); } }
1,163
0.772141
0.771281
39
28.820513
27.042105
118
false
false
0
0
0
0
0
0
0.923077
false
false
14
316869d8a17b3c077c8533ec259ab87c2247eb4b
4,818,953,331,443
32561370150282fcd6e084f5d5cc598920e03c2d
/sistema/src/datos/EtniaD.java
d775ae93d344005f0ff698b5e4b54e5be6929f71
[]
no_license
efra1/prueba_2
https://github.com/efra1/prueba_2
ee173960df254d2eebd9e420a1905de5154670d4
655b3cbf7e00fc7e685b9fc06feff3e735ae65f7
refs/heads/master
2020-03-29T02:42:35.811000
2018-09-19T13:44:07
2018-09-19T13:44:07
149,449,896
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package datos; import java.util.List; import java.util.Map; import modelos.Tipo; import modelos.etnia; import org.springframework.stereotype.Service; @Service public class EtniaD extends Conexion{ public List<Map<String,Object>> listarEtnias(){ return db.queryForList("select *,(select count(*) from persona where etnia=id_etn and activo) as personas from etnia"); } public void guardar(etnia e){ db.update("insert into etnia(nombre) values(?)",e.getNombre()); } public void modificar(etnia e){ db.update("update etnia set (nombre)=(?) where id_etn=?",e.getNombre(),e.getId_etn()); } public Map<String,Object> obtener(Integer id_etn){ return db.queryForMap("select * from etnia where id_etn=?",id_etn); } public void inhabilitar(Integer id_etn){ db.update("update etnia set activo=false where id_etn=?",id_etn); } }
UTF-8
Java
826
java
EtniaD.java
Java
[]
null
[]
package datos; import java.util.List; import java.util.Map; import modelos.Tipo; import modelos.etnia; import org.springframework.stereotype.Service; @Service public class EtniaD extends Conexion{ public List<Map<String,Object>> listarEtnias(){ return db.queryForList("select *,(select count(*) from persona where etnia=id_etn and activo) as personas from etnia"); } public void guardar(etnia e){ db.update("insert into etnia(nombre) values(?)",e.getNombre()); } public void modificar(etnia e){ db.update("update etnia set (nombre)=(?) where id_etn=?",e.getNombre(),e.getId_etn()); } public Map<String,Object> obtener(Integer id_etn){ return db.queryForMap("select * from etnia where id_etn=?",id_etn); } public void inhabilitar(Integer id_etn){ db.update("update etnia set activo=false where id_etn=?",id_etn); } }
826
0.738499
0.738499
29
27.482759
30.382187
120
false
false
0
0
0
0
0
0
0.827586
false
false
14
7617b43a426a3a22aac37689fdb77792376bc4a3
26,757,646,314,561
924455e2616d1af74c6cd7be5a09572edc88b76c
/src/test/java/com/schrismillar/connect4/game/player/determiners/PlayerTypeDeterminerTest.java
15e5ea363d0bf647a0ec7927b35722c53f85ad45
[]
no_license
chris-millar/connect-four
https://github.com/chris-millar/connect-four
64f5715af9bfed71be499abc1e8780875630c43f
a0deb4642c51bd1f2349668da207110dca28e30d
refs/heads/master
2021-04-26T22:38:32.969000
2020-03-10T04:22:16
2020-03-10T04:22:16
124,125,105
0
0
null
false
2020-10-12T22:50:21
2018-03-06T19:02:48
2020-03-10T04:22:25
2020-10-12T22:50:20
146
0
0
1
Java
false
false
package com.schrismillar.connect4.game.player.determiners; import static com.schrismillar.connect4.model.PlayerId.PLAYER_ONE; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; import static org.mockito.MockitoAnnotations.initMocks; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mock; import com.schrismillar.connect4.game.player.HumanPlayer; import com.schrismillar.connect4.game.player.Player; import com.schrismillar.connect4.game.player.PlayerFactory; import com.schrismillar.connect4.game.player.RandomAiPlayer; import com.schrismillar.connect4.util.ConsolePrinter; import com.schrismillar.connect4.util.ConsoleScanner; public class PlayerTypeDeterminerTest { private static final String NAME = "valid player name"; @Mock private ConsolePrinter consolePrinter; @Mock private ConsoleScanner consoleScanner; @Mock private PlayerFactory playerFactory; @Mock private HumanPlayer humanPlayer; private PlayerTypeDeterminer playerTypeDeterminer; @Before public void setUp() { initMocks(this); playerTypeDeterminer = new PlayerTypeDeterminer(consolePrinter, consoleScanner, playerFactory); } @Test public void determinePlayerTypePromptsForTypeAndReturnsHumanPlayerWhenUserAnswersWithHuman() { when(consoleScanner.next()).thenReturn("human"); when(playerFactory.createHumanPlayerWith(PLAYER_ONE, NAME)).thenReturn(humanPlayer); InOrder consoleOrderVerifier = inOrder(consolePrinter, consoleScanner); Player player = playerTypeDeterminer.determinePlayerType(PLAYER_ONE, NAME); assertEquals(humanPlayer, player); consoleOrderVerifier.verify(consolePrinter).println("Choose a type of player for " + PLAYER_ONE + ". <human>/<h> or <ai>"); consoleOrderVerifier.verify(consoleScanner).next(); } @Test public void determinePlayerTypePromptsForTypeAndReturnsHumanPlayerWhenUserAnswersWithJustH() { when(consoleScanner.next()).thenReturn("h"); when(playerFactory.createHumanPlayerWith(PLAYER_ONE, NAME)).thenReturn(humanPlayer); InOrder consoleOrderVerifier = inOrder(consolePrinter, consoleScanner); Player player = playerTypeDeterminer.determinePlayerType(PLAYER_ONE, NAME); assertEquals(humanPlayer, player); consoleOrderVerifier.verify(consolePrinter).println("Choose a type of player for " + PLAYER_ONE + ". <human>/<h> or <ai>"); consoleOrderVerifier.verify(consoleScanner).next(); } @Test public void determinePlayerTypePromptsForTypeAndReturnsRandomAiPlayerWhenUserAnswersWithAi() { RandomAiPlayer randomAiPlayer = mock(RandomAiPlayer.class); when(consoleScanner.next()).thenReturn("ai"); when(playerFactory.createRandomAiPlayerWith(PLAYER_ONE, NAME)).thenReturn(randomAiPlayer); InOrder consoleOrderVerifier = inOrder(consolePrinter, consoleScanner); Player player = playerTypeDeterminer.determinePlayerType(PLAYER_ONE, NAME); assertEquals(randomAiPlayer, player); consoleOrderVerifier.verify(consolePrinter).println("Choose a type of player for " + PLAYER_ONE + ". <human>/<h> or <ai>"); consoleOrderVerifier.verify(consoleScanner).next(); } @Test public void determinePlayerTypePrintsInvalidInputMessageAndRecursesIfInvalidPlayerType() { String invalidType = "not a valid player type"; when(consoleScanner.next()).thenReturn(invalidType).thenReturn("h"); when(playerFactory.createHumanPlayerWith(PLAYER_ONE, NAME)).thenReturn(humanPlayer); InOrder consoleOrderVerifier = inOrder(consolePrinter, consoleScanner); Player player = playerTypeDeterminer.determinePlayerType(PLAYER_ONE, NAME); assertEquals(humanPlayer, player); consoleOrderVerifier.verify(consolePrinter).println("Choose a type of player for " + PLAYER_ONE + ". <human>/<h> or <ai>"); consoleOrderVerifier.verify(consoleScanner).next(); consoleOrderVerifier.verify(consolePrinter).println("INVALID INPUT: Player type must be either <human>/<h> or <ai>."); consoleOrderVerifier.verify(consolePrinter).println("Choose a type of player for " + PLAYER_ONE + ". <human>/<h> or <ai>"); consoleOrderVerifier.verify(consoleScanner).next(); } }
UTF-8
Java
4,361
java
PlayerTypeDeterminerTest.java
Java
[]
null
[]
package com.schrismillar.connect4.game.player.determiners; import static com.schrismillar.connect4.model.PlayerId.PLAYER_ONE; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; import static org.mockito.MockitoAnnotations.initMocks; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mock; import com.schrismillar.connect4.game.player.HumanPlayer; import com.schrismillar.connect4.game.player.Player; import com.schrismillar.connect4.game.player.PlayerFactory; import com.schrismillar.connect4.game.player.RandomAiPlayer; import com.schrismillar.connect4.util.ConsolePrinter; import com.schrismillar.connect4.util.ConsoleScanner; public class PlayerTypeDeterminerTest { private static final String NAME = "valid player name"; @Mock private ConsolePrinter consolePrinter; @Mock private ConsoleScanner consoleScanner; @Mock private PlayerFactory playerFactory; @Mock private HumanPlayer humanPlayer; private PlayerTypeDeterminer playerTypeDeterminer; @Before public void setUp() { initMocks(this); playerTypeDeterminer = new PlayerTypeDeterminer(consolePrinter, consoleScanner, playerFactory); } @Test public void determinePlayerTypePromptsForTypeAndReturnsHumanPlayerWhenUserAnswersWithHuman() { when(consoleScanner.next()).thenReturn("human"); when(playerFactory.createHumanPlayerWith(PLAYER_ONE, NAME)).thenReturn(humanPlayer); InOrder consoleOrderVerifier = inOrder(consolePrinter, consoleScanner); Player player = playerTypeDeterminer.determinePlayerType(PLAYER_ONE, NAME); assertEquals(humanPlayer, player); consoleOrderVerifier.verify(consolePrinter).println("Choose a type of player for " + PLAYER_ONE + ". <human>/<h> or <ai>"); consoleOrderVerifier.verify(consoleScanner).next(); } @Test public void determinePlayerTypePromptsForTypeAndReturnsHumanPlayerWhenUserAnswersWithJustH() { when(consoleScanner.next()).thenReturn("h"); when(playerFactory.createHumanPlayerWith(PLAYER_ONE, NAME)).thenReturn(humanPlayer); InOrder consoleOrderVerifier = inOrder(consolePrinter, consoleScanner); Player player = playerTypeDeterminer.determinePlayerType(PLAYER_ONE, NAME); assertEquals(humanPlayer, player); consoleOrderVerifier.verify(consolePrinter).println("Choose a type of player for " + PLAYER_ONE + ". <human>/<h> or <ai>"); consoleOrderVerifier.verify(consoleScanner).next(); } @Test public void determinePlayerTypePromptsForTypeAndReturnsRandomAiPlayerWhenUserAnswersWithAi() { RandomAiPlayer randomAiPlayer = mock(RandomAiPlayer.class); when(consoleScanner.next()).thenReturn("ai"); when(playerFactory.createRandomAiPlayerWith(PLAYER_ONE, NAME)).thenReturn(randomAiPlayer); InOrder consoleOrderVerifier = inOrder(consolePrinter, consoleScanner); Player player = playerTypeDeterminer.determinePlayerType(PLAYER_ONE, NAME); assertEquals(randomAiPlayer, player); consoleOrderVerifier.verify(consolePrinter).println("Choose a type of player for " + PLAYER_ONE + ". <human>/<h> or <ai>"); consoleOrderVerifier.verify(consoleScanner).next(); } @Test public void determinePlayerTypePrintsInvalidInputMessageAndRecursesIfInvalidPlayerType() { String invalidType = "not a valid player type"; when(consoleScanner.next()).thenReturn(invalidType).thenReturn("h"); when(playerFactory.createHumanPlayerWith(PLAYER_ONE, NAME)).thenReturn(humanPlayer); InOrder consoleOrderVerifier = inOrder(consolePrinter, consoleScanner); Player player = playerTypeDeterminer.determinePlayerType(PLAYER_ONE, NAME); assertEquals(humanPlayer, player); consoleOrderVerifier.verify(consolePrinter).println("Choose a type of player for " + PLAYER_ONE + ". <human>/<h> or <ai>"); consoleOrderVerifier.verify(consoleScanner).next(); consoleOrderVerifier.verify(consolePrinter).println("INVALID INPUT: Player type must be either <human>/<h> or <ai>."); consoleOrderVerifier.verify(consolePrinter).println("Choose a type of player for " + PLAYER_ONE + ". <human>/<h> or <ai>"); consoleOrderVerifier.verify(consoleScanner).next(); } }
4,361
0.74914
0.747306
95
44.915791
39.153049
131
false
false
0
0
0
0
78
0.070626
0.778947
false
false
14
1f3335c7cb531ada81dfde1f725f3bdd825d888f
30,399,778,544,651
f1775c042b3e73808639f94919427f482d462e01
/src/test/java/com/capgemini/chess/components/match/services/impl/ValidationMatchServiceImplTest.java
e867b52851be066b8e9243d79e8b1c5e924d415a
[]
no_license
bartas93/Spring-ChessStatistics
https://github.com/bartas93/Spring-ChessStatistics
133b3840cc97a03bc5f93a1e43256b8e639b8be8
eef0702dc01aa1a1e8ef6cba484f9c6e801e1439
refs/heads/master
2019-06-17T12:54:17.360000
2017-09-24T11:52:36
2017-09-24T11:52:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.capgemini.chess.components.match.services.impl; import static org.mockito.Mockito.when; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.capgemini.chess.components.match.dataaccess.dao.MatchDao; import com.capgemini.chess.components.match.enums.MatchStatus; import com.capgemini.chess.components.match.services.exceptions.InvalidMatchStatusException; import com.capgemini.chess.components.match.services.to.MatchResultTo; @RunWith(MockitoJUnitRunner.class) public class ValidationMatchServiceImplTest { @Rule public ExpectedException e = ExpectedException.none(); @Mock private MatchDao matchDao; @InjectMocks private ValidationMatchServiceImpl validationMatchServiceImpl; @Test public void shouldThrowExceptionWhenStatusEqualsNull() throws InvalidMatchStatusException { // given MatchResultTo matchResultTo = new MatchResultTo(20L, MatchStatus.WHITE_WON); when(matchDao.getMatchStatus(20L)).thenReturn(null); // expected e.expect(InvalidMatchStatusException.class); // when validationMatchServiceImpl.validate(matchResultTo); } @Test public void shouldThrowExceptionWhenStatusEqualsDrawn() throws InvalidMatchStatusException { // given MatchResultTo matchResultTo = new MatchResultTo(20L, MatchStatus.WHITE_WON); when(matchDao.getMatchStatus(20L)).thenReturn(MatchStatus.DRAWN); // expected e.expect(InvalidMatchStatusException.class); // when validationMatchServiceImpl.validate(matchResultTo); } @Test public void shouldNotThrowExceptionWhenStatusIsInProgres() throws InvalidMatchStatusException { // given MatchResultTo matchResultTo = new MatchResultTo(20L, MatchStatus.WHITE_WON); when(matchDao.getMatchStatus(20L)).thenReturn(MatchStatus.IN_PROGRES); // expected e = ExpectedException.none(); // when validationMatchServiceImpl.validate(matchResultTo); } }
UTF-8
Java
2,029
java
ValidationMatchServiceImplTest.java
Java
[]
null
[]
package com.capgemini.chess.components.match.services.impl; import static org.mockito.Mockito.when; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.capgemini.chess.components.match.dataaccess.dao.MatchDao; import com.capgemini.chess.components.match.enums.MatchStatus; import com.capgemini.chess.components.match.services.exceptions.InvalidMatchStatusException; import com.capgemini.chess.components.match.services.to.MatchResultTo; @RunWith(MockitoJUnitRunner.class) public class ValidationMatchServiceImplTest { @Rule public ExpectedException e = ExpectedException.none(); @Mock private MatchDao matchDao; @InjectMocks private ValidationMatchServiceImpl validationMatchServiceImpl; @Test public void shouldThrowExceptionWhenStatusEqualsNull() throws InvalidMatchStatusException { // given MatchResultTo matchResultTo = new MatchResultTo(20L, MatchStatus.WHITE_WON); when(matchDao.getMatchStatus(20L)).thenReturn(null); // expected e.expect(InvalidMatchStatusException.class); // when validationMatchServiceImpl.validate(matchResultTo); } @Test public void shouldThrowExceptionWhenStatusEqualsDrawn() throws InvalidMatchStatusException { // given MatchResultTo matchResultTo = new MatchResultTo(20L, MatchStatus.WHITE_WON); when(matchDao.getMatchStatus(20L)).thenReturn(MatchStatus.DRAWN); // expected e.expect(InvalidMatchStatusException.class); // when validationMatchServiceImpl.validate(matchResultTo); } @Test public void shouldNotThrowExceptionWhenStatusIsInProgres() throws InvalidMatchStatusException { // given MatchResultTo matchResultTo = new MatchResultTo(20L, MatchStatus.WHITE_WON); when(matchDao.getMatchStatus(20L)).thenReturn(MatchStatus.IN_PROGRES); // expected e = ExpectedException.none(); // when validationMatchServiceImpl.validate(matchResultTo); } }
2,029
0.814194
0.80828
62
31.741936
29.729389
96
false
false
0
0
0
0
0
0
1.419355
false
false
14
476bfa2b73fbfc93a27c1510c4a34180d59406f1
31,215,822,336,979
4d713125a5b5ffee4614145e06fae0b0f5d6edb1
/ApplicationManagementService/src/main/java/com/cg/uas/applicationmanagement/controller/ApplicantController.java
591adbd0559f65f8bc04c63ae9db3c7f8fb031bb
[]
no_license
Krishan24/UAS-MicroServices-PLP-Evaluation
https://github.com/Krishan24/UAS-MicroServices-PLP-Evaluation
402a8fb0b297fa72b99ec1bd4773ee1d283cde89
26de20189f58b452c47db9e194aaea75dfc188e8
refs/heads/master
2022-11-01T00:38:12.130000
2020-06-15T12:22:07
2020-06-15T12:22:07
272,197,917
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/**************************************************************************************************************************** - File Name : ApplicantController - Author : Charul Gupta - Creation Date : 12-06-2020 - Description : This is an end point controller to consume Application Management Services. ****************************************************************************************************************************/ package com.cg.uas.applicationmanagement.controller; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.cg.uas.applicationmanagement.dto.ApplicantEntity; import com.cg.uas.applicationmanagement.exception.ApplicantAlreadyExsistsException; import com.cg.uas.applicationmanagement.exception.ApplicantNotFoundException; import com.cg.uas.applicationmanagement.service.ApplicantService; @RestController @Validated @RequestMapping("/applicants") public class ApplicantController { @Autowired private ApplicantService service; /**************************************************************************************************************************** - Method Name : getAllApplicants - Input Parameters : void - Return type : List<ApplicantEntity> - Author : Charul Gupta - Creation Date : 12-06-2020 - Description : fetching the applicant information from the database. - End point URL : http://localhost:9001/applicants/getall ****************************************************************************************************************************/ @GetMapping("/getall") public List<ApplicantEntity> getAllApplicants() { return service.getAllApplicants(); } /**************************************************************************************************************************** - Method Name : addApplicant - Input Parameters : ApplicantEntity - Return type : ResponseEntity - Author : Charul Gupta - Creation Date : 12-06-2020 - Description : Inserting the applicant information entered by user into the database. - End point URL : http://localhost:9001/applicants/addApplicant ****************************************************************************************************************************/ @PostMapping("/addApplicant") public ResponseEntity<ApplicantEntity> addApplicant(@Valid @RequestBody ApplicantEntity entity) throws ApplicantAlreadyExsistsException{ ApplicantEntity appEntity = service.addApplicant(entity); return ResponseEntity.status(HttpStatus.OK).body(appEntity); } /**************************************************************************************************************************** - Method Name : getApplicantByProgramName - Input Parameters : programName - Return type : ResponseEntity<ApplicantEntity> - Author : Charul Gupta - Creation Date : 12-06-2020 - Description : Fetching the applicant information from the database by Program Name. - End point URL : http://localhost:9001/applicants/programNames ****************************************************************************************************************************/ @GetMapping("/{programName}") public ResponseEntity<ApplicantEntity> getApplicantByProgramName(@PathVariable("programName") String programName) throws ApplicantNotFoundException{ ApplicantEntity appEntity = service.getApplicantByProgramName(programName); return ResponseEntity.status(HttpStatus.OK).body(appEntity); } /**************************************************************************************************************************** - Method Name : updateApplicantById - Input Parameters : applicantid, ApplicantEntity - Return type : ResponseEntity<ApplicantEntity> - Author : Charul Gupta - Creation Date : 12-06-2020 - Description : Updating the applicant information entered by user into the database. - End point URL : http://localhost:9001/applicants/applicantid ****************************************************************************************************************************/ @PutMapping("/{applicantid}") public ResponseEntity<ApplicantEntity> updateApplicantById(@PathVariable("applicantid") Integer applicantid, @RequestBody ApplicantEntity entity) throws ApplicantNotFoundException{ ApplicantEntity appEntity = service.updateApplicantById(applicantid, entity); return ResponseEntity.status(HttpStatus.OK).body(appEntity); } }
UTF-8
Java
5,348
java
ApplicantController.java
Java
[ { "context": " : ApplicantController\r\n - Author : Charul Gupta\r\n - Creation Date : 12-06-2020\r\n - Description", "end": 204, "score": 0.9998765587806702, "start": 192, "tag": "NAME", "value": "Charul Gupta" }, { "context": " : List<ApplicantEntity> \r\n\t - Author : Charul Gupta\r\n\t - Creation Date : 12-06-2020\r\n\t - Descripti", "end": 1982, "score": 0.9998543858528137, "start": 1970, "tag": "NAME", "value": "Charul Gupta" }, { "context": "type : ResponseEntity\r\n\t - Author : Charul Gupta\r\n\t - Creation Date : 12-06-2020\r\n\t - Descripti", "end": 2699, "score": 0.9998780488967896, "start": 2687, "tag": "NAME", "value": "Charul Gupta" }, { "context": "nseEntity<ApplicantEntity>\r\n\t - Author : Charul Gupta\r\n\t - Creation Date : 12-06-2020\r\n\t - Descripti", "end": 3650, "score": 0.999886155128479, "start": 3638, "tag": "NAME", "value": "Charul Gupta" }, { "context": "nseEntity<ApplicantEntity>\r\n\t - Author : Charul Gupta\r\n\t - Creation Date : 12-06-2020\r\n\t - Descripti", "end": 4641, "score": 0.9998820424079895, "start": 4629, "tag": "NAME", "value": "Charul Gupta" } ]
null
[]
/**************************************************************************************************************************** - File Name : ApplicantController - Author : <NAME> - Creation Date : 12-06-2020 - Description : This is an end point controller to consume Application Management Services. ****************************************************************************************************************************/ package com.cg.uas.applicationmanagement.controller; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.cg.uas.applicationmanagement.dto.ApplicantEntity; import com.cg.uas.applicationmanagement.exception.ApplicantAlreadyExsistsException; import com.cg.uas.applicationmanagement.exception.ApplicantNotFoundException; import com.cg.uas.applicationmanagement.service.ApplicantService; @RestController @Validated @RequestMapping("/applicants") public class ApplicantController { @Autowired private ApplicantService service; /**************************************************************************************************************************** - Method Name : getAllApplicants - Input Parameters : void - Return type : List<ApplicantEntity> - Author : <NAME> - Creation Date : 12-06-2020 - Description : fetching the applicant information from the database. - End point URL : http://localhost:9001/applicants/getall ****************************************************************************************************************************/ @GetMapping("/getall") public List<ApplicantEntity> getAllApplicants() { return service.getAllApplicants(); } /**************************************************************************************************************************** - Method Name : addApplicant - Input Parameters : ApplicantEntity - Return type : ResponseEntity - Author : <NAME> - Creation Date : 12-06-2020 - Description : Inserting the applicant information entered by user into the database. - End point URL : http://localhost:9001/applicants/addApplicant ****************************************************************************************************************************/ @PostMapping("/addApplicant") public ResponseEntity<ApplicantEntity> addApplicant(@Valid @RequestBody ApplicantEntity entity) throws ApplicantAlreadyExsistsException{ ApplicantEntity appEntity = service.addApplicant(entity); return ResponseEntity.status(HttpStatus.OK).body(appEntity); } /**************************************************************************************************************************** - Method Name : getApplicantByProgramName - Input Parameters : programName - Return type : ResponseEntity<ApplicantEntity> - Author : <NAME> - Creation Date : 12-06-2020 - Description : Fetching the applicant information from the database by Program Name. - End point URL : http://localhost:9001/applicants/programNames ****************************************************************************************************************************/ @GetMapping("/{programName}") public ResponseEntity<ApplicantEntity> getApplicantByProgramName(@PathVariable("programName") String programName) throws ApplicantNotFoundException{ ApplicantEntity appEntity = service.getApplicantByProgramName(programName); return ResponseEntity.status(HttpStatus.OK).body(appEntity); } /**************************************************************************************************************************** - Method Name : updateApplicantById - Input Parameters : applicantid, ApplicantEntity - Return type : ResponseEntity<ApplicantEntity> - Author : <NAME> - Creation Date : 12-06-2020 - Description : Updating the applicant information entered by user into the database. - End point URL : http://localhost:9001/applicants/applicantid ****************************************************************************************************************************/ @PutMapping("/{applicantid}") public ResponseEntity<ApplicantEntity> updateApplicantById(@PathVariable("applicantid") Integer applicantid, @RequestBody ApplicantEntity entity) throws ApplicantNotFoundException{ ApplicantEntity appEntity = service.updateApplicantById(applicantid, entity); return ResponseEntity.status(HttpStatus.OK).body(appEntity); } }
5,318
0.566006
0.555535
115
44.504349
41.671673
181
false
false
0
0
0
0
0
0
1
false
false
14
20e000852361a32db67a7a42cb00d94e01cb4858
29,755,533,483,112
63c5aadd029fda4fd8ee4e8cba5cf7eede6a9d5d
/CS160 HW/Pattern Recognition/src/Brute.java
451ce7e46f61b2dbc68927d7a582e569d76c68ea
[]
no_license
TrishDaoLe/Algorithm
https://github.com/TrishDaoLe/Algorithm
41184fe4e2a2b84a97df3e7d9b36ddb6ac9b2a88
bc3560ff5cf70aa9d71b99e99731b0a232fb5738
refs/heads/master
2021-04-18T20:20:59.266000
2017-06-17T00:13:15
2017-06-17T00:13:15
94,589,037
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Arrays; public class Brute{ public Brute(Point stack[], int N) { //Sort to Natural Order - Makes it easier to draw a line to the 4-tuples endpoints Arrays.sort(stack); double slopeIJ; double slopeJK; double slopeKL; for (int i = 0; i<N; i++){ for (int j = i+1; j<N; j++){ slopeIJ = stack[i].slopeTo(stack[j]); for (int k = j+1; k<N; k++){ slopeJK = stack[j].slopeTo(stack[k]); //continue only if the first 3 points are colinear if(slopeIJ == slopeJK){ for (int l = k+1; l<N; l++){ slopeKL = stack[k].slopeTo(stack[l]); //StdOut.println("SLopeIJ: " + slopeIJ + " SlopeJK: " + slopeJK + " SlopeKL: " + slopeKL); if(slopeJK == slopeKL && slopeJK == slopeIJ && slopeKL == slopeIJ){ StdOut.println(stack[i] + " -> " + stack[j] + " -> " + stack[k] + " -> " + stack[l]); StdOut.println(i +" "+ j +" "+ k + " "+ l ); stack[i].draw(); stack[j].draw(); stack[k].draw(); stack[l].draw(); stack[i].drawTo(stack[l]); StdDraw.show(0); } } } } } } } public static void main(String[] args) { Stopwatch stopwatch = new Stopwatch(); String filename = args[0]; //rescale coordinates and turn on animation mode StdDraw.setXscale(0, 36000); StdDraw.setYscale(0, 36000); StdDraw.show(0); In in = new In(filename); int N = in.readInt(); Point stack[] = new Point[N]; for (int i = 0; i < N; i++) { int x = in.readInt(); int y = in.readInt(); Point p = new Point(x, y); stack[i] = p; } Brute brute = new Brute(stack, N); StdOut.println("Time in seconds = " + stopwatch.elapsedTime()); } }
UTF-8
Java
1,743
java
Brute.java
Java
[]
null
[]
import java.util.Arrays; public class Brute{ public Brute(Point stack[], int N) { //Sort to Natural Order - Makes it easier to draw a line to the 4-tuples endpoints Arrays.sort(stack); double slopeIJ; double slopeJK; double slopeKL; for (int i = 0; i<N; i++){ for (int j = i+1; j<N; j++){ slopeIJ = stack[i].slopeTo(stack[j]); for (int k = j+1; k<N; k++){ slopeJK = stack[j].slopeTo(stack[k]); //continue only if the first 3 points are colinear if(slopeIJ == slopeJK){ for (int l = k+1; l<N; l++){ slopeKL = stack[k].slopeTo(stack[l]); //StdOut.println("SLopeIJ: " + slopeIJ + " SlopeJK: " + slopeJK + " SlopeKL: " + slopeKL); if(slopeJK == slopeKL && slopeJK == slopeIJ && slopeKL == slopeIJ){ StdOut.println(stack[i] + " -> " + stack[j] + " -> " + stack[k] + " -> " + stack[l]); StdOut.println(i +" "+ j +" "+ k + " "+ l ); stack[i].draw(); stack[j].draw(); stack[k].draw(); stack[l].draw(); stack[i].drawTo(stack[l]); StdDraw.show(0); } } } } } } } public static void main(String[] args) { Stopwatch stopwatch = new Stopwatch(); String filename = args[0]; //rescale coordinates and turn on animation mode StdDraw.setXscale(0, 36000); StdDraw.setYscale(0, 36000); StdDraw.show(0); In in = new In(filename); int N = in.readInt(); Point stack[] = new Point[N]; for (int i = 0; i < N; i++) { int x = in.readInt(); int y = in.readInt(); Point p = new Point(x, y); stack[i] = p; } Brute brute = new Brute(stack, N); StdOut.println("Time in seconds = " + stopwatch.elapsedTime()); } }
1,743
0.537005
0.524383
67
25.02985
23.293053
100
false
false
0
0
0
0
0
0
3.641791
false
false
14
592d6b4cf32a719dc65950fd6cbee6b5b13d9ad0
31,903,017,137,463
00bc0f5405404aaaa02755503f028bcd52a504f7
/src/main/java/com/toxind/benchmark/thrid/proto1/Main.java
3f625abb71788aabc6d46e1fbcbeea73424d40b9
[]
no_license
ethonchen/benchmark
https://github.com/ethonchen/benchmark
cf86162d606060e304ca115343aa4349e1aa208b
48637ba7b2e41112a1bf34f2a814d7e00f95ae82
refs/heads/master
2021-01-19T21:28:52.416000
2013-05-09T03:44:59
2013-05-09T03:44:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.toxind.benchmark.thrid.proto1; //package com.taobao.ethon.thrid.proto1; // //import java.io.File; //import java.io.FileNotFoundException; //import java.io.FileOutputStream; //import java.io.IOException; // //import org.junit.Test; // //import com.proto.Person.Tom; // //public class Main { // // @Test // public void testOutput() throws FileNotFoundException, IOException{ // Tom.Builder t = Tom.newBuilder(); // System.out.println(((int)'a')+" " + ((int)'@') + " " +((int)'b')); // System.out.println(Integer.toHexString(((int)'a'))+" " + Integer.toHexString(((int)'@')) + " " +Integer.toHexString(((int)'b'))); // t.setEmail("a@b"); // t.setId(1); // t.setName("xxxx"); // Tom tom = t.build(); // System.out.println(tom); // tom.writeTo(new FileOutputStream(new File("src/main/java/com/proto/tom2.prodata"))); // } //}
UTF-8
Java
842
java
Main.java
Java
[]
null
[]
package com.toxind.benchmark.thrid.proto1; //package com.taobao.ethon.thrid.proto1; // //import java.io.File; //import java.io.FileNotFoundException; //import java.io.FileOutputStream; //import java.io.IOException; // //import org.junit.Test; // //import com.proto.Person.Tom; // //public class Main { // // @Test // public void testOutput() throws FileNotFoundException, IOException{ // Tom.Builder t = Tom.newBuilder(); // System.out.println(((int)'a')+" " + ((int)'@') + " " +((int)'b')); // System.out.println(Integer.toHexString(((int)'a'))+" " + Integer.toHexString(((int)'@')) + " " +Integer.toHexString(((int)'b'))); // t.setEmail("a@b"); // t.setId(1); // t.setName("xxxx"); // Tom tom = t.build(); // System.out.println(tom); // tom.writeTo(new FileOutputStream(new File("src/main/java/com/proto/tom2.prodata"))); // } //}
842
0.647268
0.642518
27
30.185184
29.780725
133
false
false
0
0
0
0
0
0
1.444444
false
false
14
8f003d616d5dc66f3659b4f4cd03cc60b69cdc24
6,614,249,667,873
c8349b442ad1cf6eb7700499df2b271cd290b5b3
/lib_plugin/src/main/java/com/csdk/plugin/activity/IPluginActivity.java
bcec32877a3dd947a3afba9e0a51399ffd6e05b4
[]
no_license
jingyuanGit/ChannelSdkProjects
https://github.com/jingyuanGit/ChannelSdkProjects
f565437f8339878abc7a76e25791448a5a807868
a070699962c1c09e4389093a25b394907941731c
refs/heads/master
2020-07-12T21:57:16.121000
2019-08-28T16:52:09
2019-08-28T16:52:09
204,916,277
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.csdk.plugin.activity; import android.annotation.TargetApi; import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.WindowManager.LayoutParams; import com.csdk.plugin.IPlugin; import com.csdk.plugin.other.PluginPackage; public interface IPluginActivity extends IPlugin { void onCreate(Bundle savedInstanceState); void onStart(); void attach(Activity proxyActivity, PluginPackage pluginPackage); void onRestart(); void onActivityResult(int requestCode, int resultCode, Intent data); void onResume(); void onPause(); void onStop(); void onDestroy(); void onSaveInstanceState(Bundle outState); void onNewIntent(Intent intent); void onRestoreInstanceState(Bundle savedInstanceState); boolean onTouchEvent(MotionEvent event); boolean onKeyUp(int keyCode, KeyEvent event); boolean onKeyDown(int keyCode, KeyEvent event); void onWindowAttributesChanged(LayoutParams params); void onWindowFocusChanged(boolean hasFocus); void onBackPressed(); boolean onCreateOptionsMenu(Menu menu); boolean onOptionsItemSelected(MenuItem item); void onConfigurationChanged(Configuration configuration); @TargetApi(23) void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults); }
UTF-8
Java
1,528
java
IPluginActivity.java
Java
[]
null
[]
package com.csdk.plugin.activity; import android.annotation.TargetApi; import android.app.Activity; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.WindowManager.LayoutParams; import com.csdk.plugin.IPlugin; import com.csdk.plugin.other.PluginPackage; public interface IPluginActivity extends IPlugin { void onCreate(Bundle savedInstanceState); void onStart(); void attach(Activity proxyActivity, PluginPackage pluginPackage); void onRestart(); void onActivityResult(int requestCode, int resultCode, Intent data); void onResume(); void onPause(); void onStop(); void onDestroy(); void onSaveInstanceState(Bundle outState); void onNewIntent(Intent intent); void onRestoreInstanceState(Bundle savedInstanceState); boolean onTouchEvent(MotionEvent event); boolean onKeyUp(int keyCode, KeyEvent event); boolean onKeyDown(int keyCode, KeyEvent event); void onWindowAttributesChanged(LayoutParams params); void onWindowFocusChanged(boolean hasFocus); void onBackPressed(); boolean onCreateOptionsMenu(Menu menu); boolean onOptionsItemSelected(MenuItem item); void onConfigurationChanged(Configuration configuration); @TargetApi(23) void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults); }
1,528
0.769634
0.768325
64
22.875
23.469063
95
false
false
0
0
0
0
0
0
0.65625
false
false
14
f6edb0319ebeb05095dd8c3055e723a02e2cf598
22,935,125,426,745
39b6f83641d1a80a48937c42beb6a73311aebc55
/integration-tests/main/src/main/java/io/quarkus/it/context/ContextPropagationResource.java
9d1e733ec03e4b549dbfd08b2814f34fdb612798
[ "Apache-2.0" ]
permissive
quarkusio/quarkus
https://github.com/quarkusio/quarkus
112ecda7236bc061920978ac49289da6259360f4
68af440f3081de7a26bbee655f74bb8b2c57c2d5
refs/heads/main
2023-09-04T06:39:33.043000
2023-09-04T05:44:43
2023-09-04T05:44:43
139,914,932
13,109
2,940
Apache-2.0
false
2023-09-14T21:31:23
2018-07-06T00:44:20
2023-09-14T21:29:58
2023-09-14T21:31:22
264,839
12,241
2,328
2,315
Java
false
false
package io.quarkus.it.context; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import jakarta.inject.Inject; import jakarta.transaction.Status; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; import jakarta.transaction.TransactionManager; import jakarta.transaction.Transactional; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.UriInfo; import org.eclipse.microprofile.context.ThreadContext; import org.wildfly.common.Assert; import io.quarkus.arc.Arc; import io.smallrye.context.SmallRyeManagedExecutor; @Path("context-propagation") public class ContextPropagationResource { @Inject RequestBean doNotRemove; @Inject SmallRyeManagedExecutor smallRyeAllExec; @Inject SmallRyeManagedExecutor allExec; @Inject ThreadContext context; @Inject ThreadContext smallRyeContext; @Inject TransactionManager transactionManager; @Path("managed-executor/created") @Transactional @GET public CompletionStage<String> testManagedExecutorCreated(@Context UriInfo uriInfo) throws SystemException { return testCompletionStage(allExec.completedFuture("OK"), uriInfo); } @Path("managed-executor/obtained") @Transactional @GET public CompletionStage<String> testManagedExecutorObtained(@Context UriInfo uriInfo) throws SystemException { // make sure we can also do that with CF we obtained from other sources, via ManagedExecutor CompletableFuture<String> completedFuture = CompletableFuture.completedFuture("OK"); return testCompletionStage(allExec.copy(completedFuture), uriInfo); } @Path("thread-context") @Transactional @GET public CompletionStage<String> testThreadContext(@Context UriInfo uriInfo) throws SystemException { // make sure we can also do that with CF we obtained from other sources, via ThreadContext CompletableFuture<String> completedFuture = CompletableFuture.completedFuture("OK"); return testCompletionStage(context.withContextCapture(completedFuture), uriInfo); } private CompletionStage<String> testCompletionStage(CompletionStage<String> stage, UriInfo uriInfo) throws SystemException { // Transaction Transaction t1 = transactionManager.getTransaction(); Assert.assertTrue(t1 != null); Assert.assertTrue(t1.getStatus() == Status.STATUS_ACTIVE); // ArC Assert.assertTrue(Arc.container().instance(RequestBean.class).isAvailable()); RequestBean rb1 = Arc.container().instance(RequestBean.class).get(); Assert.assertTrue(rb1 != null); String rbValue = rb1.callMe(); return stage.thenApplyAsync(text -> { // RESTEasy uriInfo.getAbsolutePath(); // ArC RequestBean rb2 = Arc.container().instance(RequestBean.class).get(); Assert.assertTrue(rb2 != null); Assert.assertTrue(rb2.callMe().contentEquals(rbValue)); // Transaction Transaction t2; try { t2 = transactionManager.getTransaction(); } catch (SystemException e) { throw new RuntimeException(e); } Assert.assertTrue(t1 == t2); try { Assert.assertTrue(t2.getStatus() == Status.STATUS_ACTIVE); } catch (SystemException e) { throw new RuntimeException(e); } return text; }); } }
UTF-8
Java
3,602
java
ContextPropagationResource.java
Java
[]
null
[]
package io.quarkus.it.context; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import jakarta.inject.Inject; import jakarta.transaction.Status; import jakarta.transaction.SystemException; import jakarta.transaction.Transaction; import jakarta.transaction.TransactionManager; import jakarta.transaction.Transactional; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.UriInfo; import org.eclipse.microprofile.context.ThreadContext; import org.wildfly.common.Assert; import io.quarkus.arc.Arc; import io.smallrye.context.SmallRyeManagedExecutor; @Path("context-propagation") public class ContextPropagationResource { @Inject RequestBean doNotRemove; @Inject SmallRyeManagedExecutor smallRyeAllExec; @Inject SmallRyeManagedExecutor allExec; @Inject ThreadContext context; @Inject ThreadContext smallRyeContext; @Inject TransactionManager transactionManager; @Path("managed-executor/created") @Transactional @GET public CompletionStage<String> testManagedExecutorCreated(@Context UriInfo uriInfo) throws SystemException { return testCompletionStage(allExec.completedFuture("OK"), uriInfo); } @Path("managed-executor/obtained") @Transactional @GET public CompletionStage<String> testManagedExecutorObtained(@Context UriInfo uriInfo) throws SystemException { // make sure we can also do that with CF we obtained from other sources, via ManagedExecutor CompletableFuture<String> completedFuture = CompletableFuture.completedFuture("OK"); return testCompletionStage(allExec.copy(completedFuture), uriInfo); } @Path("thread-context") @Transactional @GET public CompletionStage<String> testThreadContext(@Context UriInfo uriInfo) throws SystemException { // make sure we can also do that with CF we obtained from other sources, via ThreadContext CompletableFuture<String> completedFuture = CompletableFuture.completedFuture("OK"); return testCompletionStage(context.withContextCapture(completedFuture), uriInfo); } private CompletionStage<String> testCompletionStage(CompletionStage<String> stage, UriInfo uriInfo) throws SystemException { // Transaction Transaction t1 = transactionManager.getTransaction(); Assert.assertTrue(t1 != null); Assert.assertTrue(t1.getStatus() == Status.STATUS_ACTIVE); // ArC Assert.assertTrue(Arc.container().instance(RequestBean.class).isAvailable()); RequestBean rb1 = Arc.container().instance(RequestBean.class).get(); Assert.assertTrue(rb1 != null); String rbValue = rb1.callMe(); return stage.thenApplyAsync(text -> { // RESTEasy uriInfo.getAbsolutePath(); // ArC RequestBean rb2 = Arc.container().instance(RequestBean.class).get(); Assert.assertTrue(rb2 != null); Assert.assertTrue(rb2.callMe().contentEquals(rbValue)); // Transaction Transaction t2; try { t2 = transactionManager.getTransaction(); } catch (SystemException e) { throw new RuntimeException(e); } Assert.assertTrue(t1 == t2); try { Assert.assertTrue(t2.getStatus() == Status.STATUS_ACTIVE); } catch (SystemException e) { throw new RuntimeException(e); } return text; }); } }
3,602
0.694059
0.690172
98
35.7551
29.882103
128
false
false
0
0
0
0
0
0
0.540816
false
false
14
d2fc80f488a9a09f936ea884a8651d906de68644
23,948,737,674,852
6251ec8dd7f02c15174e897910f72aa37e9e3c51
/MultiThreading/src/main/java/multithread/MultiThread13.java
2b3171f1faab85ae6cf870abc08c245c6845eec4
[]
no_license
Wincher/JavaWorkout
https://github.com/Wincher/JavaWorkout
ff55ecdf6d2867ed56ec2e1f95e7cf7d41aee068
81e80bfb4aec823ffe625cc98330d123ffd1e3d6
refs/heads/master
2023-06-28T07:07:38.727000
2023-03-18T06:57:55
2023-03-18T07:14:32
99,265,446
0
0
null
false
2023-06-14T22:46:52
2017-08-03T18:56:37
2023-04-03T18:32:40
2023-06-14T22:46:52
392
0
0
1
Java
false
false
package multithread; import java.util.Map; import java.util.concurrent.*; /** * @author wincher * @date 26/08/2017 * 同步类容器使用 */ public class MultiThread13 { public static void main(String[] args) { useConcurrentMap(); useCopyOnWrite(); useQueue(); //带有时间延迟的队列 useDelayQueue(); } private static void useDelayQueue() { try { System.out.println("NetBar start running"); NetBar netBar = new NetBar(); Thread onNet = new Thread(netBar); onNet.start(); netBar.checkIn("zhangsan","123",1); netBar.checkIn("lisi","124",10); netBar.checkIn("wangwu","125",5); Thread.sleep(1000); netBar.isRunning = false; } catch(Exception e) { e.printStackTrace(); } } private static void useQueue() { //高性能无阻塞无界队列:ConcurrentLinkedQueue /* ConcurrentLinkedQueue<String> q = new ConcurrentLinkedQueue<String>(); q.offer("a"); q.offer("b"); q.offer("c"); q.offer("d"); q.offer("e"); q.add("f"); System.out.println(q.size()); System.out.println(q.poll()); //从头部取出队列,并从队列里删除元素 System.out.println(q.size()); System.out.println(q.peek()); System.out.println(q.size()); System.out.println(q); ArrayBlockingQueue<String> array = new ArrayBlockingQueue<String>(5); array.add("a"); array.add("b"); array.add("c"); array.add("d"); array.add("e"); array.add("f"); System.out.println(array.offer("a",3 ,TimeUnit.SECONDS)); */ //阻塞队列 /* LinkedBlockingQueue<String> q = new LinkedBlockingQueue<String>(); q.offer("a"); q.offer("b"); q.offer("c"); q.offer("d"); q.offer("e"); q.add("f"); System.out.println(q.size()); */ //没有缓冲的队列,生产者产生的数据直接会被消费者获取并消费 /* final SynchronousQueue<String> q = new SynchronousQueue<String>(); Thread t1 = new Thread(new Runnable() { @Override public void run() { try { System.out.println(q.take()); } catch (InterruptedException e) { e.printStackTrace(); } } }); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } t1.start(); Thread t2 = new Thread(new Runnable() { @Override public void run() { q.add("hello world!"); } }); t2.start(); */ //带有优先级的阻塞队列 /* PriorityBlockingQueue<Task> q = new PriorityBlockingQueue<Task>(); Task t1 = new Task(); t1.setId(3); t1.setName("id is 3"); Task t2 = new Task(); t2.setId(4); t2.setName("id is 4"); Task t3 = new Task(); t3.setId(1); t3.setName("id is 1"); q.add(t1); q.add(t2); q.add(t3); System.out.println("queue:" + q); try { System.out.println(q.take().getId()); System.out.println("queue:" + q); System.out.println(q.take().getId()); System.out.println(q.take().getId()); } catch (InterruptedException e) { e.printStackTrace(); } */ } private static void useCopyOnWrite() { CopyOnWriteArrayList<String> cwal = new CopyOnWriteArrayList<>(); CopyOnWriteArraySet<String> cwas = new CopyOnWriteArraySet<>(); cwal.add("hello"); System.out.println(cwal); } private static void useConcurrentMap() { ConcurrentHashMap<String, Object> chm = new ConcurrentHashMap<String,Object>(); chm.put("k1","v1"); chm.put("k2","v2"); chm.put("k3","v3"); chm.put("k4","v4"); chm.put("k4","v5"); //复合操作如果value存在不会存入,put则会覆盖原有value chm.putIfAbsent("k4","v6"); for (Map.Entry<String, Object> me : chm.entrySet()) { System.out.println("key: " + me.getKey() + ", value: " + me.getValue()); } } } class Task implements Comparable<Task> { private int id; private String name; 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; } @Override public int compareTo(Task o) { return this.id > o.id ? 1 : (this.id < o.id ? -1 : 0); } @Override public String toString() { return "Task{" + "id=" + id + ", name='" + name + '\'' + '}'; } } class NetBar implements Runnable { private DelayQueue<Person> queue = new DelayQueue<>(); public boolean isRunning = true; public void checkIn(String name, String id, int money) { Person p = new Person(name, id, 1000 * money + System.currentTimeMillis()); System.out.println("name: " + p.getName() + ", IdCard: " + p.getId() + ", money: " + money +"yuan, start..."); this.queue.add(p); } public void checkOut(Person person) { System.out.println("name: " + person.getName() + ", IdCard: " + person.getId() + "time end"); } @Override public void run() { while(isRunning) { try { Person p = queue.take(); checkOut(p); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("stop NetBar..."); } } class Person implements Delayed { private String name; /** * idCard */ private String id; /** * 截止时间 */ private long endTime; /** * 定义时间工具类 */ private TimeUnit timeUnit = TimeUnit.SECONDS; public Person(String name, String id, long endTime) { this.name = name; this.id = id; this.endTime = endTime; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } /** * 用来判断是否到了截止时间 * @param unit * @return */ @Override public long getDelay(TimeUnit unit) { return endTime - System.currentTimeMillis(); } // @Override public int compareTo(Delayed o) { Person p = (Person)o; return this.getDelay(this.timeUnit) - p.getDelay(this.timeUnit) > 0 ? 1 : 0; } }
UTF-8
Java
5,894
java
MultiThread13.java
Java
[ { "context": "ap;\nimport java.util.concurrent.*;\n\n/**\n * @author wincher\n * @date 26/08/2017\n * 同步类容器使用\n */\npublic class M", "end": 98, "score": 0.9995911717414856, "start": 91, "tag": "USERNAME", "value": "wincher" } ]
null
[]
package multithread; import java.util.Map; import java.util.concurrent.*; /** * @author wincher * @date 26/08/2017 * 同步类容器使用 */ public class MultiThread13 { public static void main(String[] args) { useConcurrentMap(); useCopyOnWrite(); useQueue(); //带有时间延迟的队列 useDelayQueue(); } private static void useDelayQueue() { try { System.out.println("NetBar start running"); NetBar netBar = new NetBar(); Thread onNet = new Thread(netBar); onNet.start(); netBar.checkIn("zhangsan","123",1); netBar.checkIn("lisi","124",10); netBar.checkIn("wangwu","125",5); Thread.sleep(1000); netBar.isRunning = false; } catch(Exception e) { e.printStackTrace(); } } private static void useQueue() { //高性能无阻塞无界队列:ConcurrentLinkedQueue /* ConcurrentLinkedQueue<String> q = new ConcurrentLinkedQueue<String>(); q.offer("a"); q.offer("b"); q.offer("c"); q.offer("d"); q.offer("e"); q.add("f"); System.out.println(q.size()); System.out.println(q.poll()); //从头部取出队列,并从队列里删除元素 System.out.println(q.size()); System.out.println(q.peek()); System.out.println(q.size()); System.out.println(q); ArrayBlockingQueue<String> array = new ArrayBlockingQueue<String>(5); array.add("a"); array.add("b"); array.add("c"); array.add("d"); array.add("e"); array.add("f"); System.out.println(array.offer("a",3 ,TimeUnit.SECONDS)); */ //阻塞队列 /* LinkedBlockingQueue<String> q = new LinkedBlockingQueue<String>(); q.offer("a"); q.offer("b"); q.offer("c"); q.offer("d"); q.offer("e"); q.add("f"); System.out.println(q.size()); */ //没有缓冲的队列,生产者产生的数据直接会被消费者获取并消费 /* final SynchronousQueue<String> q = new SynchronousQueue<String>(); Thread t1 = new Thread(new Runnable() { @Override public void run() { try { System.out.println(q.take()); } catch (InterruptedException e) { e.printStackTrace(); } } }); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } t1.start(); Thread t2 = new Thread(new Runnable() { @Override public void run() { q.add("hello world!"); } }); t2.start(); */ //带有优先级的阻塞队列 /* PriorityBlockingQueue<Task> q = new PriorityBlockingQueue<Task>(); Task t1 = new Task(); t1.setId(3); t1.setName("id is 3"); Task t2 = new Task(); t2.setId(4); t2.setName("id is 4"); Task t3 = new Task(); t3.setId(1); t3.setName("id is 1"); q.add(t1); q.add(t2); q.add(t3); System.out.println("queue:" + q); try { System.out.println(q.take().getId()); System.out.println("queue:" + q); System.out.println(q.take().getId()); System.out.println(q.take().getId()); } catch (InterruptedException e) { e.printStackTrace(); } */ } private static void useCopyOnWrite() { CopyOnWriteArrayList<String> cwal = new CopyOnWriteArrayList<>(); CopyOnWriteArraySet<String> cwas = new CopyOnWriteArraySet<>(); cwal.add("hello"); System.out.println(cwal); } private static void useConcurrentMap() { ConcurrentHashMap<String, Object> chm = new ConcurrentHashMap<String,Object>(); chm.put("k1","v1"); chm.put("k2","v2"); chm.put("k3","v3"); chm.put("k4","v4"); chm.put("k4","v5"); //复合操作如果value存在不会存入,put则会覆盖原有value chm.putIfAbsent("k4","v6"); for (Map.Entry<String, Object> me : chm.entrySet()) { System.out.println("key: " + me.getKey() + ", value: " + me.getValue()); } } } class Task implements Comparable<Task> { private int id; private String name; 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; } @Override public int compareTo(Task o) { return this.id > o.id ? 1 : (this.id < o.id ? -1 : 0); } @Override public String toString() { return "Task{" + "id=" + id + ", name='" + name + '\'' + '}'; } } class NetBar implements Runnable { private DelayQueue<Person> queue = new DelayQueue<>(); public boolean isRunning = true; public void checkIn(String name, String id, int money) { Person p = new Person(name, id, 1000 * money + System.currentTimeMillis()); System.out.println("name: " + p.getName() + ", IdCard: " + p.getId() + ", money: " + money +"yuan, start..."); this.queue.add(p); } public void checkOut(Person person) { System.out.println("name: " + person.getName() + ", IdCard: " + person.getId() + "time end"); } @Override public void run() { while(isRunning) { try { Person p = queue.take(); checkOut(p); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("stop NetBar..."); } } class Person implements Delayed { private String name; /** * idCard */ private String id; /** * 截止时间 */ private long endTime; /** * 定义时间工具类 */ private TimeUnit timeUnit = TimeUnit.SECONDS; public Person(String name, String id, long endTime) { this.name = name; this.id = id; this.endTime = endTime; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } /** * 用来判断是否到了截止时间 * @param unit * @return */ @Override public long getDelay(TimeUnit unit) { return endTime - System.currentTimeMillis(); } // @Override public int compareTo(Delayed o) { Person p = (Person)o; return this.getDelay(this.timeUnit) - p.getDelay(this.timeUnit) > 0 ? 1 : 0; } }
5,894
0.615999
0.602873
280
19.139286
19.187382
112
false
false
0
0
0
0
0
0
2.175
false
false
14
6f09a1df655a6afc298e833bdbefa29078720641
17,128,329,611,166
aa6b41a011eb0bbd7a82246a054ebbda84bf81da
/src/src/tictactoe/CommunicatingServerInterface.java
b4b488d32383bd0c2cf73826332edccd9f3e7676
[]
no_license
donpereira147/TicTacToe
https://github.com/donpereira147/TicTacToe
095b16c11344ece1240809340ab3fc0fac2d235e
2f00e2e1a8685f28d6a3f5180841cbd2970ac105
refs/heads/master
2022-09-16T01:24:08.428000
2020-05-27T22:39:56
2020-05-27T22:39:56
267,440,417
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package tictactoe; import java.rmi.*; public interface CommunicatingServerInterface extends Remote { void sendInvite(String ipSender, String otherIP, String msgType) throws RemoteException; String receiveInvite(String ipSender, String ipReceiver, String msgType) throws RemoteException; String makeMove(String ipSender, String ipReceiver, String board) throws RemoteException; }
UTF-8
Java
393
java
CommunicatingServerInterface.java
Java
[]
null
[]
package tictactoe; import java.rmi.*; public interface CommunicatingServerInterface extends Remote { void sendInvite(String ipSender, String otherIP, String msgType) throws RemoteException; String receiveInvite(String ipSender, String ipReceiver, String msgType) throws RemoteException; String makeMove(String ipSender, String ipReceiver, String board) throws RemoteException; }
393
0.811705
0.811705
10
38.299999
40.858414
100
false
false
0
0
0
0
0
0
1.1
false
false
14
35f243318fe6266f275bed4ff7c1020e6824ea9f
9,929,964,388,408
634129b50390c5572bf7534823bb60d1c4283279
/src/main/java/com/xunyanhui/service/PerformanceService.java
6bd7e7fd2efd42bfa66db5418f3cd7fd4060309b
[]
no_license
HoYuanhao/bangban
https://github.com/HoYuanhao/bangban
bf16fc607ecf6c8087c3ef4f4a8dd19d12cde686
14ca4628c2ae9e74babb0ec5731b5f9739d6ebfa
refs/heads/master
2021-07-07T09:39:39.335000
2017-10-02T07:54:25
2017-10-02T07:54:25
105,505,787
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xunyanhui.service; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import com.xunyanhui.bean.PerfBean; import com.xunyanhui.bean.PerforBean; import com.xunyanhui.bean.Performance; import com.xunyanhui.model.EntryRecordN; import com.xunyanhui.model.User; public interface PerformanceService { public final static int NORMAL = 0; // 正常 public final static int SALARY_DESC = 1;// 价格从高到低 public final static int SALARY_ASC = 2;// 价格从低到高 public final static int POPULARITY_DESC = 3;// 人气从高到低 public final static int POPULARITY_ASC = 4;// 人气从低到高 public final static int IN_REVIEW = 1;// 审核中 public final static int AUDIT_PASS = 2;// 审核通过 public final static int IN_TREATMENT = 3;// 投诉处理中 public final static int END = 4;// 下架 public List<PerforBean> getPerformanceList(Date date, int order, String type, int page, String uid,String ccity); public boolean addPerformance(PerfBean perfBean, String pid, String pic); public Performance getPerformance(String perforId, HttpServletRequest request); /* * 用户报名 */ public int performanceSignup(User user, String peformanceId, int price, String desc); /* * 用户邀请报名 */ public int performanceInvite(String artistid, String performanceId, String userid); /* * 用户接受邀请报名 */ public int enableInvite(String artistid, String performanceId, int price, String desc); public List<PerforBean> searchByKey(Date date, String key, int page, String uid,String ccity); /** * 获取指定艺人的指定演艺活动的报名情况的详细内容 * * @param peformanceId * 演艺id * @param artistId * 艺人id */ public EntryRecordN getEntryRecord(String artistId, String performanceId); }
UTF-8
Java
1,921
java
PerformanceService.java
Java
[]
null
[]
package com.xunyanhui.service; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import com.xunyanhui.bean.PerfBean; import com.xunyanhui.bean.PerforBean; import com.xunyanhui.bean.Performance; import com.xunyanhui.model.EntryRecordN; import com.xunyanhui.model.User; public interface PerformanceService { public final static int NORMAL = 0; // 正常 public final static int SALARY_DESC = 1;// 价格从高到低 public final static int SALARY_ASC = 2;// 价格从低到高 public final static int POPULARITY_DESC = 3;// 人气从高到低 public final static int POPULARITY_ASC = 4;// 人气从低到高 public final static int IN_REVIEW = 1;// 审核中 public final static int AUDIT_PASS = 2;// 审核通过 public final static int IN_TREATMENT = 3;// 投诉处理中 public final static int END = 4;// 下架 public List<PerforBean> getPerformanceList(Date date, int order, String type, int page, String uid,String ccity); public boolean addPerformance(PerfBean perfBean, String pid, String pic); public Performance getPerformance(String perforId, HttpServletRequest request); /* * 用户报名 */ public int performanceSignup(User user, String peformanceId, int price, String desc); /* * 用户邀请报名 */ public int performanceInvite(String artistid, String performanceId, String userid); /* * 用户接受邀请报名 */ public int enableInvite(String artistid, String performanceId, int price, String desc); public List<PerforBean> searchByKey(Date date, String key, int page, String uid,String ccity); /** * 获取指定艺人的指定演艺活动的报名情况的详细内容 * * @param peformanceId * 演艺id * @param artistId * 艺人id */ public EntryRecordN getEntryRecord(String artistId, String performanceId); }
1,921
0.718447
0.713307
59
27.677965
29.626169
114
false
false
0
0
0
0
0
0
1.372881
false
false
14
c1531f16038b72d3bb9f439c5ac4d0d2ddfae96e
12,386,685,744,068
8e17c72f50d78c52a9ba5837cbf28e0a05470424
/src/main/java/com/laotek/churchguru/web/client/activity/user/GetUserDetailsResult.java
aca5cbf3d90d0e87ca1df15f07e3c368c1a4f514
[]
no_license
larryoke/churchguru-web
https://github.com/larryoke/churchguru-web
7cbaf6ccfabc96727b9ce13b519c59ec9c449a0f
2d33a30a59a82d56a8e827e2a59286abf84e70a1
refs/heads/master
2021-01-11T14:58:31.286000
2018-12-05T17:18:46
2018-12-05T17:18:46
80,263,931
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.laotek.churchguru.web.client.activity.user; import java.util.ArrayList; import java.util.List; import net.customware.gwt.dispatch.shared.Result; import com.laotek.churchguru.web.shared.UserDto; public class GetUserDetailsResult implements Result{ private List<UserDto> dtos = new ArrayList<UserDto>(); public List<UserDto> getDtos() { return dtos; } public void setDtos(List<UserDto> dtos) { this.dtos = dtos; } }
UTF-8
Java
443
java
GetUserDetailsResult.java
Java
[]
null
[]
package com.laotek.churchguru.web.client.activity.user; import java.util.ArrayList; import java.util.List; import net.customware.gwt.dispatch.shared.Result; import com.laotek.churchguru.web.shared.UserDto; public class GetUserDetailsResult implements Result{ private List<UserDto> dtos = new ArrayList<UserDto>(); public List<UserDto> getDtos() { return dtos; } public void setDtos(List<UserDto> dtos) { this.dtos = dtos; } }
443
0.760722
0.760722
21
20.095238
21.394047
55
false
false
0
0
0
0
0
0
0.857143
false
false
14
060c35d8c6c0441a2b743b8f1c5b0ad2b85e04d9
15,144,054,690,706
3a03af0431787193ad946f251364c266263b7d14
/src/Maintenance/TicketCategoriesTests.java
72a8bc48b1df5e8c15d6099fcb3c723a3beb8043
[]
no_license
resmiar/CashControlTests
https://github.com/resmiar/CashControlTests
a70ed75dc231e8cfb12d8ba0fb297d6899abf949
6335b0af1c35690f56d7d11c11c836769f5f2a9e
refs/heads/master
2021-01-24T18:57:41.830000
2018-10-03T12:07:21
2018-10-03T12:07:21
123,238,499
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Maintenance; import org.testng.Assert; import org.testng.annotations.Test; import Pages.Maintenance.SalesRepsPage; import Pages.Maintenance.TicketCategoriesPage; public class TicketCategoriesTests extends BaseTest{ @Test //To verify that the edit attendance string functionality is working properly void checkEditingAttendanceAccount() { TicketCategoriesPage.goTo(); TicketCategoriesPage.editAttendanceString(); Assert.assertTrue(TicketCategoriesPage.isEdited(), "Attendance String is not edited"); TicketCategoriesPage.close(); } @Test //To verify that the edit attendance string functionality is working properly void checkEditingRevenueAccount() { TicketCategoriesPage.goTo(); TicketCategoriesPage.editRevenueString(); Assert.assertTrue(TicketCategoriesPage.isEdited(), "Revenue String is not edited"); TicketCategoriesPage.close(); } @Test //To verify that the cancel functionality is working properly void cancelEditing() { TicketCategoriesPage.goTo(); TicketCategoriesPage.editAndCancelCategory(); Assert.assertTrue(TicketCategoriesPage.isEdited(), "Revenue String is edited"); TicketCategoriesPage.close(); } }
UTF-8
Java
1,221
java
TicketCategoriesTests.java
Java
[]
null
[]
package Maintenance; import org.testng.Assert; import org.testng.annotations.Test; import Pages.Maintenance.SalesRepsPage; import Pages.Maintenance.TicketCategoriesPage; public class TicketCategoriesTests extends BaseTest{ @Test //To verify that the edit attendance string functionality is working properly void checkEditingAttendanceAccount() { TicketCategoriesPage.goTo(); TicketCategoriesPage.editAttendanceString(); Assert.assertTrue(TicketCategoriesPage.isEdited(), "Attendance String is not edited"); TicketCategoriesPage.close(); } @Test //To verify that the edit attendance string functionality is working properly void checkEditingRevenueAccount() { TicketCategoriesPage.goTo(); TicketCategoriesPage.editRevenueString(); Assert.assertTrue(TicketCategoriesPage.isEdited(), "Revenue String is not edited"); TicketCategoriesPage.close(); } @Test //To verify that the cancel functionality is working properly void cancelEditing() { TicketCategoriesPage.goTo(); TicketCategoriesPage.editAndCancelCategory(); Assert.assertTrue(TicketCategoriesPage.isEdited(), "Revenue String is edited"); TicketCategoriesPage.close(); } }
1,221
0.765766
0.765766
38
30.078947
26.58688
88
false
false
0
0
0
0
0
0
1.605263
false
false
14