id
int64 22
34.9k
| original_code
stringlengths 31
107k
| code_wo_comment
stringlengths 29
77.3k
| cleancode
stringlengths 25
62.1k
| repo
stringlengths 6
65
| label
sequencelengths 4
4
|
---|---|---|---|---|---|
17,338 | @Test
@Ignore("Test execution is depending on server technical characteristics.")
// ToDo: Need to rewrite.
public void Should_ignoreExceptionsFromTask()
throws Exception {
ITask taskMock1 = mock(ITask.class), taskMock2 = mock(ITask.class);
doThrow(new TaskExecutionException("Whoops!")).when(taskMock1).execute();
thread.execute(taskMock1);
verify(taskMock1, timeout(100)).execute();
Thread.sleep(200);
thread.execute(taskMock2);
verify(taskMock2, timeout(100)).execute(); } | @Test
@Ignore("Test execution is depending on server technical characteristics.")
public void Should_ignoreExceptionsFromTask()
throws Exception {
ITask taskMock1 = mock(ITask.class), taskMock2 = mock(ITask.class);
doThrow(new TaskExecutionException("Whoops!")).when(taskMock1).execute();
thread.execute(taskMock1);
verify(taskMock1, timeout(100)).execute();
Thread.sleep(200);
thread.execute(taskMock2);
verify(taskMock2, timeout(100)).execute(); } | @test @ignore("test execution is depending on server technical characteristics.") public void should_ignoreexceptionsfromtask() throws exception { itask taskmock1 = mock(itask.class), taskmock2 = mock(itask.class); dothrow(new taskexecutionexception("whoops!")).when(taskmock1).execute(); thread.execute(taskmock1); verify(taskmock1, timeout(100)).execute(); thread.sleep(200); thread.execute(taskmock2); verify(taskmock2, timeout(100)).execute(); } | d-protsenko/smartactors-core | [
0,
1,
0,
0
] |
25,637 | @Override
double getTurnInput(HumanInput humanInput) {
// TODO: Maybe sine curve is more appropriate for turning?
// Pass the raw turn value through an input curve, then apply the turn sensitivity.
return Util.applyInputCurve(humanInput.getGamePad().rs().getHorizontal(), .75, 3) * turnSensitivity;
} | @Override
double getTurnInput(HumanInput humanInput) {
return Util.applyInputCurve(humanInput.getGamePad().rs().getHorizontal(), .75, 3) * turnSensitivity;
} | @override double getturninput(humaninput humaninput) { return util.applyinputcurve(humaninput.getgamepad().rs().gethorizontal(), .75, 3) * turnsensitivity; } | first-1251/exp-drive | [
1,
0,
0,
0
] |
17,495 | public ReloadableType getSuperRtype() {
if (superRtype != null) {
return superRtype;
}
if (superclazz == null) {
// Not filled in yet? Why is this code different to the interface case?
String name = this.getSlashedSupertypeName();
if (name == null) {
return null;
}
else {
ReloadableType rtype = typeRegistry.getReloadableSuperType(name);
superRtype = rtype;
return superRtype;
}
}
else {
ClassLoader superClassLoader = superclazz.getClassLoader();
TypeRegistry superTypeRegistry = TypeRegistry.getTypeRegistryFor(superClassLoader);
superRtype = superTypeRegistry.getReloadableType(superclazz);
return superRtype;
}
} | public ReloadableType getSuperRtype() {
if (superRtype != null) {
return superRtype;
}
if (superclazz == null) {
String name = this.getSlashedSupertypeName();
if (name == null) {
return null;
}
else {
ReloadableType rtype = typeRegistry.getReloadableSuperType(name);
superRtype = rtype;
return superRtype;
}
}
else {
ClassLoader superClassLoader = superclazz.getClassLoader();
TypeRegistry superTypeRegistry = TypeRegistry.getTypeRegistryFor(superClassLoader);
superRtype = superTypeRegistry.getReloadableType(superclazz);
return superRtype;
}
} | public reloadabletype getsuperrtype() { if (superrtype != null) { return superrtype; } if (superclazz == null) { string name = this.getslashedsupertypename(); if (name == null) { return null; } else { reloadabletype rtype = typeregistry.getreloadablesupertype(name); superrtype = rtype; return superrtype; } } else { classloader superclassloader = superclazz.getclassloader(); typeregistry supertyperegistry = typeregistry.gettyperegistryfor(superclassloader); superrtype = supertyperegistry.getreloadabletype(superclazz); return superrtype; } } | crudolf/spring-loaded | [
1,
0,
0,
0
] |
33,952 | public boolean waitForExpectedReplicaMap(final long timeoutMs, YBTable table,
Map<String, List<List<Integer>>> replicaMapExpected) {
Condition replicaMapCondition = new ReplicaMapCondition(table, replicaMapExpected, timeoutMs);
return waitForCondition(replicaMapCondition, timeoutMs);
} | public boolean waitForExpectedReplicaMap(final long timeoutMs, YBTable table,
Map<String, List<List<Integer>>> replicaMapExpected) {
Condition replicaMapCondition = new ReplicaMapCondition(table, replicaMapExpected, timeoutMs);
return waitForCondition(replicaMapCondition, timeoutMs);
} | public boolean waitforexpectedreplicamap(final long timeoutms, ybtable table, map<string, list<list<integer>>> replicamapexpected) { condition replicamapcondition = new replicamapcondition(table, replicamapexpected, timeoutms); return waitforcondition(replicamapcondition, timeoutms); } | def-/yugabyte-db | [
1,
0,
0,
0
] |
25,790 | @Test
public void testBlowingUpWithDuplicateLoaders() {
KeyValuePairLoader kvpl = new KeyValuePairLoader();
kvpl.setKeyValuePairs(cmdLineArgsWFullClassName);
try {
AndHowConfiguration config = AndHowTestConfig.instance()
.setLoaders(kvpl, kvpl)
.addOverrideGroups(configPtGroups);
AndHow.setConfig(config);
AndHow.instance();
fail(); //The line above should throw an error
} catch (AppFatalException ce) {
assertEquals(1, ce.getProblems().filter(ConstructionProblem.class).size());
assertTrue(ce.getProblems().filter(ConstructionProblem.class).get(0) instanceof ConstructionProblem.DuplicateLoader);
ConstructionProblem.DuplicateLoader dl = (ConstructionProblem.DuplicateLoader)ce.getProblems().filter(ConstructionProblem.class).get(0);
assertEquals(kvpl, dl.getLoader());
assertTrue(ce.getSampleDirectory().length() > 0);
File sampleDir = new File(ce.getSampleDirectory());
assertTrue(sampleDir.exists());
assertTrue(sampleDir.listFiles().length > 0);
}
} | @Test
public void testBlowingUpWithDuplicateLoaders() {
KeyValuePairLoader kvpl = new KeyValuePairLoader();
kvpl.setKeyValuePairs(cmdLineArgsWFullClassName);
try {
AndHowConfiguration config = AndHowTestConfig.instance()
.setLoaders(kvpl, kvpl)
.addOverrideGroups(configPtGroups);
AndHow.setConfig(config);
AndHow.instance();
fail();
} catch (AppFatalException ce) {
assertEquals(1, ce.getProblems().filter(ConstructionProblem.class).size());
assertTrue(ce.getProblems().filter(ConstructionProblem.class).get(0) instanceof ConstructionProblem.DuplicateLoader);
ConstructionProblem.DuplicateLoader dl = (ConstructionProblem.DuplicateLoader)ce.getProblems().filter(ConstructionProblem.class).get(0);
assertEquals(kvpl, dl.getLoader());
assertTrue(ce.getSampleDirectory().length() > 0);
File sampleDir = new File(ce.getSampleDirectory());
assertTrue(sampleDir.exists());
assertTrue(sampleDir.listFiles().length > 0);
}
} | @test public void testblowingupwithduplicateloaders() { keyvaluepairloader kvpl = new keyvaluepairloader(); kvpl.setkeyvaluepairs(cmdlineargswfullclassname); try { andhowconfiguration config = andhowtestconfig.instance() .setloaders(kvpl, kvpl) .addoverridegroups(configptgroups); andhow.setconfig(config); andhow.instance(); fail(); } catch (appfatalexception ce) { assertequals(1, ce.getproblems().filter(constructionproblem.class).size()); asserttrue(ce.getproblems().filter(constructionproblem.class).get(0) instanceof constructionproblem.duplicateloader); constructionproblem.duplicateloader dl = (constructionproblem.duplicateloader)ce.getproblems().filter(constructionproblem.class).get(0); assertequals(kvpl, dl.getloader()); asserttrue(ce.getsampledirectory().length() > 0); file sampledir = new file(ce.getsampledirectory()); asserttrue(sampledir.exists()); asserttrue(sampledir.listfiles().length > 0); } } | emafazillah/andhow | [
1,
0,
0,
0
] |
17,643 | public void bootstrapMessagingSystem(){
try{
messagingSystem = new MessagingSystem(ACTIVEMQ_BROKER_URI, ACTIVEMQ_BROKER_PORT);
messagingSystem.createConnection();
messagingSystem.createSession();
//TODO: handle topics, not just queues
messagingSystem.createDestination(ACTIVEMQ_DESTINATION_NAME);
messagingSystem.createProducer();
System.out.println("SolrToActiveMQComponent: Bootstrapping messaging system done.");
messagingSystem.validateConnection();
}
catch (JMSException e){
System.out.println("SolrToActiveMQComponent: Bootstrapping messaging system failed.\n" + e);
messagingSystem.invalidateConnection();
}
} | public void bootstrapMessagingSystem(){
try{
messagingSystem = new MessagingSystem(ACTIVEMQ_BROKER_URI, ACTIVEMQ_BROKER_PORT);
messagingSystem.createConnection();
messagingSystem.createSession();
messagingSystem.createDestination(ACTIVEMQ_DESTINATION_NAME);
messagingSystem.createProducer();
System.out.println("SolrToActiveMQComponent: Bootstrapping messaging system done.");
messagingSystem.validateConnection();
}
catch (JMSException e){
System.out.println("SolrToActiveMQComponent: Bootstrapping messaging system failed.\n" + e);
messagingSystem.invalidateConnection();
}
} | public void bootstrapmessagingsystem(){ try{ messagingsystem = new messagingsystem(activemq_broker_uri, activemq_broker_port); messagingsystem.createconnection(); messagingsystem.createsession(); messagingsystem.createdestination(activemq_destination_name); messagingsystem.createproducer(); system.out.println("solrtoactivemqcomponent: bootstrapping messaging system done."); messagingsystem.validateconnection(); } catch (jmsexception e){ system.out.println("solrtoactivemqcomponent: bootstrapping messaging system failed.\n" + e); messagingsystem.invalidateconnection(); } } | dbraga/solr2activemq | [
0,
1,
0,
0
] |
9,486 | public boolean shouldAcquire(String name) {
// the org.robolectric.res package lives in the base classloader, but not its tests; yuck.
int lastDot = name.lastIndexOf('.');
String pkgName = name.substring(0, lastDot == -1 ? 0 : lastDot);
if (pkgName.equals("org.robolectric.res")) {
return name.contains("Test");
}
if (name.matches("com\\.android\\.internal\\.R(\\$.*)?")) return true;
// Android SDK code almost universally refers to com.android.internal.R, except
// when refering to android.R.stylable, as in HorizontalScrollView. arghgh.
// See https://github.com/robolectric/robolectric/issues/521
if (name.equals("android.R$styleable")) return true;
return !(
name.matches(".*\\.R(|\\$[a-z]+)$")
|| CLASSES_TO_ALWAYS_DELEGATE.contains(name)
|| name.startsWith("java.")
|| name.startsWith("javax.")
|| name.startsWith("sun.")
|| name.startsWith("com.sun.")
|| name.startsWith("org.w3c.")
|| name.startsWith("org.xml.")
|| name.startsWith("org.junit")
|| name.startsWith("org.hamcrest")
|| name.startsWith("org.specs2") // allows for android projects with mixed scala\java tests to be
|| name.startsWith("scala.") // run with Maven Surefire (see the RoboSpecs project on github)
|| name.startsWith("org.sqlite.") // ugh, we're barfing while loading org.sqlite now for some reason?!? todo: still?
);
} | public boolean shouldAcquire(String name) {
int lastDot = name.lastIndexOf('.');
String pkgName = name.substring(0, lastDot == -1 ? 0 : lastDot);
if (pkgName.equals("org.robolectric.res")) {
return name.contains("Test");
}
if (name.matches("com\\.android\\.internal\\.R(\\$.*)?")) return true;
if (name.equals("android.R$styleable")) return true;
return !(
name.matches(".*\\.R(|\\$[a-z]+)$")
|| CLASSES_TO_ALWAYS_DELEGATE.contains(name)
|| name.startsWith("java.")
|| name.startsWith("javax.")
|| name.startsWith("sun.")
|| name.startsWith("com.sun.")
|| name.startsWith("org.w3c.")
|| name.startsWith("org.xml.")
|| name.startsWith("org.junit")
|| name.startsWith("org.hamcrest")
|| name.startsWith("org.specs2")
|| name.startsWith("scala.")
|| name.startsWith("org.sqlite.")
);
} | public boolean shouldacquire(string name) { int lastdot = name.lastindexof('.'); string pkgname = name.substring(0, lastdot == -1 ? 0 : lastdot); if (pkgname.equals("org.robolectric.res")) { return name.contains("test"); } if (name.matches("com\\.android\\.internal\\.r(\\$.*)?")) return true; if (name.equals("android.r$styleable")) return true; return !( name.matches(".*\\.r(|\\$[a-z]+)$") || classes_to_always_delegate.contains(name) || name.startswith("java.") || name.startswith("javax.") || name.startswith("sun.") || name.startswith("com.sun.") || name.startswith("org.w3c.") || name.startswith("org.xml.") || name.startswith("org.junit") || name.startswith("org.hamcrest") || name.startswith("org.specs2") || name.startswith("scala.") || name.startswith("org.sqlite.") ); } | ecgreb/robolectric | [
1,
0,
0,
0
] |
17,714 | public void writeBytes(int stream, byte[] b, int offset, int len) {
// TODO: optimize
final int end = offset + len;
for(int i=offset;i<end;i++)
writeByte(stream, b[i]);
} | public void writeBytes(int stream, byte[] b, int offset, int len) {
final int end = offset + len;
for(int i=offset;i<end;i++)
writeByte(stream, b[i]);
} | public void writebytes(int stream, byte[] b, int offset, int len) { final int end = offset + len; for(int i=offset;i<end;i++) writebyte(stream, b[i]); } | dannycho7/RTP_Latest | [
1,
0,
0,
0
] |
9,527 | public static VirtualFile createDir(Project project, final VirtualFile parent, final String name) {
final Ref<VirtualFile> result = new Ref<VirtualFile>();
new WriteCommandAction.Simple(project) {
@Override
protected void run() throws Throwable {
try {
VirtualFile dir = parent.findChild(name);
if (dir == null) {
dir = parent.createChildDirectory(this, name);
}
result.set(dir);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
}.execute();
return result.get();
} | public static VirtualFile createDir(Project project, final VirtualFile parent, final String name) {
final Ref<VirtualFile> result = new Ref<VirtualFile>();
new WriteCommandAction.Simple(project) {
@Override
protected void run() throws Throwable {
try {
VirtualFile dir = parent.findChild(name);
if (dir == null) {
dir = parent.createChildDirectory(this, name);
}
result.set(dir);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
}.execute();
return result.get();
} | public static virtualfile createdir(project project, final virtualfile parent, final string name) { final ref<virtualfile> result = new ref<virtualfile>(); new writecommandaction.simple(project) { @override protected void run() throws throwable { try { virtualfile dir = parent.findchild(name); if (dir == null) { dir = parent.createchilddirectory(this, name); } result.set(dir); } catch (ioexception e) { throw new runtimeexception(e); } } }.execute(); return result.get(); } | consulo/consulo-git | [
0,
1,
0,
0
] |
9,528 | @CEntryPoint(name = "execute")
public static int execute(IsolateThread thread, int statement) {
try {
boolean hasResult = statements.get(statement).execute();
if (hasResult) {
throw new SQLException("unexpected results on statement execute");
}
return statements.get(statement).getUpdateCount();
} catch (Throwable e) {
setError(e);
return -1;
} finally {
try {
statements.get(statement).close();
} catch(Throwable t) {
// Ignored. TODO: Do I have to handle this?
}
}
} | @CEntryPoint(name = "execute")
public static int execute(IsolateThread thread, int statement) {
try {
boolean hasResult = statements.get(statement).execute();
if (hasResult) {
throw new SQLException("unexpected results on statement execute");
}
return statements.get(statement).getUpdateCount();
} catch (Throwable e) {
setError(e);
return -1;
} finally {
try {
statements.get(statement).close();
} catch(Throwable t) {
}
}
} | @centrypoint(name = "execute") public static int execute(isolatethread thread, int statement) { try { boolean hasresult = statements.get(statement).execute(); if (hasresult) { throw new sqlexception("unexpected results on statement execute"); } return statements.get(statement).getupdatecount(); } catch (throwable e) { seterror(e); return -1; } finally { try { statements.get(statement).close(); } catch(throwable t) { } } } | csmu-cenr/gdbc | [
1,
0,
0,
0
] |
17,766 | @Test
@RunAsClient
public void simpleSession() throws InterruptedException, ExecutionException {
final String uuid = uuid();
try (ClosableResponse res = post(target("000", uuid, XHR), json(null))) {
// New line is a frame delimiter specific for xhr-polling"
assertEquals(Status.OK, res.getStatusInfo());
assertEquals("o\n", res.readEntity(String.class));
}
// After a session was established the server needs to accept requests for sending messages.
// Xhr-polling accepts messages as a list of JSON-encoded strings.
try (ClosableResponse res = post(target("000", uuid, XHR_SEND), json("[\"a\"]"))) {
assertEquals(Status.NO_CONTENT, res.getStatusInfo());
verifyEmptyEntity(res);
}
// We're using an echo service - we'll receive our message back. The message is encoded as an array 'a'.
try (ClosableResponse res = post(target("000", uuid, XHR), json(null))) {
assertEquals(Status.OK, res.getStatusInfo());
assertEquals("a[\"a\"]\n", res.readEntity(String.class));
}
// Sending messages to not existing sessions is invalid.
try (ClosableResponse res = post(target("000", "bad_session", XHR_SEND), json("[\"a\"]"))) {
verify404(XHR_SEND, res);
}
// The session must time out after 5 seconds of not having a receiving connection. The server must send a
// heartbeat frame every 25 seconds. The heartbeat frame contains a single h character. This delay may be
// configurable.
// TODO
// The server must not allow two receiving connections to wait on a single session. In such case the server must
// send a close frame to the new connection.
for (int i = 0; i < 10; i++) {
try (ClosableResponse res = post(target("000", uuid, XHR_SEND), json("[\"xxxxxx\"]"))) {
assertEquals(Status.NO_CONTENT, res.getStatusInfo());
}
}
// Due to the time it takes for an async request to be scheduled it might actually be the one that returns the
// 'another connection still open' error. Therefore we need to check both.
final Future<Response> asyncFuture = target("000", uuid, XHR).request().async().post(json(null));
try (ClosableResponse res = post(target("000", uuid, XHR), json(null))) {
assertEquals(Status.OK, res.getStatusInfo());
final String resPayload = res.readEntity(String.class);
try (ClosableResponse asyncRes = closable(asyncFuture.get())) {
assertEquals(Status.OK, asyncRes.getStatusInfo());
final String asyncResPayload = asyncRes.readEntity(String.class);
if (ENABLE_CONCURRENT_REQUESTS_TEST) {
final String expectedError = "c[2010,\"Another connection still open\"]\n";
if (!expectedError.equals(resPayload) && !expectedError.equals(asyncResPayload)) {
fail("Neither response had '" + expectedError + "'! [blocking=" + resPayload + ",async=" + asyncResPayload + "]");
}
final String expected = "a[\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\"]\n";
if (!expected.equals(resPayload) && !expected.equals(asyncResPayload)) {
fail("Neither response had '" + expected + "'! [blocking=" + resPayload + ",async=" + asyncResPayload + "]");
}
}
}
} finally {
asyncFuture.cancel(true);
}
} | @Test
@RunAsClient
public void simpleSession() throws InterruptedException, ExecutionException {
final String uuid = uuid();
try (ClosableResponse res = post(target("000", uuid, XHR), json(null))) {
assertEquals(Status.OK, res.getStatusInfo());
assertEquals("o\n", res.readEntity(String.class));
}
try (ClosableResponse res = post(target("000", uuid, XHR_SEND), json("[\"a\"]"))) {
assertEquals(Status.NO_CONTENT, res.getStatusInfo());
verifyEmptyEntity(res);
}
try (ClosableResponse res = post(target("000", uuid, XHR), json(null))) {
assertEquals(Status.OK, res.getStatusInfo());
assertEquals("a[\"a\"]\n", res.readEntity(String.class));
}
try (ClosableResponse res = post(target("000", "bad_session", XHR_SEND), json("[\"a\"]"))) {
verify404(XHR_SEND, res);
}
for (int i = 0; i < 10; i++) {
try (ClosableResponse res = post(target("000", uuid, XHR_SEND), json("[\"xxxxxx\"]"))) {
assertEquals(Status.NO_CONTENT, res.getStatusInfo());
}
}
final Future<Response> asyncFuture = target("000", uuid, XHR).request().async().post(json(null));
try (ClosableResponse res = post(target("000", uuid, XHR), json(null))) {
assertEquals(Status.OK, res.getStatusInfo());
final String resPayload = res.readEntity(String.class);
try (ClosableResponse asyncRes = closable(asyncFuture.get())) {
assertEquals(Status.OK, asyncRes.getStatusInfo());
final String asyncResPayload = asyncRes.readEntity(String.class);
if (ENABLE_CONCURRENT_REQUESTS_TEST) {
final String expectedError = "c[2010,\"Another connection still open\"]\n";
if (!expectedError.equals(resPayload) && !expectedError.equals(asyncResPayload)) {
fail("Neither response had '" + expectedError + "'! [blocking=" + resPayload + ",async=" + asyncResPayload + "]");
}
final String expected = "a[\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\"]\n";
if (!expected.equals(resPayload) && !expected.equals(asyncResPayload)) {
fail("Neither response had '" + expected + "'! [blocking=" + resPayload + ",async=" + asyncResPayload + "]");
}
}
}
} finally {
asyncFuture.cancel(true);
}
} | @test @runasclient public void simplesession() throws interruptedexception, executionexception { final string uuid = uuid(); try (closableresponse res = post(target("000", uuid, xhr), json(null))) { assertequals(status.ok, res.getstatusinfo()); assertequals("o\n", res.readentity(string.class)); } try (closableresponse res = post(target("000", uuid, xhr_send), json("[\"a\"]"))) { assertequals(status.no_content, res.getstatusinfo()); verifyemptyentity(res); } try (closableresponse res = post(target("000", uuid, xhr), json(null))) { assertequals(status.ok, res.getstatusinfo()); assertequals("a[\"a\"]\n", res.readentity(string.class)); } try (closableresponse res = post(target("000", "bad_session", xhr_send), json("[\"a\"]"))) { verify404(xhr_send, res); } for (int i = 0; i < 10; i++) { try (closableresponse res = post(target("000", uuid, xhr_send), json("[\"xxxxxx\"]"))) { assertequals(status.no_content, res.getstatusinfo()); } } final future<response> asyncfuture = target("000", uuid, xhr).request().async().post(json(null)); try (closableresponse res = post(target("000", uuid, xhr), json(null))) { assertequals(status.ok, res.getstatusinfo()); final string respayload = res.readentity(string.class); try (closableresponse asyncres = closable(asyncfuture.get())) { assertequals(status.ok, asyncres.getstatusinfo()); final string asyncrespayload = asyncres.readentity(string.class); if (enable_concurrent_requests_test) { final string expectederror = "c[2010,\"another connection still open\"]\n"; if (!expectederror.equals(respayload) && !expectederror.equals(asyncrespayload)) { fail("neither response had '" + expectederror + "'! [blocking=" + respayload + ",async=" + asyncrespayload + "]"); } final string expected = "a[\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\",\"xxxxxx\"]\n"; if (!expected.equals(respayload) && !expected.equals(asyncrespayload)) { fail("neither response had '" + expected + "'! [blocking=" + respayload + ",async=" + asyncrespayload + "]"); } } } } finally { asyncfuture.cancel(true); } } | dansiviter/cito-sockjs | [
1,
0,
0,
1
] |
9,593 | @Override
public boolean isConcurrentAccessSupported()
{
// Maybe we could support concurrent some time in the future
return false;
} | @Override
public boolean isConcurrentAccessSupported()
{
return false;
} | @override public boolean isconcurrentaccesssupported() { return false; } | elharo/plexus-archiver | [
0,
1,
0,
0
] |
9,601 | public void writeContent(HttpCarbonMessage httpOutboundRequest) {
if (handlerExecutor != null) {
handlerExecutor.executeAtTargetRequestReceiving(httpOutboundRequest);
}
BackPressureHandler backpressureHandler = Util.getBackPressureHandler(targetHandler.getContext());
Util.setBackPressureListener(httpOutboundRequest, backpressureHandler, httpOutboundRequest.getSourceContext());
resetTargetChannelState();
httpOutboundRequest.getHttpContentAsync().setMessageListener((httpContent -> {
//TODO:Until the listener is set, content writing happens in I/O thread. If writability changed
//while in I/O thread and DefaultBackPressureListener is engaged, there's a chance of I/O thread
//getting blocked. Cannot recreate, only a possibility.
Util.checkUnWritabilityAndNotify(targetHandler.getContext(), backpressureHandler);
this.channel.eventLoop().execute(() -> {
try {
senderReqRespStateManager.writeOutboundRequestEntity(httpOutboundRequest, httpContent);
} catch (Exception exception) {
String errorMsg = "Failed to send the request : "
+ exception.getMessage().toLowerCase(Locale.ENGLISH);
LOG.error(errorMsg, exception);
this.targetHandler.getHttpResponseFuture().notifyHttpListener(exception);
}
});
}));
} | public void writeContent(HttpCarbonMessage httpOutboundRequest) {
if (handlerExecutor != null) {
handlerExecutor.executeAtTargetRequestReceiving(httpOutboundRequest);
}
BackPressureHandler backpressureHandler = Util.getBackPressureHandler(targetHandler.getContext());
Util.setBackPressureListener(httpOutboundRequest, backpressureHandler, httpOutboundRequest.getSourceContext());
resetTargetChannelState();
httpOutboundRequest.getHttpContentAsync().setMessageListener((httpContent -> {
Util.checkUnWritabilityAndNotify(targetHandler.getContext(), backpressureHandler);
this.channel.eventLoop().execute(() -> {
try {
senderReqRespStateManager.writeOutboundRequestEntity(httpOutboundRequest, httpContent);
} catch (Exception exception) {
String errorMsg = "Failed to send the request : "
+ exception.getMessage().toLowerCase(Locale.ENGLISH);
LOG.error(errorMsg, exception);
this.targetHandler.getHttpResponseFuture().notifyHttpListener(exception);
}
});
}));
} | public void writecontent(httpcarbonmessage httpoutboundrequest) { if (handlerexecutor != null) { handlerexecutor.executeattargetrequestreceiving(httpoutboundrequest); } backpressurehandler backpressurehandler = util.getbackpressurehandler(targethandler.getcontext()); util.setbackpressurelistener(httpoutboundrequest, backpressurehandler, httpoutboundrequest.getsourcecontext()); resettargetchannelstate(); httpoutboundrequest.gethttpcontentasync().setmessagelistener((httpcontent -> { util.checkunwritabilityandnotify(targethandler.getcontext(), backpressurehandler); this.channel.eventloop().execute(() -> { try { senderreqrespstatemanager.writeoutboundrequestentity(httpoutboundrequest, httpcontent); } catch (exception exception) { string errormsg = "failed to send the request : " + exception.getmessage().tolowercase(locale.english); log.error(errormsg, exception); this.targethandler.gethttpresponsefuture().notifyhttplistener(exception); } }); })); } | gabilang/module-ballerina-http | [
0,
0,
1,
0
] |
1,413 | @GetMapping("/{viewId}/{rowId}/field/{fieldName}/zoomInto")
public JSONZoomInto getRowFieldZoomInto(
@PathVariable("windowId") final String windowIdStr,
@PathVariable(PARAM_ViewId) final String viewIdStr,
@PathVariable("rowId") final String rowId,
@PathVariable("fieldName") final String fieldName)
{
// userSession.assertLoggedIn(); // NOTE: not needed because we are forwarding to windowRestController
ViewId.ofViewIdString(viewIdStr, WindowId.fromJson(windowIdStr)); // just validate the windowId and viewId
// TODO: atm we are forwarding all calls to windowRestController hoping the document existing and has the same ID as view's row ID.
return windowRestController.getDocumentFieldZoomInto(windowIdStr, rowId, fieldName);
} | @GetMapping("/{viewId}/{rowId}/field/{fieldName}/zoomInto")
public JSONZoomInto getRowFieldZoomInto(
@PathVariable("windowId") final String windowIdStr,
@PathVariable(PARAM_ViewId) final String viewIdStr,
@PathVariable("rowId") final String rowId,
@PathVariable("fieldName") final String fieldName)
{
ViewId.ofViewIdString(viewIdStr, WindowId.fromJson(windowIdStr));
return windowRestController.getDocumentFieldZoomInto(windowIdStr, rowId, fieldName);
} | @getmapping("/{viewid}/{rowid}/field/{fieldname}/zoominto") public jsonzoominto getrowfieldzoominto( @pathvariable("windowid") final string windowidstr, @pathvariable(param_viewid) final string viewidstr, @pathvariable("rowid") final string rowid, @pathvariable("fieldname") final string fieldname) { viewid.ofviewidstring(viewidstr, windowid.fromjson(windowidstr)); return windowrestcontroller.getdocumentfieldzoominto(windowidstr, rowid, fieldname); } | focadiz/metasfresh | [
1,
0,
0,
0
] |
26,006 | public void bad() throws Throwable
{
String password = (new CWE319_Cleartext_Tx_Sensitive_Info__URLConnection_passwordAuth_61b()).badSource();
if (password != null)
{
/* POTENTIAL FLAW: Use password directly in PasswordAuthentication() */
PasswordAuthentication credentials = new PasswordAuthentication("user", password.toCharArray());
IO.writeLine(credentials.toString());
}
} | public void bad() throws Throwable
{
String password = (new CWE319_Cleartext_Tx_Sensitive_Info__URLConnection_passwordAuth_61b()).badSource();
if (password != null)
{
PasswordAuthentication credentials = new PasswordAuthentication("user", password.toCharArray());
IO.writeLine(credentials.toString());
}
} | public void bad() throws throwable { string password = (new cwe319_cleartext_tx_sensitive_info__urlconnection_passwordauth_61b()).badsource(); if (password != null) { passwordauthentication credentials = new passwordauthentication("user", password.tochararray()); io.writeline(credentials.tostring()); } } | diktat-static-analysis/juliet-benchmark-java | [
0,
0,
1,
0
] |
26,007 | private void goodG2B() throws Throwable
{
String password = (new CWE319_Cleartext_Tx_Sensitive_Info__URLConnection_passwordAuth_61b()).goodG2BSource();
if (password != null)
{
/* POTENTIAL FLAW: Use password directly in PasswordAuthentication() */
PasswordAuthentication credentials = new PasswordAuthentication("user", password.toCharArray());
IO.writeLine(credentials.toString());
}
} | private void goodG2B() throws Throwable
{
String password = (new CWE319_Cleartext_Tx_Sensitive_Info__URLConnection_passwordAuth_61b()).goodG2BSource();
if (password != null)
{
PasswordAuthentication credentials = new PasswordAuthentication("user", password.toCharArray());
IO.writeLine(credentials.toString());
}
} | private void goodg2b() throws throwable { string password = (new cwe319_cleartext_tx_sensitive_info__urlconnection_passwordauth_61b()).goodg2bsource(); if (password != null) { passwordauthentication credentials = new passwordauthentication("user", password.tochararray()); io.writeline(credentials.tostring()); } } | diktat-static-analysis/juliet-benchmark-java | [
0,
0,
1,
0
] |
34,231 | @SuppressWarnings("deprecation")
private void send(Iterator<TableRef> tableRefIterator) throws SQLException {
int i = 0;
long[] serverTimeStamps = null;
boolean sendAll = false;
if (tableRefIterator == null) {
serverTimeStamps = validateAll();
tableRefIterator = mutations.keySet().iterator();
sendAll = true;
}
Map<ImmutableBytesPtr, RowMutationState> valuesMap;
Map<TableInfo,List<Mutation>> physicalTableMutationMap = Maps.newLinkedHashMap();
// add tracing for this operation
try (TraceScope trace = Tracing.startNewSpan(connection, "Committing mutations to tables")) {
Span span = trace.getSpan();
ImmutableBytesWritable indexMetaDataPtr = new ImmutableBytesWritable();
while (tableRefIterator.hasNext()) {
// at this point we are going through mutations for each table
final TableRef tableRef = tableRefIterator.next();
valuesMap = mutations.get(tableRef);
if (valuesMap == null || valuesMap.isEmpty()) {
continue;
}
// Validate as we go if transactional since we can undo if a problem occurs (which is unlikely)
long serverTimestamp = serverTimeStamps == null ? validateAndGetServerTimestamp(tableRef, valuesMap) : serverTimeStamps[i++];
Long scn = connection.getSCN();
long mutationTimestamp = scn == null ? HConstants.LATEST_TIMESTAMP : scn;
final PTable table = tableRef.getTable();
Iterator<Pair<PName,List<Mutation>>> mutationsIterator = addRowMutations(tableRef, valuesMap, mutationTimestamp, serverTimestamp, false, sendAll);
// build map from physical table to mutation list
boolean isDataTable = true;
while (mutationsIterator.hasNext()) {
Pair<PName,List<Mutation>> pair = mutationsIterator.next();
PName hTableName = pair.getFirst();
List<Mutation> mutationList = pair.getSecond();
TableInfo tableInfo = new TableInfo(isDataTable, hTableName, tableRef);
List<Mutation> oldMutationList = physicalTableMutationMap.put(tableInfo, mutationList);
if (oldMutationList!=null)
mutationList.addAll(0, oldMutationList);
isDataTable = false;
}
// For transactions, track the statement indexes as we send data
// over because our CommitException should include all statements
// involved in the transaction since none of them would have been
// committed in the event of a failure.
if (table.isTransactional()) {
addUncommittedStatementIndexes(valuesMap.values());
if (txMutations.isEmpty()) {
txMutations = Maps.newHashMapWithExpectedSize(mutations.size());
}
// Keep all mutations we've encountered until a commit or rollback.
// This is not ideal, but there's not good way to get the values back
// in the event that we need to replay the commit.
// Copy TableRef so we have the original PTable and know when the
// indexes have changed.
joinMutationState(new TableRef(tableRef), valuesMap, txMutations);
}
}
long serverTimestamp = HConstants.LATEST_TIMESTAMP;
Iterator<Entry<TableInfo, List<Mutation>>> mutationsIterator = physicalTableMutationMap.entrySet().iterator();
while (mutationsIterator.hasNext()) {
Entry<TableInfo, List<Mutation>> pair = mutationsIterator.next();
TableInfo tableInfo = pair.getKey();
byte[] htableName = tableInfo.getHTableName().getBytes();
List<Mutation> mutationList = pair.getValue();
//create a span per target table
//TODO maybe we can be smarter about the table name to string here?
Span child = Tracing.child(span,"Writing mutation batch for table: "+Bytes.toString(htableName));
int retryCount = 0;
boolean shouldRetry = false;
long numMutations = 0;
long mutationSizeBytes = 0;
long mutationCommitTime = 0;
long numFailedMutations = 0;;
long startTime = 0;
do {
TableRef origTableRef = tableInfo.getOrigTableRef();
PTable table = origTableRef.getTable();
table.getIndexMaintainers(indexMetaDataPtr, connection);
final ServerCache cache = tableInfo.isDataTable() ? setMetaDataOnMutations(origTableRef, mutationList, indexMetaDataPtr) : null;
// If we haven't retried yet, retry for this case only, as it's possible that
// a split will occur after we send the index metadata cache to all known
// region servers.
shouldRetry = cache!=null;
SQLException sqlE = null;
HTableInterface hTable = connection.getQueryServices().getTable(htableName);
try {
if (table.isTransactional()) {
// Track tables to which we've sent uncommitted data
uncommittedPhysicalNames.add(table.getPhysicalName().getString());
// If we have indexes, wrap the HTable in a delegate HTable that
// will attach the necessary index meta data in the event of a
// rollback
if (!table.getIndexes().isEmpty()) {
hTable = new MetaDataAwareHTable(hTable, origTableRef);
}
hTable = TransactionUtil.getPhoenixTransactionTable(phoenixTransactionContext, hTable, table);
}
numMutations = mutationList.size();
GLOBAL_MUTATION_BATCH_SIZE.update(numMutations);
mutationSizeBytes = calculateMutationSize(mutationList);
startTime = System.currentTimeMillis();
child.addTimelineAnnotation("Attempt " + retryCount);
List<List<Mutation>> mutationBatchList = getMutationBatchList(batchSize, batchSizeBytes, mutationList);
for (List<Mutation> mutationBatch : mutationBatchList) {
hTable.batch(mutationBatch);
batchCount++;
}
if (logger.isDebugEnabled()) logger.debug("Sent batch of " + numMutations + " for " + Bytes.toString(htableName));
child.stop();
child.stop();
shouldRetry = false;
mutationCommitTime = System.currentTimeMillis() - startTime;
GLOBAL_MUTATION_COMMIT_TIME.update(mutationCommitTime);
numFailedMutations = 0;
if (tableInfo.isDataTable()) {
numRows -= numMutations;
}
// Remove batches as we process them
mutations.remove(origTableRef);
} catch (Exception e) {
mutationCommitTime = System.currentTimeMillis() - startTime;
serverTimestamp = ServerUtil.parseServerTimestamp(e);
SQLException inferredE = ServerUtil.parseServerExceptionOrNull(e);
if (inferredE != null) {
if (shouldRetry && retryCount == 0 && inferredE.getErrorCode() == SQLExceptionCode.INDEX_METADATA_NOT_FOUND.getErrorCode()) {
// Swallow this exception once, as it's possible that we split after sending the index metadata
// and one of the region servers doesn't have it. This will cause it to have it the next go around.
// If it fails again, we don't retry.
String msg = "Swallowing exception and retrying after clearing meta cache on connection. " + inferredE;
logger.warn(LogUtil.addCustomAnnotations(msg, connection));
connection.getQueryServices().clearTableRegionCache(htableName);
// add a new child span as this one failed
child.addTimelineAnnotation(msg);
child.stop();
child = Tracing.child(span,"Failed batch, attempting retry");
continue;
}
e = inferredE;
}
// Throw to client an exception that indicates the statements that
// were not committed successfully.
int[] uncommittedStatementIndexes = getUncommittedStatementIndexes();
sqlE = new CommitException(e, uncommittedStatementIndexes, serverTimestamp);
numFailedMutations = uncommittedStatementIndexes.length;
GLOBAL_MUTATION_BATCH_FAILED_COUNT.update(numFailedMutations);
} finally {
MutationMetric mutationsMetric = new MutationMetric(numMutations, mutationSizeBytes, mutationCommitTime, numFailedMutations);
mutationMetricQueue.addMetricsForTable(Bytes.toString(htableName), mutationsMetric);
try {
if (cache!=null)
cache.close();
} finally {
try {
hTable.close();
}
catch (IOException e) {
if (sqlE != null) {
sqlE.setNextException(ServerUtil.parseServerException(e));
} else {
sqlE = ServerUtil.parseServerException(e);
}
}
if (sqlE != null) {
throw sqlE;
}
}
}
} while (shouldRetry && retryCount++ < 1);
}
}
} | @SuppressWarnings("deprecation")
private void send(Iterator<TableRef> tableRefIterator) throws SQLException {
int i = 0;
long[] serverTimeStamps = null;
boolean sendAll = false;
if (tableRefIterator == null) {
serverTimeStamps = validateAll();
tableRefIterator = mutations.keySet().iterator();
sendAll = true;
}
Map<ImmutableBytesPtr, RowMutationState> valuesMap;
Map<TableInfo,List<Mutation>> physicalTableMutationMap = Maps.newLinkedHashMap();
try (TraceScope trace = Tracing.startNewSpan(connection, "Committing mutations to tables")) {
Span span = trace.getSpan();
ImmutableBytesWritable indexMetaDataPtr = new ImmutableBytesWritable();
while (tableRefIterator.hasNext()) {
final TableRef tableRef = tableRefIterator.next();
valuesMap = mutations.get(tableRef);
if (valuesMap == null || valuesMap.isEmpty()) {
continue;
}
long serverTimestamp = serverTimeStamps == null ? validateAndGetServerTimestamp(tableRef, valuesMap) : serverTimeStamps[i++];
Long scn = connection.getSCN();
long mutationTimestamp = scn == null ? HConstants.LATEST_TIMESTAMP : scn;
final PTable table = tableRef.getTable();
Iterator<Pair<PName,List<Mutation>>> mutationsIterator = addRowMutations(tableRef, valuesMap, mutationTimestamp, serverTimestamp, false, sendAll);
boolean isDataTable = true;
while (mutationsIterator.hasNext()) {
Pair<PName,List<Mutation>> pair = mutationsIterator.next();
PName hTableName = pair.getFirst();
List<Mutation> mutationList = pair.getSecond();
TableInfo tableInfo = new TableInfo(isDataTable, hTableName, tableRef);
List<Mutation> oldMutationList = physicalTableMutationMap.put(tableInfo, mutationList);
if (oldMutationList!=null)
mutationList.addAll(0, oldMutationList);
isDataTable = false;
}
if (table.isTransactional()) {
addUncommittedStatementIndexes(valuesMap.values());
if (txMutations.isEmpty()) {
txMutations = Maps.newHashMapWithExpectedSize(mutations.size());
}
joinMutationState(new TableRef(tableRef), valuesMap, txMutations);
}
}
long serverTimestamp = HConstants.LATEST_TIMESTAMP;
Iterator<Entry<TableInfo, List<Mutation>>> mutationsIterator = physicalTableMutationMap.entrySet().iterator();
while (mutationsIterator.hasNext()) {
Entry<TableInfo, List<Mutation>> pair = mutationsIterator.next();
TableInfo tableInfo = pair.getKey();
byte[] htableName = tableInfo.getHTableName().getBytes();
List<Mutation> mutationList = pair.getValue();
Span child = Tracing.child(span,"Writing mutation batch for table: "+Bytes.toString(htableName));
int retryCount = 0;
boolean shouldRetry = false;
long numMutations = 0;
long mutationSizeBytes = 0;
long mutationCommitTime = 0;
long numFailedMutations = 0;;
long startTime = 0;
do {
TableRef origTableRef = tableInfo.getOrigTableRef();
PTable table = origTableRef.getTable();
table.getIndexMaintainers(indexMetaDataPtr, connection);
final ServerCache cache = tableInfo.isDataTable() ? setMetaDataOnMutations(origTableRef, mutationList, indexMetaDataPtr) : null;
shouldRetry = cache!=null;
SQLException sqlE = null;
HTableInterface hTable = connection.getQueryServices().getTable(htableName);
try {
if (table.isTransactional()) {
uncommittedPhysicalNames.add(table.getPhysicalName().getString());
if (!table.getIndexes().isEmpty()) {
hTable = new MetaDataAwareHTable(hTable, origTableRef);
}
hTable = TransactionUtil.getPhoenixTransactionTable(phoenixTransactionContext, hTable, table);
}
numMutations = mutationList.size();
GLOBAL_MUTATION_BATCH_SIZE.update(numMutations);
mutationSizeBytes = calculateMutationSize(mutationList);
startTime = System.currentTimeMillis();
child.addTimelineAnnotation("Attempt " + retryCount);
List<List<Mutation>> mutationBatchList = getMutationBatchList(batchSize, batchSizeBytes, mutationList);
for (List<Mutation> mutationBatch : mutationBatchList) {
hTable.batch(mutationBatch);
batchCount++;
}
if (logger.isDebugEnabled()) logger.debug("Sent batch of " + numMutations + " for " + Bytes.toString(htableName));
child.stop();
child.stop();
shouldRetry = false;
mutationCommitTime = System.currentTimeMillis() - startTime;
GLOBAL_MUTATION_COMMIT_TIME.update(mutationCommitTime);
numFailedMutations = 0;
if (tableInfo.isDataTable()) {
numRows -= numMutations;
}
mutations.remove(origTableRef);
} catch (Exception e) {
mutationCommitTime = System.currentTimeMillis() - startTime;
serverTimestamp = ServerUtil.parseServerTimestamp(e);
SQLException inferredE = ServerUtil.parseServerExceptionOrNull(e);
if (inferredE != null) {
if (shouldRetry && retryCount == 0 && inferredE.getErrorCode() == SQLExceptionCode.INDEX_METADATA_NOT_FOUND.getErrorCode()) {
String msg = "Swallowing exception and retrying after clearing meta cache on connection. " + inferredE;
logger.warn(LogUtil.addCustomAnnotations(msg, connection));
connection.getQueryServices().clearTableRegionCache(htableName);
child.addTimelineAnnotation(msg);
child.stop();
child = Tracing.child(span,"Failed batch, attempting retry");
continue;
}
e = inferredE;
}
int[] uncommittedStatementIndexes = getUncommittedStatementIndexes();
sqlE = new CommitException(e, uncommittedStatementIndexes, serverTimestamp);
numFailedMutations = uncommittedStatementIndexes.length;
GLOBAL_MUTATION_BATCH_FAILED_COUNT.update(numFailedMutations);
} finally {
MutationMetric mutationsMetric = new MutationMetric(numMutations, mutationSizeBytes, mutationCommitTime, numFailedMutations);
mutationMetricQueue.addMetricsForTable(Bytes.toString(htableName), mutationsMetric);
try {
if (cache!=null)
cache.close();
} finally {
try {
hTable.close();
}
catch (IOException e) {
if (sqlE != null) {
sqlE.setNextException(ServerUtil.parseServerException(e));
} else {
sqlE = ServerUtil.parseServerException(e);
}
}
if (sqlE != null) {
throw sqlE;
}
}
}
} while (shouldRetry && retryCount++ < 1);
}
}
} | @suppresswarnings("deprecation") private void send(iterator<tableref> tablerefiterator) throws sqlexception { int i = 0; long[] servertimestamps = null; boolean sendall = false; if (tablerefiterator == null) { servertimestamps = validateall(); tablerefiterator = mutations.keyset().iterator(); sendall = true; } map<immutablebytesptr, rowmutationstate> valuesmap; map<tableinfo,list<mutation>> physicaltablemutationmap = maps.newlinkedhashmap(); try (tracescope trace = tracing.startnewspan(connection, "committing mutations to tables")) { span span = trace.getspan(); immutablebyteswritable indexmetadataptr = new immutablebyteswritable(); while (tablerefiterator.hasnext()) { final tableref tableref = tablerefiterator.next(); valuesmap = mutations.get(tableref); if (valuesmap == null || valuesmap.isempty()) { continue; } long servertimestamp = servertimestamps == null ? validateandgetservertimestamp(tableref, valuesmap) : servertimestamps[i++]; long scn = connection.getscn(); long mutationtimestamp = scn == null ? hconstants.latest_timestamp : scn; final ptable table = tableref.gettable(); iterator<pair<pname,list<mutation>>> mutationsiterator = addrowmutations(tableref, valuesmap, mutationtimestamp, servertimestamp, false, sendall); boolean isdatatable = true; while (mutationsiterator.hasnext()) { pair<pname,list<mutation>> pair = mutationsiterator.next(); pname htablename = pair.getfirst(); list<mutation> mutationlist = pair.getsecond(); tableinfo tableinfo = new tableinfo(isdatatable, htablename, tableref); list<mutation> oldmutationlist = physicaltablemutationmap.put(tableinfo, mutationlist); if (oldmutationlist!=null) mutationlist.addall(0, oldmutationlist); isdatatable = false; } if (table.istransactional()) { adduncommittedstatementindexes(valuesmap.values()); if (txmutations.isempty()) { txmutations = maps.newhashmapwithexpectedsize(mutations.size()); } joinmutationstate(new tableref(tableref), valuesmap, txmutations); } } long servertimestamp = hconstants.latest_timestamp; iterator<entry<tableinfo, list<mutation>>> mutationsiterator = physicaltablemutationmap.entryset().iterator(); while (mutationsiterator.hasnext()) { entry<tableinfo, list<mutation>> pair = mutationsiterator.next(); tableinfo tableinfo = pair.getkey(); byte[] htablename = tableinfo.gethtablename().getbytes(); list<mutation> mutationlist = pair.getvalue(); span child = tracing.child(span,"writing mutation batch for table: "+bytes.tostring(htablename)); int retrycount = 0; boolean shouldretry = false; long nummutations = 0; long mutationsizebytes = 0; long mutationcommittime = 0; long numfailedmutations = 0;; long starttime = 0; do { tableref origtableref = tableinfo.getorigtableref(); ptable table = origtableref.gettable(); table.getindexmaintainers(indexmetadataptr, connection); final servercache cache = tableinfo.isdatatable() ? setmetadataonmutations(origtableref, mutationlist, indexmetadataptr) : null; shouldretry = cache!=null; sqlexception sqle = null; htableinterface htable = connection.getqueryservices().gettable(htablename); try { if (table.istransactional()) { uncommittedphysicalnames.add(table.getphysicalname().getstring()); if (!table.getindexes().isempty()) { htable = new metadataawarehtable(htable, origtableref); } htable = transactionutil.getphoenixtransactiontable(phoenixtransactioncontext, htable, table); } nummutations = mutationlist.size(); global_mutation_batch_size.update(nummutations); mutationsizebytes = calculatemutationsize(mutationlist); starttime = system.currenttimemillis(); child.addtimelineannotation("attempt " + retrycount); list<list<mutation>> mutationbatchlist = getmutationbatchlist(batchsize, batchsizebytes, mutationlist); for (list<mutation> mutationbatch : mutationbatchlist) { htable.batch(mutationbatch); batchcount++; } if (logger.isdebugenabled()) logger.debug("sent batch of " + nummutations + " for " + bytes.tostring(htablename)); child.stop(); child.stop(); shouldretry = false; mutationcommittime = system.currenttimemillis() - starttime; global_mutation_commit_time.update(mutationcommittime); numfailedmutations = 0; if (tableinfo.isdatatable()) { numrows -= nummutations; } mutations.remove(origtableref); } catch (exception e) { mutationcommittime = system.currenttimemillis() - starttime; servertimestamp = serverutil.parseservertimestamp(e); sqlexception inferrede = serverutil.parseserverexceptionornull(e); if (inferrede != null) { if (shouldretry && retrycount == 0 && inferrede.geterrorcode() == sqlexceptioncode.index_metadata_not_found.geterrorcode()) { string msg = "swallowing exception and retrying after clearing meta cache on connection. " + inferrede; logger.warn(logutil.addcustomannotations(msg, connection)); connection.getqueryservices().cleartableregioncache(htablename); child.addtimelineannotation(msg); child.stop(); child = tracing.child(span,"failed batch, attempting retry"); continue; } e = inferrede; } int[] uncommittedstatementindexes = getuncommittedstatementindexes(); sqle = new commitexception(e, uncommittedstatementindexes, servertimestamp); numfailedmutations = uncommittedstatementindexes.length; global_mutation_batch_failed_count.update(numfailedmutations); } finally { mutationmetric mutationsmetric = new mutationmetric(nummutations, mutationsizebytes, mutationcommittime, numfailedmutations); mutationmetricqueue.addmetricsfortable(bytes.tostring(htablename), mutationsmetric); try { if (cache!=null) cache.close(); } finally { try { htable.close(); } catch (ioexception e) { if (sqle != null) { sqle.setnextexception(serverutil.parseserverexception(e)); } else { sqle = serverutil.parseserverexception(e); } } if (sqle != null) { throw sqle; } } } } while (shouldretry && retrycount++ < 1); } } } | cruisehz/phoenix | [
1,
0,
0,
0
] |
1,597 | @Transactional()
@Override
public EmailResponse resendConfirmationthroughEmail(
String applicationId, String securityToken, String emailId, String appName) {
logger.info("UserManagementProfileServiceImpl - resendConfirmationthroughEmail() - Starts");
AppEntity appPropertiesDetails = null;
String content = "";
String subject = "";
AppOrgInfoBean appOrgInfoBean = null;
appOrgInfoBean = commonDao.getUserAppDetailsByAllApi("", applicationId);
appPropertiesDetails =
userProfileManagementDao.getAppPropertiesDetailsByAppId(appOrgInfoBean.getAppInfoId());
Map<String, String> templateArgs = new HashMap<>();
if ((appPropertiesDetails == null)
|| (appPropertiesDetails.getRegEmailSub() == null)
|| (appPropertiesDetails.getRegEmailBody() == null)
|| appPropertiesDetails.getRegEmailBody().equalsIgnoreCase("")
|| appPropertiesDetails.getRegEmailSub().equalsIgnoreCase("")) {
subject = appConfig.getConfirmationMailSubject();
content = appConfig.getConfirmationMail();
} else {
content = appPropertiesDetails.getRegEmailBody();
subject = appPropertiesDetails.getRegEmailSub();
}
templateArgs.put("appName", appName);
// TODO(#496): replace with actual study's org name.
templateArgs.put("orgName", appConfig.getOrgName());
templateArgs.put("contactEmail", appConfig.getContactEmail());
templateArgs.put("securitytoken", securityToken);
EmailRequest emailRequest =
new EmailRequest(
appConfig.getFromEmail(),
new String[] {emailId},
null,
null,
subject,
content,
templateArgs);
logger.info("UserManagementProfileServiceImpl - resendConfirmationthroughEmail() - Ends");
return emailService.sendMimeMail(emailRequest);
} | @Transactional()
@Override
public EmailResponse resendConfirmationthroughEmail(
String applicationId, String securityToken, String emailId, String appName) {
logger.info("UserManagementProfileServiceImpl - resendConfirmationthroughEmail() - Starts");
AppEntity appPropertiesDetails = null;
String content = "";
String subject = "";
AppOrgInfoBean appOrgInfoBean = null;
appOrgInfoBean = commonDao.getUserAppDetailsByAllApi("", applicationId);
appPropertiesDetails =
userProfileManagementDao.getAppPropertiesDetailsByAppId(appOrgInfoBean.getAppInfoId());
Map<String, String> templateArgs = new HashMap<>();
if ((appPropertiesDetails == null)
|| (appPropertiesDetails.getRegEmailSub() == null)
|| (appPropertiesDetails.getRegEmailBody() == null)
|| appPropertiesDetails.getRegEmailBody().equalsIgnoreCase("")
|| appPropertiesDetails.getRegEmailSub().equalsIgnoreCase("")) {
subject = appConfig.getConfirmationMailSubject();
content = appConfig.getConfirmationMail();
} else {
content = appPropertiesDetails.getRegEmailBody();
subject = appPropertiesDetails.getRegEmailSub();
}
templateArgs.put("appName", appName);
templateArgs.put("orgName", appConfig.getOrgName());
templateArgs.put("contactEmail", appConfig.getContactEmail());
templateArgs.put("securitytoken", securityToken);
EmailRequest emailRequest =
new EmailRequest(
appConfig.getFromEmail(),
new String[] {emailId},
null,
null,
subject,
content,
templateArgs);
logger.info("UserManagementProfileServiceImpl - resendConfirmationthroughEmail() - Ends");
return emailService.sendMimeMail(emailRequest);
} | @transactional() @override public emailresponse resendconfirmationthroughemail( string applicationid, string securitytoken, string emailid, string appname) { logger.info("usermanagementprofileserviceimpl - resendconfirmationthroughemail() - starts"); appentity apppropertiesdetails = null; string content = ""; string subject = ""; apporginfobean apporginfobean = null; apporginfobean = commondao.getuserappdetailsbyallapi("", applicationid); apppropertiesdetails = userprofilemanagementdao.getapppropertiesdetailsbyappid(apporginfobean.getappinfoid()); map<string, string> templateargs = new hashmap<>(); if ((apppropertiesdetails == null) || (apppropertiesdetails.getregemailsub() == null) || (apppropertiesdetails.getregemailbody() == null) || apppropertiesdetails.getregemailbody().equalsignorecase("") || apppropertiesdetails.getregemailsub().equalsignorecase("")) { subject = appconfig.getconfirmationmailsubject(); content = appconfig.getconfirmationmail(); } else { content = apppropertiesdetails.getregemailbody(); subject = apppropertiesdetails.getregemailsub(); } templateargs.put("appname", appname); templateargs.put("orgname", appconfig.getorgname()); templateargs.put("contactemail", appconfig.getcontactemail()); templateargs.put("securitytoken", securitytoken); emailrequest emailrequest = new emailrequest( appconfig.getfromemail(), new string[] {emailid}, null, null, subject, content, templateargs); logger.info("usermanagementprofileserviceimpl - resendconfirmationthroughemail() - ends"); return emailservice.sendmimemail(emailrequest); } | deepsinghchouhan/fdamystudies | [
1,
0,
0,
0
] |
18,031 | private String replaceParam(String message, Object... parameters) {
int startSize = 0;
int parametersIndex = 0;
int index;
String tmpMessage = message;
while ((index = message.indexOf("{}", startSize)) != -1) {
if (parametersIndex >= parameters.length) {
break;
}
/**
* @Fix the Illegal group reference issue
*/
tmpMessage = tmpMessage.replaceFirst("\\{\\}", Matcher.quoteReplacement(String.valueOf(parameters[parametersIndex++])));
startSize = index + 2;
}
return tmpMessage;
} | private String replaceParam(String message, Object... parameters) {
int startSize = 0;
int parametersIndex = 0;
int index;
String tmpMessage = message;
while ((index = message.indexOf("{}", startSize)) != -1) {
if (parametersIndex >= parameters.length) {
break;
}
tmpMessage = tmpMessage.replaceFirst("\\{\\}", Matcher.quoteReplacement(String.valueOf(parameters[parametersIndex++])));
startSize = index + 2;
}
return tmpMessage;
} | private string replaceparam(string message, object... parameters) { int startsize = 0; int parametersindex = 0; int index; string tmpmessage = message; while ((index = message.indexof("{}", startsize)) != -1) { if (parametersindex >= parameters.length) { break; } tmpmessage = tmpmessage.replacefirst("\\{\\}", matcher.quotereplacement(string.valueof(parameters[parametersindex++]))); startsize = index + 2; } return tmpmessage; } | erda-project/erda-java-extensions | [
0,
0,
1,
0
] |
26,234 | @GET
@PermitAll
@Path("/server/info")
@Produces(MediaType.APPLICATION_JSON)
public Response getServerInformation() throws ApiException {
Map<String, Object> returnMap = new HashMap<String, Object>();
List<Object> configurations = new ArrayList<Object>();
AppConstants appConstants = AppConstants.getInstance();
for (Configuration configuration : getIbisManager().getConfigurations()) {
Map<String, Object> cfg = new HashMap<String, Object>();
cfg.put("name", configuration.getName());
cfg.put("version", configuration.getVersion());
cfg.put("stubbed", configuration.isStubbed());
cfg.put("type", configuration.getClassLoaderType());
if(configuration.getConfigurationException() != null) {
cfg.put("exception", configuration.getConfigurationException().getMessage());
}
ClassLoader classLoader = configuration.getClassLoader();
if(classLoader instanceof DatabaseClassLoader) {
cfg.put("filename", ((DatabaseClassLoader) classLoader).getFileName());
cfg.put("created", ((DatabaseClassLoader) classLoader).getCreationDate());
cfg.put("user", ((DatabaseClassLoader) classLoader).getUser());
}
String parentConfig = AppConstants.getInstance().getString("configurations." + configuration.getName() + ".parentConfig", null);
if(parentConfig != null)
cfg.put("parent", parentConfig);
configurations.add(cfg);
}
//TODO Replace this with java.util.Collections!
Collections.sort(configurations, new Comparator<Map<String, String>>() {
@Override
public int compare(Map<String, String> lhs, Map<String, String> rhs) {
String name1 = lhs.get("name");
String name2 = rhs.get("name");
return name1.startsWith("IAF_") ? -1 : name2.startsWith("IAF_") ? 1 : name1.compareTo(name2);
}
});
returnMap.put("configurations", configurations);
Map<String, Object> framework = new HashMap<String, Object>(2);
framework.put("name", "FF!");
framework.put("version", appConstants.getProperty("application.version"));
returnMap.put("framework", framework);
Map<String, Object> instance = new HashMap<String, Object>(2);
instance.put("version", appConstants.getProperty("instance.version"));
instance.put("name", getIbisContext().getApplicationName());
returnMap.put("instance", instance);
String dtapStage = appConstants.getProperty("dtap.stage");
returnMap.put("dtap.stage", dtapStage);
String dtapSide = appConstants.getProperty("dtap.side");
returnMap.put("dtap.side", dtapSide);
returnMap.put("applicationServer", servletConfig.getServletContext().getServerInfo());
returnMap.put("javaVersion", System.getProperty("java.runtime.name") + " (" + System.getProperty("java.runtime.version") + ")");
Map<String, Object> fileSystem = new HashMap<String, Object>(2);
fileSystem.put("totalSpace", Misc.getFileSystemTotalSpace());
fileSystem.put("freeSpace", Misc.getFileSystemFreeSpace());
returnMap.put("fileSystem", fileSystem);
returnMap.put("processMetrics", ProcessMetrics.toMap());
Date date = new Date();
returnMap.put("serverTime", date.getTime());
returnMap.put("machineName" , Misc.getHostname());
ApplicationMetrics metrics = getIbisContext().getBean("metrics", ApplicationMetrics.class);
returnMap.put("uptime", (metrics != null) ? metrics.getUptimeDate() : "");
return Response.status(Response.Status.OK).entity(returnMap).build();
} | @GET
@PermitAll
@Path("/server/info")
@Produces(MediaType.APPLICATION_JSON)
public Response getServerInformation() throws ApiException {
Map<String, Object> returnMap = new HashMap<String, Object>();
List<Object> configurations = new ArrayList<Object>();
AppConstants appConstants = AppConstants.getInstance();
for (Configuration configuration : getIbisManager().getConfigurations()) {
Map<String, Object> cfg = new HashMap<String, Object>();
cfg.put("name", configuration.getName());
cfg.put("version", configuration.getVersion());
cfg.put("stubbed", configuration.isStubbed());
cfg.put("type", configuration.getClassLoaderType());
if(configuration.getConfigurationException() != null) {
cfg.put("exception", configuration.getConfigurationException().getMessage());
}
ClassLoader classLoader = configuration.getClassLoader();
if(classLoader instanceof DatabaseClassLoader) {
cfg.put("filename", ((DatabaseClassLoader) classLoader).getFileName());
cfg.put("created", ((DatabaseClassLoader) classLoader).getCreationDate());
cfg.put("user", ((DatabaseClassLoader) classLoader).getUser());
}
String parentConfig = AppConstants.getInstance().getString("configurations." + configuration.getName() + ".parentConfig", null);
if(parentConfig != null)
cfg.put("parent", parentConfig);
configurations.add(cfg);
}
Collections.sort(configurations, new Comparator<Map<String, String>>() {
@Override
public int compare(Map<String, String> lhs, Map<String, String> rhs) {
String name1 = lhs.get("name");
String name2 = rhs.get("name");
return name1.startsWith("IAF_") ? -1 : name2.startsWith("IAF_") ? 1 : name1.compareTo(name2);
}
});
returnMap.put("configurations", configurations);
Map<String, Object> framework = new HashMap<String, Object>(2);
framework.put("name", "FF!");
framework.put("version", appConstants.getProperty("application.version"));
returnMap.put("framework", framework);
Map<String, Object> instance = new HashMap<String, Object>(2);
instance.put("version", appConstants.getProperty("instance.version"));
instance.put("name", getIbisContext().getApplicationName());
returnMap.put("instance", instance);
String dtapStage = appConstants.getProperty("dtap.stage");
returnMap.put("dtap.stage", dtapStage);
String dtapSide = appConstants.getProperty("dtap.side");
returnMap.put("dtap.side", dtapSide);
returnMap.put("applicationServer", servletConfig.getServletContext().getServerInfo());
returnMap.put("javaVersion", System.getProperty("java.runtime.name") + " (" + System.getProperty("java.runtime.version") + ")");
Map<String, Object> fileSystem = new HashMap<String, Object>(2);
fileSystem.put("totalSpace", Misc.getFileSystemTotalSpace());
fileSystem.put("freeSpace", Misc.getFileSystemFreeSpace());
returnMap.put("fileSystem", fileSystem);
returnMap.put("processMetrics", ProcessMetrics.toMap());
Date date = new Date();
returnMap.put("serverTime", date.getTime());
returnMap.put("machineName" , Misc.getHostname());
ApplicationMetrics metrics = getIbisContext().getBean("metrics", ApplicationMetrics.class);
returnMap.put("uptime", (metrics != null) ? metrics.getUptimeDate() : "");
return Response.status(Response.Status.OK).entity(returnMap).build();
} | @get @permitall @path("/server/info") @produces(mediatype.application_json) public response getserverinformation() throws apiexception { map<string, object> returnmap = new hashmap<string, object>(); list<object> configurations = new arraylist<object>(); appconstants appconstants = appconstants.getinstance(); for (configuration configuration : getibismanager().getconfigurations()) { map<string, object> cfg = new hashmap<string, object>(); cfg.put("name", configuration.getname()); cfg.put("version", configuration.getversion()); cfg.put("stubbed", configuration.isstubbed()); cfg.put("type", configuration.getclassloadertype()); if(configuration.getconfigurationexception() != null) { cfg.put("exception", configuration.getconfigurationexception().getmessage()); } classloader classloader = configuration.getclassloader(); if(classloader instanceof databaseclassloader) { cfg.put("filename", ((databaseclassloader) classloader).getfilename()); cfg.put("created", ((databaseclassloader) classloader).getcreationdate()); cfg.put("user", ((databaseclassloader) classloader).getuser()); } string parentconfig = appconstants.getinstance().getstring("configurations." + configuration.getname() + ".parentconfig", null); if(parentconfig != null) cfg.put("parent", parentconfig); configurations.add(cfg); } collections.sort(configurations, new comparator<map<string, string>>() { @override public int compare(map<string, string> lhs, map<string, string> rhs) { string name1 = lhs.get("name"); string name2 = rhs.get("name"); return name1.startswith("iaf_") ? -1 : name2.startswith("iaf_") ? 1 : name1.compareto(name2); } }); returnmap.put("configurations", configurations); map<string, object> framework = new hashmap<string, object>(2); framework.put("name", "ff!"); framework.put("version", appconstants.getproperty("application.version")); returnmap.put("framework", framework); map<string, object> instance = new hashmap<string, object>(2); instance.put("version", appconstants.getproperty("instance.version")); instance.put("name", getibiscontext().getapplicationname()); returnmap.put("instance", instance); string dtapstage = appconstants.getproperty("dtap.stage"); returnmap.put("dtap.stage", dtapstage); string dtapside = appconstants.getproperty("dtap.side"); returnmap.put("dtap.side", dtapside); returnmap.put("applicationserver", servletconfig.getservletcontext().getserverinfo()); returnmap.put("javaversion", system.getproperty("java.runtime.name") + " (" + system.getproperty("java.runtime.version") + ")"); map<string, object> filesystem = new hashmap<string, object>(2); filesystem.put("totalspace", misc.getfilesystemtotalspace()); filesystem.put("freespace", misc.getfilesystemfreespace()); returnmap.put("filesystem", filesystem); returnmap.put("processmetrics", processmetrics.tomap()); date date = new date(); returnmap.put("servertime", date.gettime()); returnmap.put("machinename" , misc.gethostname()); applicationmetrics metrics = getibiscontext().getbean("metrics", applicationmetrics.class); returnmap.put("uptime", (metrics != null) ? metrics.getuptimedate() : ""); return response.status(response.status.ok).entity(returnmap).build(); } | francisgw/iaf | [
1,
0,
0,
0
] |
18,158 | public static int getSqlStatementType(String sql) {
sql = sql.trim();
if (sql.length() < 3) {
return STATEMENT_OTHER;
}
String prefixSql = sql.substring(0, 3).toUpperCase(Locale.ROOT);
if (prefixSql.equals("SEL")) {
return STATEMENT_SELECT;
} else if (prefixSql.equals("INS") ||
prefixSql.equals("UPD") ||
prefixSql.equals("REP") ||
prefixSql.equals("DEL")) {
return STATEMENT_UPDATE;
} else if (prefixSql.equals("ATT")) {
return STATEMENT_ATTACH;
} else if (prefixSql.equals("COM")) {
return STATEMENT_COMMIT;
} else if (prefixSql.equals("END")) {
return STATEMENT_COMMIT;
} else if (prefixSql.equals("ROL")) {
return STATEMENT_ABORT;
} else if (prefixSql.equals("BEG")) {
return STATEMENT_BEGIN;
} else if (prefixSql.equals("PRA")) {
return STATEMENT_PRAGMA;
} else if (prefixSql.equals("CRE") || prefixSql.equals("DRO") ||
prefixSql.equals("ALT")) {
return STATEMENT_DDL;
} else if (prefixSql.equals("ANA") || prefixSql.equals("DET")) {
return STATEMENT_UNPREPARED;
}
return STATEMENT_OTHER;
} | public static int getSqlStatementType(String sql) {
sql = sql.trim();
if (sql.length() < 3) {
return STATEMENT_OTHER;
}
String prefixSql = sql.substring(0, 3).toUpperCase(Locale.ROOT);
if (prefixSql.equals("SEL")) {
return STATEMENT_SELECT;
} else if (prefixSql.equals("INS") ||
prefixSql.equals("UPD") ||
prefixSql.equals("REP") ||
prefixSql.equals("DEL")) {
return STATEMENT_UPDATE;
} else if (prefixSql.equals("ATT")) {
return STATEMENT_ATTACH;
} else if (prefixSql.equals("COM")) {
return STATEMENT_COMMIT;
} else if (prefixSql.equals("END")) {
return STATEMENT_COMMIT;
} else if (prefixSql.equals("ROL")) {
return STATEMENT_ABORT;
} else if (prefixSql.equals("BEG")) {
return STATEMENT_BEGIN;
} else if (prefixSql.equals("PRA")) {
return STATEMENT_PRAGMA;
} else if (prefixSql.equals("CRE") || prefixSql.equals("DRO") ||
prefixSql.equals("ALT")) {
return STATEMENT_DDL;
} else if (prefixSql.equals("ANA") || prefixSql.equals("DET")) {
return STATEMENT_UNPREPARED;
}
return STATEMENT_OTHER;
} | public static int getsqlstatementtype(string sql) { sql = sql.trim(); if (sql.length() < 3) { return statement_other; } string prefixsql = sql.substring(0, 3).touppercase(locale.root); if (prefixsql.equals("sel")) { return statement_select; } else if (prefixsql.equals("ins") || prefixsql.equals("upd") || prefixsql.equals("rep") || prefixsql.equals("del")) { return statement_update; } else if (prefixsql.equals("att")) { return statement_attach; } else if (prefixsql.equals("com")) { return statement_commit; } else if (prefixsql.equals("end")) { return statement_commit; } else if (prefixsql.equals("rol")) { return statement_abort; } else if (prefixsql.equals("beg")) { return statement_begin; } else if (prefixsql.equals("pra")) { return statement_pragma; } else if (prefixsql.equals("cre") || prefixsql.equals("dro") || prefixsql.equals("alt")) { return statement_ddl; } else if (prefixsql.equals("ana") || prefixsql.equals("det")) { return statement_unprepared; } return statement_other; } | finki001/couchbase-lite-java-core | [
0,
0,
0,
0
] |
34,557 | @Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ComplexBean that = (ComplexBean) o;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
if (!Arrays.equals(strs, that.strs))
return false;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
if (!Arrays.equals(jobs, that.jobs))
return false;
if (list != null ? !list.equals(that.list) : that.list != null)
return false;
if (map != null ? !map.equals(that.map) : that.map != null)
return false;
return clazz != null ? clazz.equals(that.clazz) : that.clazz == null;
} | @Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ComplexBean that = (ComplexBean) o;
if (!Arrays.equals(strs, that.strs))
return false;
if (!Arrays.equals(jobs, that.jobs))
return false;
if (list != null ? !list.equals(that.list) : that.list != null)
return false;
if (map != null ? !map.equals(that.map) : that.map != null)
return false;
return clazz != null ? clazz.equals(that.clazz) : that.clazz == null;
} | @override public boolean equals(object o) { if (this == o) return true; if (o == null || getclass() != o.getclass()) return false; complexbean that = (complexbean) o; if (!arrays.equals(strs, that.strs)) return false; if (!arrays.equals(jobs, that.jobs)) return false; if (list != null ? !list.equals(that.list) : that.list != null) return false; if (map != null ? !map.equals(that.map) : that.map != null) return false; return clazz != null ? clazz.equals(that.clazz) : that.clazz == null; } | dbl-x/sofa-rpc | [
0,
0,
1,
0
] |
10,052 | @Override
public void selectionDone(SelectionEvent evt) {
if (!useUnixTextSelection)
return;
Object o = evt.getSelection();
if (!(o instanceof CharacterIterator))
return;
CharacterIterator iter = (CharacterIterator) o;
// first see if we can access the clipboard
if (!PermissionChecker.getInstance().checkPermission(new AWTPermission("accessClipboard"))) {
// Can't access clipboard.
return;
}
int sz = iter.getEndIndex() - iter.getBeginIndex();
if (sz == 0)
return;
char[] cbuff = new char[sz];
cbuff[0] = iter.first();
for (int i = 1; i < cbuff.length; ++i) {
cbuff[i] = iter.next();
}
final String strSel = new String(cbuff);
// HACK: getSystemClipboard sometimes deadlocks on
// linux when called from the AWT Thread. The Thread
// creation prevents that.
new Thread() {
@Override
public void run() {
Clipboard cb;
cb = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection sel;
sel = new StringSelection(strSel);
cb.setContents(sel, sel);
}
}.start();
} | @Override
public void selectionDone(SelectionEvent evt) {
if (!useUnixTextSelection)
return;
Object o = evt.getSelection();
if (!(o instanceof CharacterIterator))
return;
CharacterIterator iter = (CharacterIterator) o;
if (!PermissionChecker.getInstance().checkPermission(new AWTPermission("accessClipboard"))) {
return;
}
int sz = iter.getEndIndex() - iter.getBeginIndex();
if (sz == 0)
return;
char[] cbuff = new char[sz];
cbuff[0] = iter.first();
for (int i = 1; i < cbuff.length; ++i) {
cbuff[i] = iter.next();
}
final String strSel = new String(cbuff);
new Thread() {
@Override
public void run() {
Clipboard cb;
cb = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection sel;
sel = new StringSelection(strSel);
cb.setContents(sel, sel);
}
}.start();
} | @override public void selectiondone(selectionevent evt) { if (!useunixtextselection) return; object o = evt.getselection(); if (!(o instanceof characteriterator)) return; characteriterator iter = (characteriterator) o; if (!permissionchecker.getinstance().checkpermission(new awtpermission("accessclipboard"))) { return; } int sz = iter.getendindex() - iter.getbeginindex(); if (sz == 0) return; char[] cbuff = new char[sz]; cbuff[0] = iter.first(); for (int i = 1; i < cbuff.length; ++i) { cbuff[i] = iter.next(); } final string strsel = new string(cbuff); new thread() { @override public void run() { clipboard cb; cb = toolkit.getdefaulttoolkit().getsystemclipboard(); stringselection sel; sel = new stringselection(strsel); cb.setcontents(sel, sel); } }.start(); } | css4j/echosvg | [
1,
0,
0,
0
] |
10,102 | protected boolean dispatchLocal(HttpServletRequest httpRequest,
HttpServletResponse httpResponse) throws ServletException,
IOException {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Local dispatch /" + translateRequestPath(httpRequest));
}
if (!serveStatic) {
return false;
}
// String contextRelativePath = httpRequest.getServletPath();
String translatedNoQuery = "/" + translateRequestPath(httpRequest);
// String absPath = getServletContext().getRealPath(contextRelativePath);
String absPath = getServletContext().getRealPath(translatedNoQuery);
if (this.isEnableMemento()) {
MementoUtils.addDoNotNegotiateHeader(httpResponse);
}
//IK: added null check for absPath, it may be null (ex. on jetty)
if (absPath != null) {
File test = new File(absPath);
if((test != null) && !test.exists()) {
return false;
}
}
String translatedQ = "/" + translateRequestPathQuery(httpRequest);
WaybackRequest wbRequest = new WaybackRequest();
// wbRequest.setContextPrefix(getUrlRoot());
wbRequest.setAccessPoint(this);
wbRequest.extractHttpRequestInfo(httpRequest);
UIResults uiResults = new UIResults(wbRequest,uriConverter);
try {
uiResults.forward(httpRequest, httpResponse, translatedQ);
return true;
} catch(IOException e) {
// TODO: figure out if we got IO because of a missing dispatcher
}
return false;
} | protected boolean dispatchLocal(HttpServletRequest httpRequest,
HttpServletResponse httpResponse) throws ServletException,
IOException {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Local dispatch /" + translateRequestPath(httpRequest));
}
if (!serveStatic) {
return false;
}
String translatedNoQuery = "/" + translateRequestPath(httpRequest);
String absPath = getServletContext().getRealPath(translatedNoQuery);
if (this.isEnableMemento()) {
MementoUtils.addDoNotNegotiateHeader(httpResponse);
}
if (absPath != null) {
File test = new File(absPath);
if((test != null) && !test.exists()) {
return false;
}
}
String translatedQ = "/" + translateRequestPathQuery(httpRequest);
WaybackRequest wbRequest = new WaybackRequest();
wbRequest.setAccessPoint(this);
wbRequest.extractHttpRequestInfo(httpRequest);
UIResults uiResults = new UIResults(wbRequest,uriConverter);
try {
uiResults.forward(httpRequest, httpResponse, translatedQ);
return true;
} catch(IOException e) {
}
return false;
} | protected boolean dispatchlocal(httpservletrequest httprequest, httpservletresponse httpresponse) throws servletexception, ioexception { if (logger.isloggable(level.fine)) { logger.fine("local dispatch /" + translaterequestpath(httprequest)); } if (!servestatic) { return false; } string translatednoquery = "/" + translaterequestpath(httprequest); string abspath = getservletcontext().getrealpath(translatednoquery); if (this.isenablememento()) { mementoutils.adddonotnegotiateheader(httpresponse); } if (abspath != null) { file test = new file(abspath); if((test != null) && !test.exists()) { return false; } } string translatedq = "/" + translaterequestpathquery(httprequest); waybackrequest wbrequest = new waybackrequest(); wbrequest.setaccesspoint(this); wbrequest.extracthttprequestinfo(httprequest); uiresults uiresults = new uiresults(wbrequest,uriconverter); try { uiresults.forward(httprequest, httpresponse, translatedq); return true; } catch(ioexception e) { } return false; } | csrster/openwayback-csrdev | [
1,
0,
0,
0
] |
10,103 | public boolean handleRequest(HttpServletRequest httpRequest,
HttpServletResponse httpResponse) throws ServletException,
IOException {
WaybackRequest wbRequest = null;
boolean handled = false;
try {
PerfStats.clearAll();
if (this.isEnablePerfStatsHeader() && (perfStatsHeader != null)) {
PerfStats.timeStart(PerfStat.Total);
httpResponse = new PerfWritingHttpServletResponse(httpRequest,
httpResponse, PerfStat.Total, perfStatsHeader,
perfStatsHeaderFormat);
}
String inputPath = translateRequestPathQuery(httpRequest);
Thread.currentThread().setName("Thread " +
Thread.currentThread().getId() + " " + getBeanName() +
" handling: " + inputPath);
LOGGER.fine("Handling translated: " + inputPath);
wbRequest = getParser().parse(httpRequest, this);
if (wbRequest != null) {
handled = true;
// TODO: refactor this code into RequestParser implementations
wbRequest.setAccessPoint(this);
// wbRequest.setContextPrefix(getAbsoluteLocalPrefix(httpRequest));
// wbRequest.setContextPrefix(getUrlRoot());
wbRequest.extractHttpRequestInfo(httpRequest);
// end of refactor
if (getAuthentication() != null) {
if (!getAuthentication().isTrue(wbRequest)) {
throw new AuthenticationControlException(
"Unauthorized", isRequestAuth());
}
}
// set exclusionFilter on wbRequest only if not set externally
if (wbRequest.getExclusionFilter() == null) {
wbRequest.setExclusionFilter(createExclusionFilter());
}
// TODO: refactor this into RequestParser implementations, so a
// user could alter requests to change the behavior within a
// single AccessPoint. For now, this is a simple way to expose
// the feature to configuration.g
wbRequest.setExactScheme(isExactSchemeMatch());
if (wbRequest.isReplayRequest()) {
if (bounceToReplayPrefix) {
// we don't accept replay requests on this AccessPoint
// bounce the user to the right place:
String suffix = translateRequestPathQuery(httpRequest);
String replayUrl = replayPrefix + suffix;
httpResponse.sendRedirect(replayUrl);
return true;
}
handleReplay(wbRequest, httpRequest, httpResponse);
} else {
if (bounceToQueryPrefix) {
// we don't accept replay requests on this AccessPoint
// bounce the user to the right place:
String suffix = translateRequestPathQuery(httpRequest);
String replayUrl = queryPrefix + suffix;
httpResponse.sendRedirect(replayUrl);
return true;
}
wbRequest.setExactHost(isExactHostMatch());
handleQuery(wbRequest, httpRequest, httpResponse);
}
} else {
handled = dispatchLocal(httpRequest, httpResponse);
}
} catch (BetterRequestException e) {
e.generateResponse(httpResponse, wbRequest);
httpResponse.getWriter(); // cause perf headers to be committed
handled = true;
} catch (WaybackException e) {
if (httpResponse.isCommitted()) {
return true;
}
if (wbRequest == null) {
wbRequest = new WaybackRequest();
wbRequest.setAccessPoint(this);
}
logError(httpResponse, errorMsgHeader, e, wbRequest);
LiveWebState liveWebState = LiveWebState.NOT_FOUND;
if ((getLiveWebRedirector() != null) &&
!wbRequest.hasMementoAcceptDatetime() && !wbRequest.isMementoTimemapRequest()) {
liveWebState = getLiveWebRedirector().handleRedirect(e, wbRequest, httpRequest, httpResponse);
}
// If not liveweb redirected, then render current exception
if (liveWebState != LiveWebState.REDIRECTED) {
e.setLiveWebAvailable(liveWebState == LiveWebState.FOUND);
getException().renderException(httpRequest, httpResponse, wbRequest, e, getUriConverter());
}
handled = true;
} catch (Exception other) {
logError(httpResponse, errorMsgHeader, other, wbRequest);
} finally {
//Slightly hacky, but ensures that all block loaders are closed
ZipNumBlockLoader.closeAllReaders();
}
return handled;
} | public boolean handleRequest(HttpServletRequest httpRequest,
HttpServletResponse httpResponse) throws ServletException,
IOException {
WaybackRequest wbRequest = null;
boolean handled = false;
try {
PerfStats.clearAll();
if (this.isEnablePerfStatsHeader() && (perfStatsHeader != null)) {
PerfStats.timeStart(PerfStat.Total);
httpResponse = new PerfWritingHttpServletResponse(httpRequest,
httpResponse, PerfStat.Total, perfStatsHeader,
perfStatsHeaderFormat);
}
String inputPath = translateRequestPathQuery(httpRequest);
Thread.currentThread().setName("Thread " +
Thread.currentThread().getId() + " " + getBeanName() +
" handling: " + inputPath);
LOGGER.fine("Handling translated: " + inputPath);
wbRequest = getParser().parse(httpRequest, this);
if (wbRequest != null) {
handled = true;
wbRequest.setAccessPoint(this);
wbRequest.extractHttpRequestInfo(httpRequest);
if (getAuthentication() != null) {
if (!getAuthentication().isTrue(wbRequest)) {
throw new AuthenticationControlException(
"Unauthorized", isRequestAuth());
}
}
if (wbRequest.getExclusionFilter() == null) {
wbRequest.setExclusionFilter(createExclusionFilter());
}
wbRequest.setExactScheme(isExactSchemeMatch());
if (wbRequest.isReplayRequest()) {
if (bounceToReplayPrefix) {
String suffix = translateRequestPathQuery(httpRequest);
String replayUrl = replayPrefix + suffix;
httpResponse.sendRedirect(replayUrl);
return true;
}
handleReplay(wbRequest, httpRequest, httpResponse);
} else {
if (bounceToQueryPrefix) {
String suffix = translateRequestPathQuery(httpRequest);
String replayUrl = queryPrefix + suffix;
httpResponse.sendRedirect(replayUrl);
return true;
}
wbRequest.setExactHost(isExactHostMatch());
handleQuery(wbRequest, httpRequest, httpResponse);
}
} else {
handled = dispatchLocal(httpRequest, httpResponse);
}
} catch (BetterRequestException e) {
e.generateResponse(httpResponse, wbRequest);
httpResponse.getWriter();
handled = true;
} catch (WaybackException e) {
if (httpResponse.isCommitted()) {
return true;
}
if (wbRequest == null) {
wbRequest = new WaybackRequest();
wbRequest.setAccessPoint(this);
}
logError(httpResponse, errorMsgHeader, e, wbRequest);
LiveWebState liveWebState = LiveWebState.NOT_FOUND;
if ((getLiveWebRedirector() != null) &&
!wbRequest.hasMementoAcceptDatetime() && !wbRequest.isMementoTimemapRequest()) {
liveWebState = getLiveWebRedirector().handleRedirect(e, wbRequest, httpRequest, httpResponse);
}
if (liveWebState != LiveWebState.REDIRECTED) {
e.setLiveWebAvailable(liveWebState == LiveWebState.FOUND);
getException().renderException(httpRequest, httpResponse, wbRequest, e, getUriConverter());
}
handled = true;
} catch (Exception other) {
logError(httpResponse, errorMsgHeader, other, wbRequest);
} finally {
ZipNumBlockLoader.closeAllReaders();
}
return handled;
} | public boolean handlerequest(httpservletrequest httprequest, httpservletresponse httpresponse) throws servletexception, ioexception { waybackrequest wbrequest = null; boolean handled = false; try { perfstats.clearall(); if (this.isenableperfstatsheader() && (perfstatsheader != null)) { perfstats.timestart(perfstat.total); httpresponse = new perfwritinghttpservletresponse(httprequest, httpresponse, perfstat.total, perfstatsheader, perfstatsheaderformat); } string inputpath = translaterequestpathquery(httprequest); thread.currentthread().setname("thread " + thread.currentthread().getid() + " " + getbeanname() + " handling: " + inputpath); logger.fine("handling translated: " + inputpath); wbrequest = getparser().parse(httprequest, this); if (wbrequest != null) { handled = true; wbrequest.setaccesspoint(this); wbrequest.extracthttprequestinfo(httprequest); if (getauthentication() != null) { if (!getauthentication().istrue(wbrequest)) { throw new authenticationcontrolexception( "unauthorized", isrequestauth()); } } if (wbrequest.getexclusionfilter() == null) { wbrequest.setexclusionfilter(createexclusionfilter()); } wbrequest.setexactscheme(isexactschemematch()); if (wbrequest.isreplayrequest()) { if (bouncetoreplayprefix) { string suffix = translaterequestpathquery(httprequest); string replayurl = replayprefix + suffix; httpresponse.sendredirect(replayurl); return true; } handlereplay(wbrequest, httprequest, httpresponse); } else { if (bouncetoqueryprefix) { string suffix = translaterequestpathquery(httprequest); string replayurl = queryprefix + suffix; httpresponse.sendredirect(replayurl); return true; } wbrequest.setexacthost(isexacthostmatch()); handlequery(wbrequest, httprequest, httpresponse); } } else { handled = dispatchlocal(httprequest, httpresponse); } } catch (betterrequestexception e) { e.generateresponse(httpresponse, wbrequest); httpresponse.getwriter(); handled = true; } catch (waybackexception e) { if (httpresponse.iscommitted()) { return true; } if (wbrequest == null) { wbrequest = new waybackrequest(); wbrequest.setaccesspoint(this); } logerror(httpresponse, errormsgheader, e, wbrequest); livewebstate livewebstate = livewebstate.not_found; if ((getlivewebredirector() != null) && !wbrequest.hasmementoacceptdatetime() && !wbrequest.ismementotimemaprequest()) { livewebstate = getlivewebredirector().handleredirect(e, wbrequest, httprequest, httpresponse); } if (livewebstate != livewebstate.redirected) { e.setlivewebavailable(livewebstate == livewebstate.found); getexception().renderexception(httprequest, httpresponse, wbrequest, e, geturiconverter()); } handled = true; } catch (exception other) { logerror(httpresponse, errormsgheader, other, wbrequest); } finally { zipnumblockloader.closeallreaders(); } return handled; } | csrster/openwayback-csrdev | [
1,
0,
0,
0
] |
1,957 | private void actionDelete(AjaxRequestTarget aTarget)
throws IOException, UIMAException, ClassNotFoundException
{
BratAnnotatorModel bratAnnotatorModel = getModelObject();
JCas jCas = getCas(bratAnnotatorModel);
AnnotationFS fs = selectByAddr(jCas, selectedAnnotationId);
TypeAdapter adapter = getAdapter(selectedAnnotationLayer);
String attachFeatureName = adapter.getAttachFeatureName();
String attachTypeName = adapter.getAnnotationTypeName();
Set<TypeAdapter> typeAdapters = new HashSet<TypeAdapter>();
for (AnnotationLayer layer : annotationService.listAnnotationLayer(bratAnnotatorModel
.getProject())) {
typeAdapters.add(getAdapter(layer));
}
// delete associated relation annotation
for (TypeAdapter ad : typeAdapters) {
if (adapter.getAnnotationTypeName().equals(ad.getAnnotationTypeName())) {
continue;
}
String tn = ad.getAttachTypeName();
if (tn == null) {
continue;
}
if (tn.equals(attachTypeName)) {
Sentence thisSentence = BratAjaxCasUtil.getCurrentSentence(jCas, beginOffset,
endOffset);
ad.deleteBySpan(jCas, fs, thisSentence.getBegin(), thisSentence.getEnd());
break;
}
String fn = ad.getAttachFeatureName();
if (fn == null) {
continue;
}
if (fn.equals(attachFeatureName)) {
Sentence thisSentence = BratAjaxCasUtil.getCurrentSentence(jCas, beginOffset,
endOffset);
ad.deleteBySpan(jCas, fs, thisSentence.getBegin(), thisSentence.getEnd());
break;
}
}
// BEGIN HACK - Issue 933
if (adapter instanceof ChainAdapter) {
((ChainAdapter) adapter).setArc(false);
}
// END HACK - Issue 933
adapter.delete(jCas, selectedAnnotationId);
repository.updateJCas(bratAnnotatorModel.getMode(), bratAnnotatorModel.getDocument(),
bratAnnotatorModel.getUser(), jCas);
// update timestamp now
int sentenceNumber = BratAjaxCasUtil.getSentenceNumber(jCas, beginOffset);
bratAnnotatorModel.getDocument().setSentenceAccessed(sentenceNumber);
repository.updateTimeStamp(bratAnnotatorModel.getDocument(), bratAnnotatorModel.getUser(),
bratAnnotatorModel.getMode());
if (bratAnnotatorModel.isScrollPage()) {
updateSentenceAddressAndOffsets(jCas, beginOffset);
}
bratAnnotatorModel.setRememberedSpanLayer(selectedAnnotationLayer);
bratAnnotatorModel.setAnnotate(false);
// store latest annotations
for (IModel<String> model : featureValueModels) {
AnnotationFeature feature = featuresModel.get(featureValueModels.indexOf(model))
.getObject().feature;
selectedAnnotationLayer = feature.getLayer();
selectedFeatureValues.put(feature, model.getObject());
}
info(generateMessage(selectedAnnotationLayer, null, true));
// A hack to rememeber the Visural DropDown display
// value
bratAnnotatorModel.setRememberedSpanLayer(selectedAnnotationLayer);
bratAnnotatorModel.setRememberedSpanFeatures(selectedFeatureValues);
selectedSpanText = "";
selectedAnnotationId = -1;
aTarget.add(annotationFeatureForm);
// setLayerAndFeatureModels(jCas);
bratRender(aTarget, jCas);
onChange(aTarget, getModelObject());
} | private void actionDelete(AjaxRequestTarget aTarget)
throws IOException, UIMAException, ClassNotFoundException
{
BratAnnotatorModel bratAnnotatorModel = getModelObject();
JCas jCas = getCas(bratAnnotatorModel);
AnnotationFS fs = selectByAddr(jCas, selectedAnnotationId);
TypeAdapter adapter = getAdapter(selectedAnnotationLayer);
String attachFeatureName = adapter.getAttachFeatureName();
String attachTypeName = adapter.getAnnotationTypeName();
Set<TypeAdapter> typeAdapters = new HashSet<TypeAdapter>();
for (AnnotationLayer layer : annotationService.listAnnotationLayer(bratAnnotatorModel
.getProject())) {
typeAdapters.add(getAdapter(layer));
}
for (TypeAdapter ad : typeAdapters) {
if (adapter.getAnnotationTypeName().equals(ad.getAnnotationTypeName())) {
continue;
}
String tn = ad.getAttachTypeName();
if (tn == null) {
continue;
}
if (tn.equals(attachTypeName)) {
Sentence thisSentence = BratAjaxCasUtil.getCurrentSentence(jCas, beginOffset,
endOffset);
ad.deleteBySpan(jCas, fs, thisSentence.getBegin(), thisSentence.getEnd());
break;
}
String fn = ad.getAttachFeatureName();
if (fn == null) {
continue;
}
if (fn.equals(attachFeatureName)) {
Sentence thisSentence = BratAjaxCasUtil.getCurrentSentence(jCas, beginOffset,
endOffset);
ad.deleteBySpan(jCas, fs, thisSentence.getBegin(), thisSentence.getEnd());
break;
}
}
if (adapter instanceof ChainAdapter) {
((ChainAdapter) adapter).setArc(false);
}
adapter.delete(jCas, selectedAnnotationId);
repository.updateJCas(bratAnnotatorModel.getMode(), bratAnnotatorModel.getDocument(),
bratAnnotatorModel.getUser(), jCas);
int sentenceNumber = BratAjaxCasUtil.getSentenceNumber(jCas, beginOffset);
bratAnnotatorModel.getDocument().setSentenceAccessed(sentenceNumber);
repository.updateTimeStamp(bratAnnotatorModel.getDocument(), bratAnnotatorModel.getUser(),
bratAnnotatorModel.getMode());
if (bratAnnotatorModel.isScrollPage()) {
updateSentenceAddressAndOffsets(jCas, beginOffset);
}
bratAnnotatorModel.setRememberedSpanLayer(selectedAnnotationLayer);
bratAnnotatorModel.setAnnotate(false);
for (IModel<String> model : featureValueModels) {
AnnotationFeature feature = featuresModel.get(featureValueModels.indexOf(model))
.getObject().feature;
selectedAnnotationLayer = feature.getLayer();
selectedFeatureValues.put(feature, model.getObject());
}
info(generateMessage(selectedAnnotationLayer, null, true));
bratAnnotatorModel.setRememberedSpanLayer(selectedAnnotationLayer);
bratAnnotatorModel.setRememberedSpanFeatures(selectedFeatureValues);
selectedSpanText = "";
selectedAnnotationId = -1;
aTarget.add(annotationFeatureForm);
bratRender(aTarget, jCas);
onChange(aTarget, getModelObject());
} | private void actiondelete(ajaxrequesttarget atarget) throws ioexception, uimaexception, classnotfoundexception { bratannotatormodel bratannotatormodel = getmodelobject(); jcas jcas = getcas(bratannotatormodel); annotationfs fs = selectbyaddr(jcas, selectedannotationid); typeadapter adapter = getadapter(selectedannotationlayer); string attachfeaturename = adapter.getattachfeaturename(); string attachtypename = adapter.getannotationtypename(); set<typeadapter> typeadapters = new hashset<typeadapter>(); for (annotationlayer layer : annotationservice.listannotationlayer(bratannotatormodel .getproject())) { typeadapters.add(getadapter(layer)); } for (typeadapter ad : typeadapters) { if (adapter.getannotationtypename().equals(ad.getannotationtypename())) { continue; } string tn = ad.getattachtypename(); if (tn == null) { continue; } if (tn.equals(attachtypename)) { sentence thissentence = bratajaxcasutil.getcurrentsentence(jcas, beginoffset, endoffset); ad.deletebyspan(jcas, fs, thissentence.getbegin(), thissentence.getend()); break; } string fn = ad.getattachfeaturename(); if (fn == null) { continue; } if (fn.equals(attachfeaturename)) { sentence thissentence = bratajaxcasutil.getcurrentsentence(jcas, beginoffset, endoffset); ad.deletebyspan(jcas, fs, thissentence.getbegin(), thissentence.getend()); break; } } if (adapter instanceof chainadapter) { ((chainadapter) adapter).setarc(false); } adapter.delete(jcas, selectedannotationid); repository.updatejcas(bratannotatormodel.getmode(), bratannotatormodel.getdocument(), bratannotatormodel.getuser(), jcas); int sentencenumber = bratajaxcasutil.getsentencenumber(jcas, beginoffset); bratannotatormodel.getdocument().setsentenceaccessed(sentencenumber); repository.updatetimestamp(bratannotatormodel.getdocument(), bratannotatormodel.getuser(), bratannotatormodel.getmode()); if (bratannotatormodel.isscrollpage()) { updatesentenceaddressandoffsets(jcas, beginoffset); } bratannotatormodel.setrememberedspanlayer(selectedannotationlayer); bratannotatormodel.setannotate(false); for (imodel<string> model : featurevaluemodels) { annotationfeature feature = featuresmodel.get(featurevaluemodels.indexof(model)) .getobject().feature; selectedannotationlayer = feature.getlayer(); selectedfeaturevalues.put(feature, model.getobject()); } info(generatemessage(selectedannotationlayer, null, true)); bratannotatormodel.setrememberedspanlayer(selectedannotationlayer); bratannotatormodel.setrememberedspanfeatures(selectedfeaturevalues); selectedspantext = ""; selectedannotationid = -1; atarget.add(annotationfeatureform); bratrender(atarget, jcas); onchange(atarget, getmodelobject()); } | debovis/webanno | [
0,
0,
0,
0
] |
34,792 | private List<Pair<Object, Double>> getMostInfluentialFeatures(Label clazz, FeatureVector featureVector) {
assert this.model instanceof NaiveBayesModel;
NaiveBayesModel myModel = (NaiveBayesModel) this.model;
List<Pair<Object, Double>> mostInfluentialFeatures = new ArrayList<>();
for (Object feature : featureVector) {
double classConditional = myModel.computeClassConditionalProbability(feature, clazz);
if (useLogits)
classConditional = -Math.log(classConditional);
mostInfluentialFeatures.add(Pair.of(feature, classConditional));
}
// sort the list
// TODO understand logits!!
// remove 1 counts!
if (useLogits)
mostInfluentialFeatures.sort(Comparator.comparing(Pair::getRight));
else
mostInfluentialFeatures.sort((o1, o2) -> o2.getRight().compareTo(o1.getRight()));
return mostInfluentialFeatures.subList(0, mostInfluentialFeatures.size() <= numberOfInfluentialFeatures ? mostInfluentialFeatures.size() - 1 : numberOfInfluentialFeatures);
} | private List<Pair<Object, Double>> getMostInfluentialFeatures(Label clazz, FeatureVector featureVector) {
assert this.model instanceof NaiveBayesModel;
NaiveBayesModel myModel = (NaiveBayesModel) this.model;
List<Pair<Object, Double>> mostInfluentialFeatures = new ArrayList<>();
for (Object feature : featureVector) {
double classConditional = myModel.computeClassConditionalProbability(feature, clazz);
if (useLogits)
classConditional = -Math.log(classConditional);
mostInfluentialFeatures.add(Pair.of(feature, classConditional));
}
if (useLogits)
mostInfluentialFeatures.sort(Comparator.comparing(Pair::getRight));
else
mostInfluentialFeatures.sort((o1, o2) -> o2.getRight().compareTo(o1.getRight()));
return mostInfluentialFeatures.subList(0, mostInfluentialFeatures.size() <= numberOfInfluentialFeatures ? mostInfluentialFeatures.size() - 1 : numberOfInfluentialFeatures);
} | private list<pair<object, double>> getmostinfluentialfeatures(label clazz, featurevector featurevector) { assert this.model instanceof naivebayesmodel; naivebayesmodel mymodel = (naivebayesmodel) this.model; list<pair<object, double>> mostinfluentialfeatures = new arraylist<>(); for (object feature : featurevector) { double classconditional = mymodel.computeclassconditionalprobability(feature, clazz); if (uselogits) classconditional = -math.log(classconditional); mostinfluentialfeatures.add(pair.of(feature, classconditional)); } if (uselogits) mostinfluentialfeatures.sort(comparator.comparing(pair::getright)); else mostinfluentialfeatures.sort((o1, o2) -> o2.getright().compareto(o1.getright())); return mostinfluentialfeatures.sublist(0, mostinfluentialfeatures.size() <= numberofinfluentialfeatures ? mostinfluentialfeatures.size() - 1 : numberofinfluentialfeatures); } | floschne/NLP_ThumbnailAnnotator | [
1,
0,
0,
0
] |
34,835 | @Override
public boolean allowsNewVlanCreation() throws CloudException, InternalException {
// TODO: change me when implemented
return false;
} | @Override
public boolean allowsNewVlanCreation() throws CloudException, InternalException {
return false;
} | @override public boolean allowsnewvlancreation() throws cloudexception, internalexception { return false; } | erik-johnson/dasein-cloud-vcloud | [
0,
1,
0,
0
] |
34,840 | @DataProvider(name = "TrimCigarData")
public Object[][] makeTrimCigarData() {
List<Object[]> tests = new ArrayList<>();
for ( final CigarOperator op : Arrays.asList(CigarOperator.D, CigarOperator.EQ, CigarOperator.X, CigarOperator.M) ) {
for ( int myLength = 1; myLength < 6; myLength++ ) {
for ( int start = 0; start < myLength - 1; start++ ) {
for ( int end = start; end < myLength; end++ ) {
final int length = end - start + 1;
final List<CigarOperator> padOps = Arrays.asList(CigarOperator.D, CigarOperator.M);
for ( final CigarOperator padOp: padOps) {
for ( int leftPad = 0; leftPad < 2; leftPad++ ) {
for ( int rightPad = 0; rightPad < 2; rightPad++ ) {
tests.add(new Object[]{
(leftPad > 0 ? leftPad + padOp.toString() : "") + myLength + op.toString() + (rightPad > 0 ? rightPad + padOp.toString() : ""),
start + leftPad,
end + leftPad,
length + op.toString()});
}
}
}
}
}
}
}
for ( final int leftPad : Arrays.asList(0, 1, 2, 5) ) {
for ( final int rightPad : Arrays.asList(0, 1, 2, 5) ) {
final int length = leftPad + rightPad;
if ( length > 0 ) {
for ( final int insSize : Arrays.asList(1, 10) ) {
for ( int start = 0; start <= leftPad; start++ ) {
for ( int stop = leftPad; stop < length; stop++ ) {
final int leftPadRemaining = leftPad - start;
final int rightPadRemaining = stop - leftPad + 1;
final String insC = insSize + "I";
tests.add(new Object[]{
leftPad + "M" + insC + rightPad + "M",
start,
stop,
(leftPadRemaining > 0 ? leftPadRemaining + "M" : "") + insC + (rightPadRemaining > 0 ? rightPadRemaining + "M" : "")
});
}
}
}
}
}
}
tests.add(new Object[]{"3M2D4M", 0, 8, "3M2D4M"});
tests.add(new Object[]{"3M2D4M", 2, 8, "1M2D4M"});
tests.add(new Object[]{"3M2D4M", 2, 6, "1M2D2M"});
tests.add(new Object[]{"3M2D4M", 3, 6, "2D2M"});
tests.add(new Object[]{"3M2D4M", 4, 6, "1D2M"});
tests.add(new Object[]{"3M2D4M", 5, 6, "2M"});
tests.add(new Object[]{"3M2D4M", 6, 6, "1M"});
tests.add(new Object[]{"2M3I4M", 0, 5, "2M3I4M"});
tests.add(new Object[]{"2M3I4M", 1, 5, "1M3I4M"});
tests.add(new Object[]{"2M3I4M", 1, 4, "1M3I3M"});
tests.add(new Object[]{"2M3I4M", 2, 4, "3I3M"});
tests.add(new Object[]{"2M3I4M", 2, 3, "3I2M"});
tests.add(new Object[]{"2M3I4M", 2, 2, "3I1M"});
tests.add(new Object[]{"2M3I4M", 3, 4, "2M"});
tests.add(new Object[]{"2M3I4M", 3, 3, "1M"});
tests.add(new Object[]{"2M3I4M", 4, 4, "1M"});
// this doesn't work -- but I'm not sure it should
// tests.add(new Object[]{"2M3I4M", 2, 1, "3I"});
return tests.toArray(new Object[][]{});
} | @DataProvider(name = "TrimCigarData")
public Object[][] makeTrimCigarData() {
List<Object[]> tests = new ArrayList<>();
for ( final CigarOperator op : Arrays.asList(CigarOperator.D, CigarOperator.EQ, CigarOperator.X, CigarOperator.M) ) {
for ( int myLength = 1; myLength < 6; myLength++ ) {
for ( int start = 0; start < myLength - 1; start++ ) {
for ( int end = start; end < myLength; end++ ) {
final int length = end - start + 1;
final List<CigarOperator> padOps = Arrays.asList(CigarOperator.D, CigarOperator.M);
for ( final CigarOperator padOp: padOps) {
for ( int leftPad = 0; leftPad < 2; leftPad++ ) {
for ( int rightPad = 0; rightPad < 2; rightPad++ ) {
tests.add(new Object[]{
(leftPad > 0 ? leftPad + padOp.toString() : "") + myLength + op.toString() + (rightPad > 0 ? rightPad + padOp.toString() : ""),
start + leftPad,
end + leftPad,
length + op.toString()});
}
}
}
}
}
}
}
for ( final int leftPad : Arrays.asList(0, 1, 2, 5) ) {
for ( final int rightPad : Arrays.asList(0, 1, 2, 5) ) {
final int length = leftPad + rightPad;
if ( length > 0 ) {
for ( final int insSize : Arrays.asList(1, 10) ) {
for ( int start = 0; start <= leftPad; start++ ) {
for ( int stop = leftPad; stop < length; stop++ ) {
final int leftPadRemaining = leftPad - start;
final int rightPadRemaining = stop - leftPad + 1;
final String insC = insSize + "I";
tests.add(new Object[]{
leftPad + "M" + insC + rightPad + "M",
start,
stop,
(leftPadRemaining > 0 ? leftPadRemaining + "M" : "") + insC + (rightPadRemaining > 0 ? rightPadRemaining + "M" : "")
});
}
}
}
}
}
}
tests.add(new Object[]{"3M2D4M", 0, 8, "3M2D4M"});
tests.add(new Object[]{"3M2D4M", 2, 8, "1M2D4M"});
tests.add(new Object[]{"3M2D4M", 2, 6, "1M2D2M"});
tests.add(new Object[]{"3M2D4M", 3, 6, "2D2M"});
tests.add(new Object[]{"3M2D4M", 4, 6, "1D2M"});
tests.add(new Object[]{"3M2D4M", 5, 6, "2M"});
tests.add(new Object[]{"3M2D4M", 6, 6, "1M"});
tests.add(new Object[]{"2M3I4M", 0, 5, "2M3I4M"});
tests.add(new Object[]{"2M3I4M", 1, 5, "1M3I4M"});
tests.add(new Object[]{"2M3I4M", 1, 4, "1M3I3M"});
tests.add(new Object[]{"2M3I4M", 2, 4, "3I3M"});
tests.add(new Object[]{"2M3I4M", 2, 3, "3I2M"});
tests.add(new Object[]{"2M3I4M", 2, 2, "3I1M"});
tests.add(new Object[]{"2M3I4M", 3, 4, "2M"});
tests.add(new Object[]{"2M3I4M", 3, 3, "1M"});
tests.add(new Object[]{"2M3I4M", 4, 4, "1M"});
return tests.toArray(new Object[][]{});
} | @dataprovider(name = "trimcigardata") public object[][] maketrimcigardata() { list<object[]> tests = new arraylist<>(); for ( final cigaroperator op : arrays.aslist(cigaroperator.d, cigaroperator.eq, cigaroperator.x, cigaroperator.m) ) { for ( int mylength = 1; mylength < 6; mylength++ ) { for ( int start = 0; start < mylength - 1; start++ ) { for ( int end = start; end < mylength; end++ ) { final int length = end - start + 1; final list<cigaroperator> padops = arrays.aslist(cigaroperator.d, cigaroperator.m); for ( final cigaroperator padop: padops) { for ( int leftpad = 0; leftpad < 2; leftpad++ ) { for ( int rightpad = 0; rightpad < 2; rightpad++ ) { tests.add(new object[]{ (leftpad > 0 ? leftpad + padop.tostring() : "") + mylength + op.tostring() + (rightpad > 0 ? rightpad + padop.tostring() : ""), start + leftpad, end + leftpad, length + op.tostring()}); } } } } } } } for ( final int leftpad : arrays.aslist(0, 1, 2, 5) ) { for ( final int rightpad : arrays.aslist(0, 1, 2, 5) ) { final int length = leftpad + rightpad; if ( length > 0 ) { for ( final int inssize : arrays.aslist(1, 10) ) { for ( int start = 0; start <= leftpad; start++ ) { for ( int stop = leftpad; stop < length; stop++ ) { final int leftpadremaining = leftpad - start; final int rightpadremaining = stop - leftpad + 1; final string insc = inssize + "i"; tests.add(new object[]{ leftpad + "m" + insc + rightpad + "m", start, stop, (leftpadremaining > 0 ? leftpadremaining + "m" : "") + insc + (rightpadremaining > 0 ? rightpadremaining + "m" : "") }); } } } } } } tests.add(new object[]{"3m2d4m", 0, 8, "3m2d4m"}); tests.add(new object[]{"3m2d4m", 2, 8, "1m2d4m"}); tests.add(new object[]{"3m2d4m", 2, 6, "1m2d2m"}); tests.add(new object[]{"3m2d4m", 3, 6, "2d2m"}); tests.add(new object[]{"3m2d4m", 4, 6, "1d2m"}); tests.add(new object[]{"3m2d4m", 5, 6, "2m"}); tests.add(new object[]{"3m2d4m", 6, 6, "1m"}); tests.add(new object[]{"2m3i4m", 0, 5, "2m3i4m"}); tests.add(new object[]{"2m3i4m", 1, 5, "1m3i4m"}); tests.add(new object[]{"2m3i4m", 1, 4, "1m3i3m"}); tests.add(new object[]{"2m3i4m", 2, 4, "3i3m"}); tests.add(new object[]{"2m3i4m", 2, 3, "3i2m"}); tests.add(new object[]{"2m3i4m", 2, 2, "3i1m"}); tests.add(new object[]{"2m3i4m", 3, 4, "2m"}); tests.add(new object[]{"2m3i4m", 3, 3, "1m"}); tests.add(new object[]{"2m3i4m", 4, 4, "1m"}); return tests.toarray(new object[][]{}); } | ga4gh/gatk | [
0,
0,
1,
0
] |
18,558 | @Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
//TODO set last message time
final ChatDescription description = descriptionList.get(position);
User mainUser = ((GlobalVars)(inboxFragment.getActivity()).getApplication()).getUser();
final User otherUser;
if (Objects.equals(mainUser.getUid(), description.getUserid1()))
otherUser = userMap.get(description.getUserid2());
else otherUser = userMap.get(description.getUserid1());
final InboxViewHolder viewHolder = (InboxViewHolder) holder;
Glide.with(context).load(otherUser.getProfileUrl()).asBitmap().centerCrop().dontAnimate().
into(new BitmapImageViewTarget(viewHolder.ivProfile) {
@Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCircular(true);
viewHolder.ivProfile.setImageDrawable(circularBitmapDrawable);
viewHolder.ivProfile.setBorderColor(otherUser.getColorHexDark(context));
}
});
String lastMessage;
if (description.lastMessage != null) lastMessage = description.lastMessage.getText();
else lastMessage = "";
viewHolder.tvLastMessage.setText(lastMessage);
viewHolder.tvLastMessage.setEllipsize(TextUtils.TruncateAt.END);
viewHolder.tvLastMessage.setMaxLines(2);
viewHolder.tvOtherUserName.setText(otherUser.getFirstName());
Long seconds = description.getLastMessage().getSentTime().getTime();
viewHolder.tvTime.setText(TimeFormatter.getTimeDifference(seconds));
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(view.getContext(), MessageActivity.class);
i.putExtra("otherUser", Parcels.wrap(otherUser));
i.putExtra("description", Parcels.wrap(description));
inboxFragment.startActivityForResult(i, InboxFragment.CHANGEDESCRIPTION);
}
});
if (position == 0) holder.itemView.setPadding(0, 200, 0, 0); //not the right way to do this
} | @Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final ChatDescription description = descriptionList.get(position);
User mainUser = ((GlobalVars)(inboxFragment.getActivity()).getApplication()).getUser();
final User otherUser;
if (Objects.equals(mainUser.getUid(), description.getUserid1()))
otherUser = userMap.get(description.getUserid2());
else otherUser = userMap.get(description.getUserid1());
final InboxViewHolder viewHolder = (InboxViewHolder) holder;
Glide.with(context).load(otherUser.getProfileUrl()).asBitmap().centerCrop().dontAnimate().
into(new BitmapImageViewTarget(viewHolder.ivProfile) {
@Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCircular(true);
viewHolder.ivProfile.setImageDrawable(circularBitmapDrawable);
viewHolder.ivProfile.setBorderColor(otherUser.getColorHexDark(context));
}
});
String lastMessage;
if (description.lastMessage != null) lastMessage = description.lastMessage.getText();
else lastMessage = "";
viewHolder.tvLastMessage.setText(lastMessage);
viewHolder.tvLastMessage.setEllipsize(TextUtils.TruncateAt.END);
viewHolder.tvLastMessage.setMaxLines(2);
viewHolder.tvOtherUserName.setText(otherUser.getFirstName());
Long seconds = description.getLastMessage().getSentTime().getTime();
viewHolder.tvTime.setText(TimeFormatter.getTimeDifference(seconds));
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(view.getContext(), MessageActivity.class);
i.putExtra("otherUser", Parcels.wrap(otherUser));
i.putExtra("description", Parcels.wrap(description));
inboxFragment.startActivityForResult(i, InboxFragment.CHANGEDESCRIPTION);
}
});
if (position == 0) holder.itemView.setPadding(0, 200, 0, 0);
} | @override public void onbindviewholder(recyclerview.viewholder holder, int position) { final chatdescription description = descriptionlist.get(position); user mainuser = ((globalvars)(inboxfragment.getactivity()).getapplication()).getuser(); final user otheruser; if (objects.equals(mainuser.getuid(), description.getuserid1())) otheruser = usermap.get(description.getuserid2()); else otheruser = usermap.get(description.getuserid1()); final inboxviewholder viewholder = (inboxviewholder) holder; glide.with(context).load(otheruser.getprofileurl()).asbitmap().centercrop().dontanimate(). into(new bitmapimageviewtarget(viewholder.ivprofile) { @override protected void setresource(bitmap resource) { roundedbitmapdrawable circularbitmapdrawable = roundedbitmapdrawablefactory.create(context.getresources(), resource); circularbitmapdrawable.setcircular(true); viewholder.ivprofile.setimagedrawable(circularbitmapdrawable); viewholder.ivprofile.setbordercolor(otheruser.getcolorhexdark(context)); } }); string lastmessage; if (description.lastmessage != null) lastmessage = description.lastmessage.gettext(); else lastmessage = ""; viewholder.tvlastmessage.settext(lastmessage); viewholder.tvlastmessage.setellipsize(textutils.truncateat.end); viewholder.tvlastmessage.setmaxlines(2); viewholder.tvotherusername.settext(otheruser.getfirstname()); long seconds = description.getlastmessage().getsenttime().gettime(); viewholder.tvtime.settext(timeformatter.gettimedifference(seconds)); viewholder.itemview.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { intent i = new intent(view.getcontext(), messageactivity.class); i.putextra("otheruser", parcels.wrap(otheruser)); i.putextra("description", parcels.wrap(description)); inboxfragment.startactivityforresult(i, inboxfragment.changedescription); } }); if (position == 0) holder.itemview.setpadding(0, 200, 0, 0); } | dgisser/Ripple | [
0,
1,
0,
0
] |
18,576 | private void computeTimes (TransportNetwork network, ProfileRequest req, TIntIntMap accessTimes, TIntIntMap egressTimes) {
if (!accessTimes.containsKey(this.boardStops[0])) throw new IllegalArgumentException("Access times do not contain first stop of path!");
if (!egressTimes.containsKey(this.alightStops[this.length - 1])) throw new IllegalArgumentException("Egress times do not contain last stop of path!");
int accessTime = accessTimes.get(this.boardStops[0]);
int egressTime = egressTimes.get(this.alightStops[this.length - 1]);
if (network.transitLayer.hasFrequencies) {
// TODO fix
throw new UnsupportedOperationException("Frequency-based trips are not yet supported in customer-facing profile routing");
}
// we now know what patterns are being used, interleave to find times
// NB no need to reverse-optimize these itineraries; we'll just filter them below.
TripPattern[] patterns = IntStream.of(this.patterns).mapToObj(p -> network.transitLayer.tripPatterns.get(p)).toArray(s -> new TripPattern[s]);
// find all possible times to board and alight each pattern
// for each trip pattern, for each trip on that pattern, array of [depart origin, arrive destination]
int[][][] times = new int[patterns.length][][];
for (int patIdx = 0; patIdx < patterns.length; patIdx++) {
final int pidx = patIdx;
int fromStopInPattern = 0;
while (patterns[patIdx].stops[fromStopInPattern] != this.boardStops[pidx]) fromStopInPattern++;
int toStopInPattern = fromStopInPattern;
while (patterns[patIdx].stops[toStopInPattern] != this.alightStops[pidx]) {
// if we visit the board stop multiple times, board at the one closest to the alight stop
// TODO better handle duplicated stops/loop routes
if (patterns[patIdx].stops[toStopInPattern] == this.boardStops[pidx]) fromStopInPattern = toStopInPattern;
toStopInPattern++;
}
final int finalFromStopInPattern = fromStopInPattern;
final int finalToStopInPattern = toStopInPattern;
times[patIdx] = patterns[patIdx].tripSchedules.stream()
.map(ts -> new int[] { ts.departures[finalFromStopInPattern], ts.arrivals[finalToStopInPattern] })
.toArray(s -> new int[s][]);
}
// sort by departure time of each trip, within each pattern
Stream.of(times).forEach(t -> Arrays.sort(t, (t1, t2) -> t1[0] - t2[0]));
// loop over departures within the time window
// firstTrip is the trip on the first pattern
int firstTrip = 0;
while (times[0][firstTrip][0] < req.fromTime + accessTime + FastRaptorWorker.BOARD_SLACK_SECONDS) firstTrip++;
// now interleave times
double walkSpeedMillimetersPerSecond = req.walkSpeed * 1000;
TIMES: while (firstTrip < times[0].length) {
Itinerary itin = new Itinerary(this.patterns.length);
int time = times[0][firstTrip][0];
// linear scan over timetable to do interleaving
for (int patIdx = 0; patIdx < this.patterns.length; patIdx++) {
int trip = 0;
while (times[patIdx][trip][0] < time) {
trip++;
if (trip >= times[patIdx].length) break TIMES; // we've found the end of the times at which this path is possible
}
itin.boardTimes[patIdx] = times[patIdx][trip][0];
itin.alightTimes[patIdx] = times[patIdx][trip][1];
if (patIdx < this.length - 1) {
// find the transfer time
TIntList transfers = network.transitLayer.transfersForStop.get(this.alightStops[patIdx]);
int transferTime;
if (this.alightStops[patIdx] != this.boardStops[patIdx + 1]) {
transferTime = -1;
for (int i = 0; i < transfers.size(); i += 2) {
if (transfers.get(i) == this.boardStops[patIdx + 1]) {
int transferDistanceMillimeters = transfers.get(i + 1);
transferTime = (int)(transferDistanceMillimeters / walkSpeedMillimetersPerSecond);
break;
}
}
if (transferTime == -1) {
throw new IllegalStateException("Did not find transfer in transit network, indicates an internal error");
}
}
else transferTime = 0; // no transfer time, we are at the same stop (board slack applied below)
// TODO should board slack be applied at the origin stop? Is this done in RaptorWorker?
// See also below in computeStatistics
time = times[patIdx][trip][1] + transferTime + FastRaptorWorker.BOARD_SLACK_SECONDS;
itin.arriveAtBoardStopTimes[patIdx + 1] = time;
}
}
this.itineraries.add(itin);
firstTrip++;
}
sortAndFilterItineraries();
computeStatistics(req, accessTime, egressTime);
} | private void computeTimes (TransportNetwork network, ProfileRequest req, TIntIntMap accessTimes, TIntIntMap egressTimes) {
if (!accessTimes.containsKey(this.boardStops[0])) throw new IllegalArgumentException("Access times do not contain first stop of path!");
if (!egressTimes.containsKey(this.alightStops[this.length - 1])) throw new IllegalArgumentException("Egress times do not contain last stop of path!");
int accessTime = accessTimes.get(this.boardStops[0]);
int egressTime = egressTimes.get(this.alightStops[this.length - 1]);
if (network.transitLayer.hasFrequencies) {
throw new UnsupportedOperationException("Frequency-based trips are not yet supported in customer-facing profile routing");
}
TripPattern[] patterns = IntStream.of(this.patterns).mapToObj(p -> network.transitLayer.tripPatterns.get(p)).toArray(s -> new TripPattern[s]);
int[][][] times = new int[patterns.length][][];
for (int patIdx = 0; patIdx < patterns.length; patIdx++) {
final int pidx = patIdx;
int fromStopInPattern = 0;
while (patterns[patIdx].stops[fromStopInPattern] != this.boardStops[pidx]) fromStopInPattern++;
int toStopInPattern = fromStopInPattern;
while (patterns[patIdx].stops[toStopInPattern] != this.alightStops[pidx]) {
if (patterns[patIdx].stops[toStopInPattern] == this.boardStops[pidx]) fromStopInPattern = toStopInPattern;
toStopInPattern++;
}
final int finalFromStopInPattern = fromStopInPattern;
final int finalToStopInPattern = toStopInPattern;
times[patIdx] = patterns[patIdx].tripSchedules.stream()
.map(ts -> new int[] { ts.departures[finalFromStopInPattern], ts.arrivals[finalToStopInPattern] })
.toArray(s -> new int[s][]);
}
Stream.of(times).forEach(t -> Arrays.sort(t, (t1, t2) -> t1[0] - t2[0]));
int firstTrip = 0;
while (times[0][firstTrip][0] < req.fromTime + accessTime + FastRaptorWorker.BOARD_SLACK_SECONDS) firstTrip++;
double walkSpeedMillimetersPerSecond = req.walkSpeed * 1000;
TIMES: while (firstTrip < times[0].length) {
Itinerary itin = new Itinerary(this.patterns.length);
int time = times[0][firstTrip][0];
for (int patIdx = 0; patIdx < this.patterns.length; patIdx++) {
int trip = 0;
while (times[patIdx][trip][0] < time) {
trip++;
if (trip >= times[patIdx].length) break TIMES;
}
itin.boardTimes[patIdx] = times[patIdx][trip][0];
itin.alightTimes[patIdx] = times[patIdx][trip][1];
if (patIdx < this.length - 1) {
TIntList transfers = network.transitLayer.transfersForStop.get(this.alightStops[patIdx]);
int transferTime;
if (this.alightStops[patIdx] != this.boardStops[patIdx + 1]) {
transferTime = -1;
for (int i = 0; i < transfers.size(); i += 2) {
if (transfers.get(i) == this.boardStops[patIdx + 1]) {
int transferDistanceMillimeters = transfers.get(i + 1);
transferTime = (int)(transferDistanceMillimeters / walkSpeedMillimetersPerSecond);
break;
}
}
if (transferTime == -1) {
throw new IllegalStateException("Did not find transfer in transit network, indicates an internal error");
}
}
else transferTime = 0;
time = times[patIdx][trip][1] + transferTime + FastRaptorWorker.BOARD_SLACK_SECONDS;
itin.arriveAtBoardStopTimes[patIdx + 1] = time;
}
}
this.itineraries.add(itin);
firstTrip++;
}
sortAndFilterItineraries();
computeStatistics(req, accessTime, egressTime);
} | private void computetimes (transportnetwork network, profilerequest req, tintintmap accesstimes, tintintmap egresstimes) { if (!accesstimes.containskey(this.boardstops[0])) throw new illegalargumentexception("access times do not contain first stop of path!"); if (!egresstimes.containskey(this.alightstops[this.length - 1])) throw new illegalargumentexception("egress times do not contain last stop of path!"); int accesstime = accesstimes.get(this.boardstops[0]); int egresstime = egresstimes.get(this.alightstops[this.length - 1]); if (network.transitlayer.hasfrequencies) { throw new unsupportedoperationexception("frequency-based trips are not yet supported in customer-facing profile routing"); } trippattern[] patterns = intstream.of(this.patterns).maptoobj(p -> network.transitlayer.trippatterns.get(p)).toarray(s -> new trippattern[s]); int[][][] times = new int[patterns.length][][]; for (int patidx = 0; patidx < patterns.length; patidx++) { final int pidx = patidx; int fromstopinpattern = 0; while (patterns[patidx].stops[fromstopinpattern] != this.boardstops[pidx]) fromstopinpattern++; int tostopinpattern = fromstopinpattern; while (patterns[patidx].stops[tostopinpattern] != this.alightstops[pidx]) { if (patterns[patidx].stops[tostopinpattern] == this.boardstops[pidx]) fromstopinpattern = tostopinpattern; tostopinpattern++; } final int finalfromstopinpattern = fromstopinpattern; final int finaltostopinpattern = tostopinpattern; times[patidx] = patterns[patidx].tripschedules.stream() .map(ts -> new int[] { ts.departures[finalfromstopinpattern], ts.arrivals[finaltostopinpattern] }) .toarray(s -> new int[s][]); } stream.of(times).foreach(t -> arrays.sort(t, (t1, t2) -> t1[0] - t2[0])); int firsttrip = 0; while (times[0][firsttrip][0] < req.fromtime + accesstime + fastraptorworker.board_slack_seconds) firsttrip++; double walkspeedmillimeterspersecond = req.walkspeed * 1000; times: while (firsttrip < times[0].length) { itinerary itin = new itinerary(this.patterns.length); int time = times[0][firsttrip][0]; for (int patidx = 0; patidx < this.patterns.length; patidx++) { int trip = 0; while (times[patidx][trip][0] < time) { trip++; if (trip >= times[patidx].length) break times; } itin.boardtimes[patidx] = times[patidx][trip][0]; itin.alighttimes[patidx] = times[patidx][trip][1]; if (patidx < this.length - 1) { tintlist transfers = network.transitlayer.transfersforstop.get(this.alightstops[patidx]); int transfertime; if (this.alightstops[patidx] != this.boardstops[patidx + 1]) { transfertime = -1; for (int i = 0; i < transfers.size(); i += 2) { if (transfers.get(i) == this.boardstops[patidx + 1]) { int transferdistancemillimeters = transfers.get(i + 1); transfertime = (int)(transferdistancemillimeters / walkspeedmillimeterspersecond); break; } } if (transfertime == -1) { throw new illegalstateexception("did not find transfer in transit network, indicates an internal error"); } } else transfertime = 0; time = times[patidx][trip][1] + transfertime + fastraptorworker.board_slack_seconds; itin.arriveatboardstoptimes[patidx + 1] = time; } } this.itineraries.add(itin); firsttrip++; } sortandfilteritineraries(); computestatistics(req, accesstime, egresstime); } | enoxos/r5 | [
1,
0,
1,
0
] |
18,691 | protected FocusListener createFocusListener() {
return new BasicComboBoxUI.FocusHandler() {
public void focusLost(final FocusEvent e) {
hasFocus = false;
if (!e.isTemporary()) {
setPopupVisible(comboBox, false);
}
comboBox.repaint();
// Notify assistive technologies that the combo box lost focus
final AccessibleContext ac = ((Accessible)comboBox).getAccessibleContext();
if (ac != null) {
ac.firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY, AccessibleState.FOCUSED, null);
}
}
};
} | protected FocusListener createFocusListener() {
return new BasicComboBoxUI.FocusHandler() {
public void focusLost(final FocusEvent e) {
hasFocus = false;
if (!e.isTemporary()) {
setPopupVisible(comboBox, false);
}
comboBox.repaint();
final AccessibleContext ac = ((Accessible)comboBox).getAccessibleContext();
if (ac != null) {
ac.firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY, AccessibleState.FOCUSED, null);
}
}
};
} | protected focuslistener createfocuslistener() { return new basiccomboboxui.focushandler() { public void focuslost(final focusevent e) { hasfocus = false; if (!e.istemporary()) { setpopupvisible(combobox, false); } combobox.repaint(); final accessiblecontext ac = ((accessible)combobox).getaccessiblecontext(); if (ac != null) { ac.firepropertychange(accessiblecontext.accessible_state_property, accessiblestate.focused, null); } } }; } | dbac/jdk8 | [
1,
0,
0,
0
] |
10,532 | public WebSocket<JsonNode> socket() {
final Http.Session session = session();
final User currentUser = Application.getLocalUser(session());
return new WebSocket<JsonNode>() {
@Override
public void onReady(In<JsonNode> in, Out<JsonNode> out) {
try {
User u = Application.getLocalUser(session);
//Logger.debug("User " + u.id + " connected");
// Add the new user to the data structures
boolean alreadyOnline = onlineUsers.containsValue(u);
onlineUsers.put(out, u);
/*try (Jedis j = jedisPool.getResource()) {
j.sadd("online_users", Long.toString(u.id));
}*/
// Notify logged users about the new player
if (!alreadyOnline) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode notification = JsonNodeFactory.instance.objectNode();
notification.put("action", "newuser");
notification.put("newuser", mapper.writeValueAsString(currentUser));
broadcastMessage(notification, new HashSet<User>() {{ add(u); }});
}
} catch (RuntimeException e) {
//Logger.debug("Unknown user connected");
} catch (JsonProcessingException e) {
Logger.error(e.getMessage(), e);
}
in.onMessage((data) -> {
Logger.debug(currentUser.id + " - " + data.toString());
String action = data.findPath("action").textValue();
switch (action) {
// TODO: add error handling
case "newgame":
onNewGameResponse(data, currentUser);
break;
case "ready":
onUserReady(data, currentUser);
break;
case "setrowboat":
onSetShip(data, currentUser, new Rowboat());
break;
case "setdestructor":
onSetShip(data, currentUser, new Destructor());
break;
case "setflattop":
onSetShip(data, currentUser, new Flattop());
break;
case "shoot":
onShoot(data, currentUser);
break;
case "userleaves":
onUserLeaves(data, currentUser);
break;
case "getOnlineUsers":
onGetOnlineUsers(data, currentUser);
break;
default:
}
});
in.onClose(() -> {
User u = onlineUsers.get(out);
if (u != null) {
//Logger.debug("User " + u.id + " disconnected");
// Remove user from the data structures
onlineUsers.remove(out);
// Wait for 100 ms to see if the user connects through another websocket
//Thread.sleep(100);
boolean stillOnline = onlineUsers.containsValue(u);
/*try (Jedis j = jedisPool.getResource()) {
j.srem("online_users", Long.toString(u.id));
}*/
// Notify logged users about the leaving player
if (!stillOnline) {
try {
ObjectMapper mapper = new ObjectMapper();
ObjectNode notification = JsonNodeFactory.instance.objectNode();
notification.put("action", "userleaves");
notification.put("leavinguser", mapper.writeValueAsString(currentUser));
broadcastMessage(notification, new HashSet<User>() {{ add(u); }});
} catch (JsonProcessingException e) {
Logger.error(e.getMessage(), e);
}
}
} else {
//Logger.debug("Unknown user disconnected");
}
});
}
};
} | public WebSocket<JsonNode> socket() {
final Http.Session session = session();
final User currentUser = Application.getLocalUser(session());
return new WebSocket<JsonNode>() {
@Override
public void onReady(In<JsonNode> in, Out<JsonNode> out) {
try {
User u = Application.getLocalUser(session);
boolean alreadyOnline = onlineUsers.containsValue(u);
onlineUsers.put(out, u);
if (!alreadyOnline) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode notification = JsonNodeFactory.instance.objectNode();
notification.put("action", "newuser");
notification.put("newuser", mapper.writeValueAsString(currentUser));
broadcastMessage(notification, new HashSet<User>() {{ add(u); }});
}
} catch (RuntimeException e) {
} catch (JsonProcessingException e) {
Logger.error(e.getMessage(), e);
}
in.onMessage((data) -> {
Logger.debug(currentUser.id + " - " + data.toString());
String action = data.findPath("action").textValue();
switch (action) {
case "newgame":
onNewGameResponse(data, currentUser);
break;
case "ready":
onUserReady(data, currentUser);
break;
case "setrowboat":
onSetShip(data, currentUser, new Rowboat());
break;
case "setdestructor":
onSetShip(data, currentUser, new Destructor());
break;
case "setflattop":
onSetShip(data, currentUser, new Flattop());
break;
case "shoot":
onShoot(data, currentUser);
break;
case "userleaves":
onUserLeaves(data, currentUser);
break;
case "getOnlineUsers":
onGetOnlineUsers(data, currentUser);
break;
default:
}
});
in.onClose(() -> {
User u = onlineUsers.get(out);
if (u != null) {
onlineUsers.remove(out);
boolean stillOnline = onlineUsers.containsValue(u);
if (!stillOnline) {
try {
ObjectMapper mapper = new ObjectMapper();
ObjectNode notification = JsonNodeFactory.instance.objectNode();
notification.put("action", "userleaves");
notification.put("leavinguser", mapper.writeValueAsString(currentUser));
broadcastMessage(notification, new HashSet<User>() {{ add(u); }});
} catch (JsonProcessingException e) {
Logger.error(e.getMessage(), e);
}
}
} else {
}
});
}
};
} | public websocket<jsonnode> socket() { final http.session session = session(); final user currentuser = application.getlocaluser(session()); return new websocket<jsonnode>() { @override public void onready(in<jsonnode> in, out<jsonnode> out) { try { user u = application.getlocaluser(session); boolean alreadyonline = onlineusers.containsvalue(u); onlineusers.put(out, u); if (!alreadyonline) { objectmapper mapper = new objectmapper(); objectnode notification = jsonnodefactory.instance.objectnode(); notification.put("action", "newuser"); notification.put("newuser", mapper.writevalueasstring(currentuser)); broadcastmessage(notification, new hashset<user>() {{ add(u); }}); } } catch (runtimeexception e) { } catch (jsonprocessingexception e) { logger.error(e.getmessage(), e); } in.onmessage((data) -> { logger.debug(currentuser.id + " - " + data.tostring()); string action = data.findpath("action").textvalue(); switch (action) { case "newgame": onnewgameresponse(data, currentuser); break; case "ready": onuserready(data, currentuser); break; case "setrowboat": onsetship(data, currentuser, new rowboat()); break; case "setdestructor": onsetship(data, currentuser, new destructor()); break; case "setflattop": onsetship(data, currentuser, new flattop()); break; case "shoot": onshoot(data, currentuser); break; case "userleaves": onuserleaves(data, currentuser); break; case "getonlineusers": ongetonlineusers(data, currentuser); break; default: } }); in.onclose(() -> { user u = onlineusers.get(out); if (u != null) { onlineusers.remove(out); boolean stillonline = onlineusers.containsvalue(u); if (!stillonline) { try { objectmapper mapper = new objectmapper(); objectnode notification = jsonnodefactory.instance.objectnode(); notification.put("action", "userleaves"); notification.put("leavinguser", mapper.writevalueasstring(currentuser)); broadcastmessage(notification, new hashset<user>() {{ add(u); }}); } catch (jsonprocessingexception e) { logger.error(e.getmessage(), e); } } } else { } }); } }; } | daniel-sandro/WTEC1516 | [
0,
1,
0,
0
] |
10,559 | private void postNotification(Context context, AnswerSet answerSet, String message) {
int surveyId = answerSet.getDbSurveyId();
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(context, SurveyActivity.class);
intent.putExtra("programId", answerSet.getDbProgramId());
intent.putExtra("answerSetUUID", answerSet.getUuid());
intent.setAction("com.sema.notification." + surveyId);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Survey survey = answerSet.getSurvey();
Program program = survey != null ? survey.getProgram() : null;
if (survey != null && program != null) {
String programName = program.getDisplayName();
Notification n = new NotificationCompat.Builder(context)
.setContentTitle(programName)
.setContentText(message)
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true)
.setSound(Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.notification_extended))
.build();
notificationManager.notify(answerSet.getStartAlarmRequestCode(), n); // TODO: alternatively could use the same app wide if want only one entry in notifications
}
} | private void postNotification(Context context, AnswerSet answerSet, String message) {
int surveyId = answerSet.getDbSurveyId();
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(context, SurveyActivity.class);
intent.putExtra("programId", answerSet.getDbProgramId());
intent.putExtra("answerSetUUID", answerSet.getUuid());
intent.setAction("com.sema.notification." + surveyId);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Survey survey = answerSet.getSurvey();
Program program = survey != null ? survey.getProgram() : null;
if (survey != null && program != null) {
String programName = program.getDisplayName();
Notification n = new NotificationCompat.Builder(context)
.setContentTitle(programName)
.setContentText(message)
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true)
.setSound(Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.notification_extended))
.build();
notificationManager.notify(answerSet.getStartAlarmRequestCode(), n);
}
} | private void postnotification(context context, answerset answerset, string message) { int surveyid = answerset.getdbsurveyid(); notificationmanager notificationmanager = (notificationmanager)context.getsystemservice(context.notification_service); intent intent = new intent(context, surveyactivity.class); intent.putextra("programid", answerset.getdbprogramid()); intent.putextra("answersetuuid", answerset.getuuid()); intent.setaction("com.sema.notification." + surveyid); pendingintent pintent = pendingintent.getactivity(context, 0, intent, pendingintent.flag_update_current); survey survey = answerset.getsurvey(); program program = survey != null ? survey.getprogram() : null; if (survey != null && program != null) { string programname = program.getdisplayname(); notification n = new notificationcompat.builder(context) .setcontenttitle(programname) .setcontenttext(message) .setsmallicon(r.drawable.ic_launcher) .setcontentintent(pintent) .setautocancel(true) .setsound(uri.parse("android.resource://" + context.getpackagename() + "/" + r.raw.notification_extended)) .build(); notificationmanager.notify(answerset.getstartalarmrequestcode(), n); } } | eorygen/sema2_android | [
1,
0,
0,
0
] |
18,865 | private static Attributes<Cell> attributesFrom(Node node, URI uri, ComplexCellModel cellModel, Predicate<String> attributeFilter) {
if (!node.hasAttributes()) { // ** base case **
return new OrderedMap<Cell>(0);
}
if (cellModel.isSimple()) {
log.error("CellModel '{}' does not allow attributes but the elem does", cellModel.getName());
throw new RuntimeException("Element and model attribute mismatch", new IllegalArgumentException());
}
// ** recursive case **
OrderedMap<Cell> attributes = new OrderedMap<Cell>(node.getAttributes().getLength());
NamedNodeMap elemAttributes = node.getAttributes(); // TODO: notice this is not ordered like the input ^^'
for (int i=0; i<elemAttributes.getLength(); i++) {
Node attribute = elemAttributes.item(i);
String attributeName = attribute.getNodeName();
URI childURI = cellURI(uri, cellModel, ATTRIBUTE_PREFIX+attributeName);
// if we are looking for public attributes, they need to match with the attributes model, otherwise we just
// point to the node cell model (IDEA: maybe in the future point to the internal model)
CellModel attributeCellModel = findAttributeWithName(cellModel, attributeName);
if (attributeFilter.test(attributeName)) {
Cell attributeCell = DaggerCellComponent.builder()
.withURI(childURI)
.fromNode(attribute)
.withCellModel(attributeCellModel)
.build()
.createCell();
attributes.addChild(attributeName, attributeCell);
//System.err.println("\t\ta["+i+"]:"+attributeName+":"+attributeCell.getValue());
} else {
}
}
return attributes;
} | private static Attributes<Cell> attributesFrom(Node node, URI uri, ComplexCellModel cellModel, Predicate<String> attributeFilter) {
if (!node.hasAttributes()) {
return new OrderedMap<Cell>(0);
}
if (cellModel.isSimple()) {
log.error("CellModel '{}' does not allow attributes but the elem does", cellModel.getName());
throw new RuntimeException("Element and model attribute mismatch", new IllegalArgumentException());
}
OrderedMap<Cell> attributes = new OrderedMap<Cell>(node.getAttributes().getLength());
NamedNodeMap elemAttributes = node.getAttributes();
for (int i=0; i<elemAttributes.getLength(); i++) {
Node attribute = elemAttributes.item(i);
String attributeName = attribute.getNodeName();
URI childURI = cellURI(uri, cellModel, ATTRIBUTE_PREFIX+attributeName);
CellModel attributeCellModel = findAttributeWithName(cellModel, attributeName);
if (attributeFilter.test(attributeName)) {
Cell attributeCell = DaggerCellComponent.builder()
.withURI(childURI)
.fromNode(attribute)
.withCellModel(attributeCellModel)
.build()
.createCell();
attributes.addChild(attributeName, attributeCell);
} else {
}
}
return attributes;
} | private static attributes<cell> attributesfrom(node node, uri uri, complexcellmodel cellmodel, predicate<string> attributefilter) { if (!node.hasattributes()) { return new orderedmap<cell>(0); } if (cellmodel.issimple()) { log.error("cellmodel '{}' does not allow attributes but the elem does", cellmodel.getname()); throw new runtimeexception("element and model attribute mismatch", new illegalargumentexception()); } orderedmap<cell> attributes = new orderedmap<cell>(node.getattributes().getlength()); namednodemap elemattributes = node.getattributes(); for (int i=0; i<elemattributes.getlength(); i++) { node attribute = elemattributes.item(i); string attributename = attribute.getnodename(); uri childuri = celluri(uri, cellmodel, attribute_prefix+attributename); cellmodel attributecellmodel = findattributewithname(cellmodel, attributename); if (attributefilter.test(attributename)) { cell attributecell = daggercellcomponent.builder() .withuri(childuri) .fromnode(attribute) .withcellmodel(attributecellmodel) .build() .createcell(); attributes.addchild(attributename, attributecell); } else { } } return attributes; } | danigiri/particle | [
1,
0,
0,
0
] |
2,495 | private List<AbstractCriterionWidget> createCriteriaWidgets(final ICentreDomainTreeManagerAndEnhancer centre, final Class<? extends AbstractEntity<?>> root) {
final Class<?> managedType = centre.getEnhancer().getManagedType(root);
final List<AbstractCriterionWidget> criteriaWidgets = new ArrayList<>();
for (final String critProp : centre.getFirstTick().checkedProperties(root)) {
if (!AbstractDomainTree.isPlaceholder(critProp)) {
final boolean isEntityItself = "".equals(critProp); // empty property means "entity itself"
final Class<?> propertyType = isEntityItself ? managedType : PropertyTypeDeterminator.determinePropertyType(managedType, critProp);
final AbstractCriterionWidget criterionWidget;
if (AbstractDomainTree.isCritOnlySingle(managedType, critProp)) {
if (EntityUtils.isEntityType(propertyType)) {
final List<Pair<String, Boolean>> additionalProps = dslDefaultConfig.getAdditionalPropsForAutocompleter(critProp);
criterionWidget = new EntitySingleCriterionWidget(root, managedType, critProp, additionalProps, getCentreContextConfigFor(critProp));
} else if (EntityUtils.isString(propertyType)) {
criterionWidget = new StringSingleCriterionWidget(root, managedType, critProp);
} else if (EntityUtils.isBoolean(propertyType)) {
criterionWidget = new BooleanSingleCriterionWidget(root, managedType, critProp);
} else if (Integer.class.isAssignableFrom(propertyType) || Long.class.isAssignableFrom(propertyType)) {
criterionWidget = new IntegerSingleCriterionWidget(root, managedType, critProp);
} else if (BigDecimal.class.isAssignableFrom(propertyType)) {
criterionWidget = new DecimalSingleCriterionWidget(root, managedType, critProp);
} else if (Money.class.isAssignableFrom(propertyType)) {
criterionWidget = new MoneySingleCriterionWidget(root, managedType, critProp);
} else if (EntityUtils.isDate(propertyType)) {
criterionWidget = new DateSingleCriterionWidget(root, managedType, critProp);
} else {
throw new UnsupportedOperationException(String.format("The crit-only single editor type [%s] is currently unsupported.", propertyType));
}
} else {
if (EntityUtils.isEntityType(propertyType)) {
final List<Pair<String, Boolean>> additionalProps = dslDefaultConfig.getAdditionalPropsForAutocompleter(critProp);
criterionWidget = new EntityCriterionWidget(root, managedType, critProp, additionalProps, getCentreContextConfigFor(critProp));
} else if (EntityUtils.isString(propertyType)) {
criterionWidget = new StringCriterionWidget(root, managedType, critProp);
} else if (EntityUtils.isBoolean(propertyType)) {
criterionWidget = new BooleanCriterionWidget(root, managedType, critProp);
} else if (Integer.class.isAssignableFrom(propertyType) || Long.class.isAssignableFrom(propertyType)) {
criterionWidget = new IntegerCriterionWidget(root, managedType, critProp);
} else if (BigDecimal.class.isAssignableFrom(propertyType)) { // TODO do not forget about Money later (after Money widget will be available)
criterionWidget = new DecimalCriterionWidget(root, managedType, critProp);
} else if (Money.class.isAssignableFrom(propertyType)) {
criterionWidget = new MoneyCriterionWidget(root, managedType, critProp);
} else if (EntityUtils.isDate(propertyType)) {
criterionWidget = new DateCriterionWidget(root, managedType, critProp);
} else {
throw new UnsupportedOperationException(String.format("The multi / range editor type [%s] is currently unsupported.", propertyType));
}
}
criteriaWidgets.add(criterionWidget);
}
}
return criteriaWidgets;
} | private List<AbstractCriterionWidget> createCriteriaWidgets(final ICentreDomainTreeManagerAndEnhancer centre, final Class<? extends AbstractEntity<?>> root) {
final Class<?> managedType = centre.getEnhancer().getManagedType(root);
final List<AbstractCriterionWidget> criteriaWidgets = new ArrayList<>();
for (final String critProp : centre.getFirstTick().checkedProperties(root)) {
if (!AbstractDomainTree.isPlaceholder(critProp)) {
final boolean isEntityItself = "".equals(critProp);
final Class<?> propertyType = isEntityItself ? managedType : PropertyTypeDeterminator.determinePropertyType(managedType, critProp);
final AbstractCriterionWidget criterionWidget;
if (AbstractDomainTree.isCritOnlySingle(managedType, critProp)) {
if (EntityUtils.isEntityType(propertyType)) {
final List<Pair<String, Boolean>> additionalProps = dslDefaultConfig.getAdditionalPropsForAutocompleter(critProp);
criterionWidget = new EntitySingleCriterionWidget(root, managedType, critProp, additionalProps, getCentreContextConfigFor(critProp));
} else if (EntityUtils.isString(propertyType)) {
criterionWidget = new StringSingleCriterionWidget(root, managedType, critProp);
} else if (EntityUtils.isBoolean(propertyType)) {
criterionWidget = new BooleanSingleCriterionWidget(root, managedType, critProp);
} else if (Integer.class.isAssignableFrom(propertyType) || Long.class.isAssignableFrom(propertyType)) {
criterionWidget = new IntegerSingleCriterionWidget(root, managedType, critProp);
} else if (BigDecimal.class.isAssignableFrom(propertyType)) {
criterionWidget = new DecimalSingleCriterionWidget(root, managedType, critProp);
} else if (Money.class.isAssignableFrom(propertyType)) {
criterionWidget = new MoneySingleCriterionWidget(root, managedType, critProp);
} else if (EntityUtils.isDate(propertyType)) {
criterionWidget = new DateSingleCriterionWidget(root, managedType, critProp);
} else {
throw new UnsupportedOperationException(String.format("The crit-only single editor type [%s] is currently unsupported.", propertyType));
}
} else {
if (EntityUtils.isEntityType(propertyType)) {
final List<Pair<String, Boolean>> additionalProps = dslDefaultConfig.getAdditionalPropsForAutocompleter(critProp);
criterionWidget = new EntityCriterionWidget(root, managedType, critProp, additionalProps, getCentreContextConfigFor(critProp));
} else if (EntityUtils.isString(propertyType)) {
criterionWidget = new StringCriterionWidget(root, managedType, critProp);
} else if (EntityUtils.isBoolean(propertyType)) {
criterionWidget = new BooleanCriterionWidget(root, managedType, critProp);
} else if (Integer.class.isAssignableFrom(propertyType) || Long.class.isAssignableFrom(propertyType)) {
criterionWidget = new IntegerCriterionWidget(root, managedType, critProp);
} else if (BigDecimal.class.isAssignableFrom(propertyType)) {
criterionWidget = new DecimalCriterionWidget(root, managedType, critProp);
} else if (Money.class.isAssignableFrom(propertyType)) {
criterionWidget = new MoneyCriterionWidget(root, managedType, critProp);
} else if (EntityUtils.isDate(propertyType)) {
criterionWidget = new DateCriterionWidget(root, managedType, critProp);
} else {
throw new UnsupportedOperationException(String.format("The multi / range editor type [%s] is currently unsupported.", propertyType));
}
}
criteriaWidgets.add(criterionWidget);
}
}
return criteriaWidgets;
} | private list<abstractcriterionwidget> createcriteriawidgets(final icentredomaintreemanagerandenhancer centre, final class<? extends abstractentity<?>> root) { final class<?> managedtype = centre.getenhancer().getmanagedtype(root); final list<abstractcriterionwidget> criteriawidgets = new arraylist<>(); for (final string critprop : centre.getfirsttick().checkedproperties(root)) { if (!abstractdomaintree.isplaceholder(critprop)) { final boolean isentityitself = "".equals(critprop); final class<?> propertytype = isentityitself ? managedtype : propertytypedeterminator.determinepropertytype(managedtype, critprop); final abstractcriterionwidget criterionwidget; if (abstractdomaintree.iscritonlysingle(managedtype, critprop)) { if (entityutils.isentitytype(propertytype)) { final list<pair<string, boolean>> additionalprops = dsldefaultconfig.getadditionalpropsforautocompleter(critprop); criterionwidget = new entitysinglecriterionwidget(root, managedtype, critprop, additionalprops, getcentrecontextconfigfor(critprop)); } else if (entityutils.isstring(propertytype)) { criterionwidget = new stringsinglecriterionwidget(root, managedtype, critprop); } else if (entityutils.isboolean(propertytype)) { criterionwidget = new booleansinglecriterionwidget(root, managedtype, critprop); } else if (integer.class.isassignablefrom(propertytype) || long.class.isassignablefrom(propertytype)) { criterionwidget = new integersinglecriterionwidget(root, managedtype, critprop); } else if (bigdecimal.class.isassignablefrom(propertytype)) { criterionwidget = new decimalsinglecriterionwidget(root, managedtype, critprop); } else if (money.class.isassignablefrom(propertytype)) { criterionwidget = new moneysinglecriterionwidget(root, managedtype, critprop); } else if (entityutils.isdate(propertytype)) { criterionwidget = new datesinglecriterionwidget(root, managedtype, critprop); } else { throw new unsupportedoperationexception(string.format("the crit-only single editor type [%s] is currently unsupported.", propertytype)); } } else { if (entityutils.isentitytype(propertytype)) { final list<pair<string, boolean>> additionalprops = dsldefaultconfig.getadditionalpropsforautocompleter(critprop); criterionwidget = new entitycriterionwidget(root, managedtype, critprop, additionalprops, getcentrecontextconfigfor(critprop)); } else if (entityutils.isstring(propertytype)) { criterionwidget = new stringcriterionwidget(root, managedtype, critprop); } else if (entityutils.isboolean(propertytype)) { criterionwidget = new booleancriterionwidget(root, managedtype, critprop); } else if (integer.class.isassignablefrom(propertytype) || long.class.isassignablefrom(propertytype)) { criterionwidget = new integercriterionwidget(root, managedtype, critprop); } else if (bigdecimal.class.isassignablefrom(propertytype)) { criterionwidget = new decimalcriterionwidget(root, managedtype, critprop); } else if (money.class.isassignablefrom(propertytype)) { criterionwidget = new moneycriterionwidget(root, managedtype, critprop); } else if (entityutils.isdate(propertytype)) { criterionwidget = new datecriterionwidget(root, managedtype, critprop); } else { throw new unsupportedoperationexception(string.format("the multi / range editor type [%s] is currently unsupported.", propertytype)); } } criteriawidgets.add(criterionwidget); } } return criteriawidgets; } | fieldenms/ | [
1,
0,
0,
0
] |
2,538 | private void initializeFop2x(XProcRuntime runtime, XStep step, Properties options) {
Object fopFactoryBuilder = null;
Constructor factBuilderConstructor = null;
try {
factBuilderConstructor = klass.getConstructor(URI.class);
} catch (NoSuchMethodException nsme) {
// nop;
}
resolver = runtime.getResolver();
URI baseURI = step.getStep().getNode().getBaseURI();
String s = getStringProp("BaseURL");
if (s != null) {
baseURI = baseURI.resolve(s);
}
try {
if (resolver == null) {
fopFactoryBuilder = factBuilderConstructor.newInstance(baseURI);
} else {
// FIXME: make an org.apache.xmlgraphics.io.ResourceResolver resolver!?
fopFactoryBuilder = factBuilderConstructor.newInstance(baseURI);
}
Class fclass = fopFactoryBuilder.getClass();
// FIXME: make this configurable
Boolean b = false;
/* Why doesn't this call work with reflection?
method = fclass.getMethod("setStrictFOValidation", Boolean.class);
method.invoke(fopFactoryBuilder, b);
*/
b = getBooleanProp("BreakIndentInheritanceOnReferenceAreaBoundary");
if (b != null) {
method = fclass.getMethod("setBreakIndentInheritanceOnReferenceAreaBoundary", Boolean.class);
method.invoke(fopFactoryBuilder, b);
}
Float f = getFloatProp("SourceResolution");
if (f != null) {
method = fclass.getMethod("setSourceResolution", Float.class);
method.invoke(fopFactoryBuilder, f);
}
/* FIXME:
s = getStringProp("FontBaseURL");
if (s != null) {
fopFactory.getFontManager().setFontBaseURL(s);
}
*/
b = getBooleanProp("Base14KerningEnabled");
if (b != null) {
Method getFontManager = fclass.getMethod("getFontManager");
Object fontManager = getFontManager.invoke(fopFactoryBuilder);
method = fontManager.getClass().getMethod("setBase14KerningEnabled", Boolean.class);
method.invoke(fontManager, b);
}
/* FIXME:
s = getStringProp("HyphenBaseURL");
if (s != null) {
fopFactory.setHyphenBaseURL(s);
}
*/
s = getStringProp("PageHeight");
if (s != null) {
method = fclass.getMethod("setPageHeight", String.class);
method.invoke(fopFactoryBuilder, s);
}
s = getStringProp("PageWidth");
if (s != null) {
method = fclass.getMethod("setPageWidth", String.class);
method.invoke(fopFactoryBuilder, s);
}
f = getFloatProp("TargetResolution");
if (f != null) {
method = fclass.getMethod("setTargetResolution", Float.class);
method.invoke(fopFactoryBuilder, f);
}
b = getBooleanProp("StrictUserConfigValidation");
if (b != null) {
method = fclass.getMethod("setStrictUserConfigValidation", Boolean.class);
method.invoke(fopFactoryBuilder, b);
}
b = getBooleanProp("StrictValidation");
if (b != null) {
method = fclass.getMethod("setStrictUserConfigValidation", Boolean.class);
method.invoke(fopFactoryBuilder, b);
}
b = getBooleanProp("UseCache");
if (b != null && !b) {
Method getFontManager = fclass.getMethod("getFontManager");
Object fontManager = getFontManager.invoke(fopFactoryBuilder);
method = fontManager.getClass().getMethod("disableFontCache");
method.invoke(fontManager);
}
/* FIXME:
s = getStringProp("UserConfig");
if (s != null) {
fopFactory.setUserConfig(s);
}
*/
method = fclass.getMethod("build");
fopFactory = method.invoke(fopFactoryBuilder);
} catch (Exception e) {
throw new XProcException(e);
}
} | private void initializeFop2x(XProcRuntime runtime, XStep step, Properties options) {
Object fopFactoryBuilder = null;
Constructor factBuilderConstructor = null;
try {
factBuilderConstructor = klass.getConstructor(URI.class);
} catch (NoSuchMethodException nsme) {
}
resolver = runtime.getResolver();
URI baseURI = step.getStep().getNode().getBaseURI();
String s = getStringProp("BaseURL");
if (s != null) {
baseURI = baseURI.resolve(s);
}
try {
if (resolver == null) {
fopFactoryBuilder = factBuilderConstructor.newInstance(baseURI);
} else {
fopFactoryBuilder = factBuilderConstructor.newInstance(baseURI);
}
Class fclass = fopFactoryBuilder.getClass();
Boolean b = false;
b = getBooleanProp("BreakIndentInheritanceOnReferenceAreaBoundary");
if (b != null) {
method = fclass.getMethod("setBreakIndentInheritanceOnReferenceAreaBoundary", Boolean.class);
method.invoke(fopFactoryBuilder, b);
}
Float f = getFloatProp("SourceResolution");
if (f != null) {
method = fclass.getMethod("setSourceResolution", Float.class);
method.invoke(fopFactoryBuilder, f);
}
b = getBooleanProp("Base14KerningEnabled");
if (b != null) {
Method getFontManager = fclass.getMethod("getFontManager");
Object fontManager = getFontManager.invoke(fopFactoryBuilder);
method = fontManager.getClass().getMethod("setBase14KerningEnabled", Boolean.class);
method.invoke(fontManager, b);
}
s = getStringProp("PageHeight");
if (s != null) {
method = fclass.getMethod("setPageHeight", String.class);
method.invoke(fopFactoryBuilder, s);
}
s = getStringProp("PageWidth");
if (s != null) {
method = fclass.getMethod("setPageWidth", String.class);
method.invoke(fopFactoryBuilder, s);
}
f = getFloatProp("TargetResolution");
if (f != null) {
method = fclass.getMethod("setTargetResolution", Float.class);
method.invoke(fopFactoryBuilder, f);
}
b = getBooleanProp("StrictUserConfigValidation");
if (b != null) {
method = fclass.getMethod("setStrictUserConfigValidation", Boolean.class);
method.invoke(fopFactoryBuilder, b);
}
b = getBooleanProp("StrictValidation");
if (b != null) {
method = fclass.getMethod("setStrictUserConfigValidation", Boolean.class);
method.invoke(fopFactoryBuilder, b);
}
b = getBooleanProp("UseCache");
if (b != null && !b) {
Method getFontManager = fclass.getMethod("getFontManager");
Object fontManager = getFontManager.invoke(fopFactoryBuilder);
method = fontManager.getClass().getMethod("disableFontCache");
method.invoke(fontManager);
}
method = fclass.getMethod("build");
fopFactory = method.invoke(fopFactoryBuilder);
} catch (Exception e) {
throw new XProcException(e);
}
} | private void initializefop2x(xprocruntime runtime, xstep step, properties options) { object fopfactorybuilder = null; constructor factbuilderconstructor = null; try { factbuilderconstructor = klass.getconstructor(uri.class); } catch (nosuchmethodexception nsme) { } resolver = runtime.getresolver(); uri baseuri = step.getstep().getnode().getbaseuri(); string s = getstringprop("baseurl"); if (s != null) { baseuri = baseuri.resolve(s); } try { if (resolver == null) { fopfactorybuilder = factbuilderconstructor.newinstance(baseuri); } else { fopfactorybuilder = factbuilderconstructor.newinstance(baseuri); } class fclass = fopfactorybuilder.getclass(); boolean b = false; b = getbooleanprop("breakindentinheritanceonreferenceareaboundary"); if (b != null) { method = fclass.getmethod("setbreakindentinheritanceonreferenceareaboundary", boolean.class); method.invoke(fopfactorybuilder, b); } float f = getfloatprop("sourceresolution"); if (f != null) { method = fclass.getmethod("setsourceresolution", float.class); method.invoke(fopfactorybuilder, f); } b = getbooleanprop("base14kerningenabled"); if (b != null) { method getfontmanager = fclass.getmethod("getfontmanager"); object fontmanager = getfontmanager.invoke(fopfactorybuilder); method = fontmanager.getclass().getmethod("setbase14kerningenabled", boolean.class); method.invoke(fontmanager, b); } s = getstringprop("pageheight"); if (s != null) { method = fclass.getmethod("setpageheight", string.class); method.invoke(fopfactorybuilder, s); } s = getstringprop("pagewidth"); if (s != null) { method = fclass.getmethod("setpagewidth", string.class); method.invoke(fopfactorybuilder, s); } f = getfloatprop("targetresolution"); if (f != null) { method = fclass.getmethod("settargetresolution", float.class); method.invoke(fopfactorybuilder, f); } b = getbooleanprop("strictuserconfigvalidation"); if (b != null) { method = fclass.getmethod("setstrictuserconfigvalidation", boolean.class); method.invoke(fopfactorybuilder, b); } b = getbooleanprop("strictvalidation"); if (b != null) { method = fclass.getmethod("setstrictuserconfigvalidation", boolean.class); method.invoke(fopfactorybuilder, b); } b = getbooleanprop("usecache"); if (b != null && !b) { method getfontmanager = fclass.getmethod("getfontmanager"); object fontmanager = getfontmanager.invoke(fopfactorybuilder); method = fontmanager.getclass().getmethod("disablefontcache"); method.invoke(fontmanager); } method = fclass.getmethod("build"); fopfactory = method.invoke(fopfactorybuilder); } catch (exception e) { throw new xprocexception(e); } } | fsasaki/xmlcalabash1-print | [
0,
0,
1,
0
] |
2,539 | public void format(XdmNode doc, OutputStream out, String contentType) {
String outputFormat = null;
if (contentType == null || "application/pdf".equalsIgnoreCase(contentType)) {
outputFormat = "application/pdf"; // "PDF";
} else if ("application/PostScript".equalsIgnoreCase(contentType)) {
outputFormat = "application/postscript"; //"PostScript";
} else if ("application/afp".equalsIgnoreCase(contentType)) {
outputFormat = "application/x-afp"; //"AFP";
} else if ("application/rtf".equalsIgnoreCase(contentType)) {
outputFormat = "application/rtf";
} else if ("text/plain".equalsIgnoreCase(contentType)) {
outputFormat = "text/plain";
} else {
throw new XProcException(step.getNode(), "Unsupported content-type on p:xsl-formatter: " + contentType);
}
if (! ("1.x".equals(fopVersion) || "2.x".equals(fopVersion))) {
throw new XProcException("Unexpected FOP version: " + fopVersion);
}
try {
InputSource fodoc = S9apiUtils.xdmToInputSource(runtime, doc);
SAXSource source = new SAXSource(fodoc);
Object userAgent = null;
Object fop = null;
if ("1.x".equals(fopVersion)) {
method = fopFactory.getClass().getMethod("newFop", String.class, OutputStream.class);
fop = method.invoke(fopFactory, outputFormat, out);
method = fop.getClass().getMethod("getUserAgent");
userAgent = method.invoke(fop);
} else {
method = fopFactory.getClass().getMethod("newFOUserAgent");
userAgent = method.invoke(fopFactory);
}
Class uaClass = userAgent.getClass();
Boolean b = getBooleanProp("Accessibility");
if (b != null) {
method = uaClass.getMethod("setAccessibility", Boolean.class);
method.invoke(userAgent, b);
}
String s = getStringProp("Author");
if (s != null) {
method = uaClass.getMethod("setAuthor", String.class);
method.invoke(userAgent, s);
}
if ("1.x".equals(fopVersion)) {
method = uaClass.getMethod("setBaseURL", String.class);
method.invoke(userAgent, step.getNode().getBaseURI().toString());
s = getStringProp("BaseURL");
if (s != null) {
method.invoke(userAgent, s);
}
} else {
// FIXME: how do I do this in 2.x?
}
b = getBooleanProp("ConserveMemoryPolicy");
if (b != null) {
method = uaClass.getMethod("setConserveMemoryPolicy", Boolean.class);
method.invoke(userAgent, b);
}
s = getStringProp("CreationDate");
if (s != null) {
DateFormat df = DateFormat.getDateInstance();
Date d = df.parse(s);
method = uaClass.getMethod("setCreationDate", Date.class);
method.invoke(userAgent, d);
}
s = getStringProp("Creator");
if (s != null) {
method = uaClass.getMethod("setCreator", String.class);
method.invoke(userAgent, s);
}
s = getStringProp("Keywords");
if (s != null) {
method = uaClass.getMethod("setKeywords", String.class);
method.invoke(userAgent, s);
}
b = getBooleanProp("LocatorEnabled");
if (b != null) {
method = uaClass.getMethod("setLocatorEnabled", Boolean.class);
method.invoke(userAgent, b);
}
s = getStringProp("Producer");
if (s != null) {
method = uaClass.getMethod("setProducer", String.class);
method.invoke(userAgent, s);
}
s = getStringProp("Subject");
if (s != null) {
method = uaClass.getMethod("setSubject", String.class);
method.invoke(userAgent, s);
}
Float f = getFloatProp("TargetResolution");
if (f != null) {
method = uaClass.getMethod("setTargetResolution", Float.class);
method.invoke(userAgent, f);
}
s = getStringProp("Title");
if (s != null) {
method = uaClass.getMethod("setTitle", String.class);
method.invoke(userAgent, s);
}
if ("2.x".equals(fopVersion)) {
method = uaClass.getMethod("newFop", String.class, OutputStream.class);
fop = method.invoke(userAgent, outputFormat, out);
}
method = fop.getClass().getMethod("getDefaultHandler");
Object defHandler = method.invoke(fop);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(source, new SAXResult((ContentHandler) defHandler));
} catch (Exception e) {
throw new XProcException(step.getNode(), "Failed to process FO document with FOP", e);
}
} | public void format(XdmNode doc, OutputStream out, String contentType) {
String outputFormat = null;
if (contentType == null || "application/pdf".equalsIgnoreCase(contentType)) {
outputFormat = "application/pdf";
} else if ("application/PostScript".equalsIgnoreCase(contentType)) {
outputFormat = "application/postscript";
} else if ("application/afp".equalsIgnoreCase(contentType)) {
outputFormat = "application/x-afp";
} else if ("application/rtf".equalsIgnoreCase(contentType)) {
outputFormat = "application/rtf";
} else if ("text/plain".equalsIgnoreCase(contentType)) {
outputFormat = "text/plain";
} else {
throw new XProcException(step.getNode(), "Unsupported content-type on p:xsl-formatter: " + contentType);
}
if (! ("1.x".equals(fopVersion) || "2.x".equals(fopVersion))) {
throw new XProcException("Unexpected FOP version: " + fopVersion);
}
try {
InputSource fodoc = S9apiUtils.xdmToInputSource(runtime, doc);
SAXSource source = new SAXSource(fodoc);
Object userAgent = null;
Object fop = null;
if ("1.x".equals(fopVersion)) {
method = fopFactory.getClass().getMethod("newFop", String.class, OutputStream.class);
fop = method.invoke(fopFactory, outputFormat, out);
method = fop.getClass().getMethod("getUserAgent");
userAgent = method.invoke(fop);
} else {
method = fopFactory.getClass().getMethod("newFOUserAgent");
userAgent = method.invoke(fopFactory);
}
Class uaClass = userAgent.getClass();
Boolean b = getBooleanProp("Accessibility");
if (b != null) {
method = uaClass.getMethod("setAccessibility", Boolean.class);
method.invoke(userAgent, b);
}
String s = getStringProp("Author");
if (s != null) {
method = uaClass.getMethod("setAuthor", String.class);
method.invoke(userAgent, s);
}
if ("1.x".equals(fopVersion)) {
method = uaClass.getMethod("setBaseURL", String.class);
method.invoke(userAgent, step.getNode().getBaseURI().toString());
s = getStringProp("BaseURL");
if (s != null) {
method.invoke(userAgent, s);
}
} else {
}
b = getBooleanProp("ConserveMemoryPolicy");
if (b != null) {
method = uaClass.getMethod("setConserveMemoryPolicy", Boolean.class);
method.invoke(userAgent, b);
}
s = getStringProp("CreationDate");
if (s != null) {
DateFormat df = DateFormat.getDateInstance();
Date d = df.parse(s);
method = uaClass.getMethod("setCreationDate", Date.class);
method.invoke(userAgent, d);
}
s = getStringProp("Creator");
if (s != null) {
method = uaClass.getMethod("setCreator", String.class);
method.invoke(userAgent, s);
}
s = getStringProp("Keywords");
if (s != null) {
method = uaClass.getMethod("setKeywords", String.class);
method.invoke(userAgent, s);
}
b = getBooleanProp("LocatorEnabled");
if (b != null) {
method = uaClass.getMethod("setLocatorEnabled", Boolean.class);
method.invoke(userAgent, b);
}
s = getStringProp("Producer");
if (s != null) {
method = uaClass.getMethod("setProducer", String.class);
method.invoke(userAgent, s);
}
s = getStringProp("Subject");
if (s != null) {
method = uaClass.getMethod("setSubject", String.class);
method.invoke(userAgent, s);
}
Float f = getFloatProp("TargetResolution");
if (f != null) {
method = uaClass.getMethod("setTargetResolution", Float.class);
method.invoke(userAgent, f);
}
s = getStringProp("Title");
if (s != null) {
method = uaClass.getMethod("setTitle", String.class);
method.invoke(userAgent, s);
}
if ("2.x".equals(fopVersion)) {
method = uaClass.getMethod("newFop", String.class, OutputStream.class);
fop = method.invoke(userAgent, outputFormat, out);
}
method = fop.getClass().getMethod("getDefaultHandler");
Object defHandler = method.invoke(fop);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(source, new SAXResult((ContentHandler) defHandler));
} catch (Exception e) {
throw new XProcException(step.getNode(), "Failed to process FO document with FOP", e);
}
} | public void format(xdmnode doc, outputstream out, string contenttype) { string outputformat = null; if (contenttype == null || "application/pdf".equalsignorecase(contenttype)) { outputformat = "application/pdf"; } else if ("application/postscript".equalsignorecase(contenttype)) { outputformat = "application/postscript"; } else if ("application/afp".equalsignorecase(contenttype)) { outputformat = "application/x-afp"; } else if ("application/rtf".equalsignorecase(contenttype)) { outputformat = "application/rtf"; } else if ("text/plain".equalsignorecase(contenttype)) { outputformat = "text/plain"; } else { throw new xprocexception(step.getnode(), "unsupported content-type on p:xsl-formatter: " + contenttype); } if (! ("1.x".equals(fopversion) || "2.x".equals(fopversion))) { throw new xprocexception("unexpected fop version: " + fopversion); } try { inputsource fodoc = s9apiutils.xdmtoinputsource(runtime, doc); saxsource source = new saxsource(fodoc); object useragent = null; object fop = null; if ("1.x".equals(fopversion)) { method = fopfactory.getclass().getmethod("newfop", string.class, outputstream.class); fop = method.invoke(fopfactory, outputformat, out); method = fop.getclass().getmethod("getuseragent"); useragent = method.invoke(fop); } else { method = fopfactory.getclass().getmethod("newfouseragent"); useragent = method.invoke(fopfactory); } class uaclass = useragent.getclass(); boolean b = getbooleanprop("accessibility"); if (b != null) { method = uaclass.getmethod("setaccessibility", boolean.class); method.invoke(useragent, b); } string s = getstringprop("author"); if (s != null) { method = uaclass.getmethod("setauthor", string.class); method.invoke(useragent, s); } if ("1.x".equals(fopversion)) { method = uaclass.getmethod("setbaseurl", string.class); method.invoke(useragent, step.getnode().getbaseuri().tostring()); s = getstringprop("baseurl"); if (s != null) { method.invoke(useragent, s); } } else { } b = getbooleanprop("conservememorypolicy"); if (b != null) { method = uaclass.getmethod("setconservememorypolicy", boolean.class); method.invoke(useragent, b); } s = getstringprop("creationdate"); if (s != null) { dateformat df = dateformat.getdateinstance(); date d = df.parse(s); method = uaclass.getmethod("setcreationdate", date.class); method.invoke(useragent, d); } s = getstringprop("creator"); if (s != null) { method = uaclass.getmethod("setcreator", string.class); method.invoke(useragent, s); } s = getstringprop("keywords"); if (s != null) { method = uaclass.getmethod("setkeywords", string.class); method.invoke(useragent, s); } b = getbooleanprop("locatorenabled"); if (b != null) { method = uaclass.getmethod("setlocatorenabled", boolean.class); method.invoke(useragent, b); } s = getstringprop("producer"); if (s != null) { method = uaclass.getmethod("setproducer", string.class); method.invoke(useragent, s); } s = getstringprop("subject"); if (s != null) { method = uaclass.getmethod("setsubject", string.class); method.invoke(useragent, s); } float f = getfloatprop("targetresolution"); if (f != null) { method = uaclass.getmethod("settargetresolution", float.class); method.invoke(useragent, f); } s = getstringprop("title"); if (s != null) { method = uaclass.getmethod("settitle", string.class); method.invoke(useragent, s); } if ("2.x".equals(fopversion)) { method = uaclass.getmethod("newfop", string.class, outputstream.class); fop = method.invoke(useragent, outputformat, out); } method = fop.getclass().getmethod("getdefaulthandler"); object defhandler = method.invoke(fop); transformerfactory transformerfactory = transformerfactory.newinstance(); transformer transformer = transformerfactory.newtransformer(); transformer.transform(source, new saxresult((contenthandler) defhandler)); } catch (exception e) { throw new xprocexception(step.getnode(), "failed to process fo document with fop", e); } } | fsasaki/xmlcalabash1-print | [
0,
0,
1,
0
] |
10,831 | @Override
@SuppressLint("SetJavaScriptEnabled")
protected void onCreate(@Nullable Bundle savedInstanceState) {
Dank.dependencyInjector().inject(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
findAndSetupToolbar();
toolbar.setBackground(null);
toolbar.setTitle(R.string.login);
contentViewGroup.setClipToOutline(true);
// Setup WebView.
CookieManager.getInstance().removeAllCookies(null);
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (!loggedIn) {
boolean shouldShowProgress = newProgress < 75;
setProgressVisible(shouldShowProgress);
}
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (url.contains("code=")) {
// We've detected the redirect URL.
webView.stopLoading();
loggedIn = true;
handleOnPermissionGranted(url);
} else if (url.contains("error=")) {
Toast.makeText(LoginActivity.this, R.string.login_error_oauth_permission_rejected, Toast.LENGTH_LONG).show();
webView.stopLoading();
setResult(RESULT_CANCELED);
finish();
}
}
});
// Bug workaround: WebView crashes when dropdown is shown on
// a Nougat emulator. Haven't tested on other devices.
webView.clearFormData();
webView.getSettings().setSaveFormData(false);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
userLoginHelper = reddit.get().login().loginHelper();
webView.loadUrl(userLoginHelper.authorizationUrl());
} | @Override
@SuppressLint("SetJavaScriptEnabled")
protected void onCreate(@Nullable Bundle savedInstanceState) {
Dank.dependencyInjector().inject(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
findAndSetupToolbar();
toolbar.setBackground(null);
toolbar.setTitle(R.string.login);
contentViewGroup.setClipToOutline(true);
CookieManager.getInstance().removeAllCookies(null);
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (!loggedIn) {
boolean shouldShowProgress = newProgress < 75;
setProgressVisible(shouldShowProgress);
}
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (url.contains("code=")) {
webView.stopLoading();
loggedIn = true;
handleOnPermissionGranted(url);
} else if (url.contains("error=")) {
Toast.makeText(LoginActivity.this, R.string.login_error_oauth_permission_rejected, Toast.LENGTH_LONG).show();
webView.stopLoading();
setResult(RESULT_CANCELED);
finish();
}
}
});
webView.clearFormData();
webView.getSettings().setSaveFormData(false);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
userLoginHelper = reddit.get().login().loginHelper();
webView.loadUrl(userLoginHelper.authorizationUrl());
} | @override @suppresslint("setjavascriptenabled") protected void oncreate(@nullable bundle savedinstancestate) { dank.dependencyinjector().inject(this); super.oncreate(savedinstancestate); setcontentview(r.layout.activity_login); butterknife.bind(this); findandsetuptoolbar(); toolbar.setbackground(null); toolbar.settitle(r.string.login); contentviewgroup.setcliptooutline(true); cookiemanager.getinstance().removeallcookies(null); webview.setwebchromeclient(new webchromeclient() { @override public void onprogresschanged(webview view, int newprogress) { if (!loggedin) { boolean shouldshowprogress = newprogress < 75; setprogressvisible(shouldshowprogress); } } }); webview.setwebviewclient(new webviewclient() { @override public void onpagestarted(webview view, string url, bitmap favicon) { if (url.contains("code=")) { webview.stoploading(); loggedin = true; handleonpermissiongranted(url); } else if (url.contains("error=")) { toast.maketext(loginactivity.this, r.string.login_error_oauth_permission_rejected, toast.length_long).show(); webview.stoploading(); setresult(result_canceled); finish(); } } }); webview.clearformdata(); webview.getsettings().setsaveformdata(false); webview.getsettings().setjavascriptenabled(true); webview.getsettings().setdomstorageenabled(true); userloginhelper = reddit.get().login().loginhelper(); webview.loadurl(userloginhelper.authorizationurl()); } | federa7675/Dawn | [
0,
0,
1,
0
] |
2,698 | private static void setChipVersion() {
//TODO: Get chip version directly if possible.
String model = IrisHal.getModel();
if (Model.isV2(model)) {
hardware.set("ZM5304AU-CME3R");
}
else if (Model.isV3(model)) {
hardware.set("ZM5101");
}
else {
hardware.set("unknown");
}
} | private static void setChipVersion() {
String model = IrisHal.getModel();
if (Model.isV2(model)) {
hardware.set("ZM5304AU-CME3R");
}
else if (Model.isV3(model)) {
hardware.set("ZM5101");
}
else {
hardware.set("unknown");
}
} | private static void setchipversion() { string model = irishal.getmodel(); if (model.isv2(model)) { hardware.set("zm5304au-cme3r"); } else if (model.isv3(model)) { hardware.set("zm5101"); } else { hardware.set("unknown"); } } | eanderso/arcusplatform | [
1,
0,
0,
0
] |
19,228 | @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_MENU) && (null == getSupportActionBar())) {
// This is to fix a bug in the v7 support lib. If there is no options menu and you hit MENU, it will crash with a
// NPE @ android.support.v7.app.ActionBarImplICS.getThemedContext(ActionBarImplICS.java:274)
// This can safely be removed if we add in menu options on this screen
return true;
}
return super.onKeyDown(keyCode, event);
} | @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_MENU) && (null == getSupportActionBar())) {
return true;
}
return super.onKeyDown(keyCode, event);
} | @override public boolean onkeydown(int keycode, keyevent event) { if ((keycode == keyevent.keycode_menu) && (null == getsupportactionbar())) { return true; } return super.onkeydown(keycode, event); } | developers16/GithubsSample | [
1,
0,
0,
0
] |
19,294 | public FFprobe setShowProgramVersion(final boolean showProgramVersion) {
this.showProgramVersion = showProgramVersion;
return this;
} | public FFprobe setShowProgramVersion(final boolean showProgramVersion) {
this.showProgramVersion = showProgramVersion;
return this;
} | public ffprobe setshowprogramversion(final boolean showprogramversion) { this.showprogramversion = showprogramversion; return this; } | entropycoder/Jaffree | [
0,
1,
0,
0
] |
19,297 | public FFprobe setShowPixelFormats(final boolean showPixelFormats) {
this.showPixelFormats = showPixelFormats;
return this;
} | public FFprobe setShowPixelFormats(final boolean showPixelFormats) {
this.showPixelFormats = showPixelFormats;
return this;
} | public ffprobe setshowpixelformats(final boolean showpixelformats) { this.showpixelformats = showpixelformats; return this; } | entropycoder/Jaffree | [
0,
1,
0,
0
] |
19,398 | private void label_iconRealizarPedidoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_label_iconRealizarPedidoMouseClicked
// TODO add your handling code here:
//instanciar a tela cad pessoa apenas uma vez
tela_realizarPedido= new Realizar_Pedido(this.conta);
tela_realizarPedido.setVisible(true);
tela_realizarPedido.setLocationRelativeTo(null);
} | private void label_iconRealizarPedidoMouseClicked(java.awt.event.MouseEvent evt) {
tela_realizarPedido= new Realizar_Pedido(this.conta);
tela_realizarPedido.setVisible(true);
tela_realizarPedido.setLocationRelativeTo(null);
} | private void label_iconrealizarpedidomouseclicked(java.awt.event.mouseevent evt) { tela_realizarpedido= new realizar_pedido(this.conta); tela_realizarpedido.setvisible(true); tela_realizarpedido.setlocationrelativeto(null); } | fsilva-c/Screens_LP2 | [
0,
1,
0,
0
] |
19,831 | public Expression getObject() {
return fObject;
} | public Expression getObject() {
return fObject;
} | public expression getobject() { return fobject; } | duarterafael/Conformitate | [
0,
1,
0,
0
] |
19,832 | public MAttribute getAttribute() {
return fAttribute;
} | public MAttribute getAttribute() {
return fAttribute;
} | public mattribute getattribute() { return fattribute; } | duarterafael/Conformitate | [
0,
1,
0,
0
] |
19,833 | public MRValue getRValue() {
return fRValue;
} | public MRValue getRValue() {
return fRValue;
} | public mrvalue getrvalue() { return frvalue; } | duarterafael/Conformitate | [
0,
1,
0,
0
] |
19,851 | public String getTagitLayoutPath() {
String res = "content/none.xhtml";
//if explorer is in createMode
switch( explorerAction.getMode() ) {
case CREATE_LOCATION:
res = "content_new/location_new.xhtml";
if( newLocationAction.getMode() == -1 ) {
newLocationAction.begin();
}
break;
case CREATE_ROUTE:
res = "content_new/route_new.xhtml";
if( newRouteAction.getMode() != 2 ) {
newRouteAction.setMode(2);
}
break;
default:
//there must be a ranking because everything that is displayable on tagit
//is a PointOfInetrest but maybe also another type (like a route)
//until then we break, when contentItem has topType (like route)
//init with none
for( KiWiResource type : currentContentItem.getTypes() ) {
String seRQLID = type.getSeRQLID();
if(seRQLID.contains(Constants.NS_FCP_CORE+"Location")) {
res = "content/location.xhtml";
locationAction.begin();
break;
} else if(seRQLID.contains(Constants.NS_KIWI_CORE+"BlogPost")) {
//TODO should be a specific Blog interface
res = "content/blog.xhtml";
newsItemAction.begin();
break;
} else if(seRQLID.contains(Constants.NS_FCP_CORE+"NewsItem")) {
res = "content/newsItem.xhtml";
newsItemAction.begin();
break;
} else if(seRQLID.contains(Constants.NS_TAGIT + "Route")) {
//TODO CHANGE!!!
res = "content/route.xhtml";
//res = "content/photoroute.xhtml";
routeAction.begin();
break;
} else if(seRQLID.contains(Constants.NS_KIWI_CORE + "User")) {
//if( currentUser.getContentItem().getId() == currentContentItem.getId() ) {
// res = "content/user.xhtml";
// personAction.begin();
// break;
//} else {
res = "content/person.xhtml";
personAction.begin();
break;
//}
} else if(seRQLID.contains(Constants.NS_DEMO+"LocatedMeeting")) {
res = "content/location.xhtml";
locationAction.begin();
break;
}
}
//TODO some common type for all pois
}
log.info("set layout to #0",res);
return res;
} | public String getTagitLayoutPath() {
String res = "content/none.xhtml";
switch( explorerAction.getMode() ) {
case CREATE_LOCATION:
res = "content_new/location_new.xhtml";
if( newLocationAction.getMode() == -1 ) {
newLocationAction.begin();
}
break;
case CREATE_ROUTE:
res = "content_new/route_new.xhtml";
if( newRouteAction.getMode() != 2 ) {
newRouteAction.setMode(2);
}
break;
default:
for( KiWiResource type : currentContentItem.getTypes() ) {
String seRQLID = type.getSeRQLID();
if(seRQLID.contains(Constants.NS_FCP_CORE+"Location")) {
res = "content/location.xhtml";
locationAction.begin();
break;
} else if(seRQLID.contains(Constants.NS_KIWI_CORE+"BlogPost")) {
res = "content/blog.xhtml";
newsItemAction.begin();
break;
} else if(seRQLID.contains(Constants.NS_FCP_CORE+"NewsItem")) {
res = "content/newsItem.xhtml";
newsItemAction.begin();
break;
} else if(seRQLID.contains(Constants.NS_TAGIT + "Route")) {
res = "content/route.xhtml";
routeAction.begin();
break;
} else if(seRQLID.contains(Constants.NS_KIWI_CORE + "User")) {
res = "content/person.xhtml";
personAction.begin();
break;
} else if(seRQLID.contains(Constants.NS_DEMO+"LocatedMeeting")) {
res = "content/location.xhtml";
locationAction.begin();
break;
}
}
}
log.info("set layout to #0",res);
return res;
} | public string gettagitlayoutpath() { string res = "content/none.xhtml"; switch( exploreraction.getmode() ) { case create_location: res = "content_new/location_new.xhtml"; if( newlocationaction.getmode() == -1 ) { newlocationaction.begin(); } break; case create_route: res = "content_new/route_new.xhtml"; if( newrouteaction.getmode() != 2 ) { newrouteaction.setmode(2); } break; default: for( kiwiresource type : currentcontentitem.gettypes() ) { string serqlid = type.getserqlid(); if(serqlid.contains(constants.ns_fcp_core+"location")) { res = "content/location.xhtml"; locationaction.begin(); break; } else if(serqlid.contains(constants.ns_kiwi_core+"blogpost")) { res = "content/blog.xhtml"; newsitemaction.begin(); break; } else if(serqlid.contains(constants.ns_fcp_core+"newsitem")) { res = "content/newsitem.xhtml"; newsitemaction.begin(); break; } else if(serqlid.contains(constants.ns_tagit + "route")) { res = "content/route.xhtml"; routeaction.begin(); break; } else if(serqlid.contains(constants.ns_kiwi_core + "user")) { res = "content/person.xhtml"; personaction.begin(); break; } else if(serqlid.contains(constants.ns_demo+"locatedmeeting")) { res = "content/location.xhtml"; locationaction.begin(); break; } } } log.info("set layout to #0",res); return res; } | fregaham/KiWi | [
1,
1,
0,
0
] |
11,778 | void load(FPod fpod)
{
this.fpod = fpod;
this.typesByName = new HashMap();
// create a hollow Type for each FType (this requires two steps,
// because we don't necessary have all the Types created for
// superclasses until this loop completes)
int numTypes = fpod.types == null ? 0 : fpod.types.length;
types = new ClassType[numTypes];
for (int i=0; i<numTypes; ++i)
{
// create type instance
ClassType type = new ClassType(this, fpod.types[i]);
// add to my data structures
types[i] = type;
if (typesByName.put(type.name, type) != null)
throw Err.make("Invalid pod: " + name + " type already defined: " + type.name);
}
// get TypeType to use for mixin List (we need to handle case
// when loading sys itself - and lookup within my own pod)
Type typeType = Sys.TypeType;
if (typeType == null)
typeType = (Type)typesByName.get("Type");
// now that everthing is mapped, we can fill in the super
// class fields (unless something is wacked, this will only
// use Types in my pod or in pods already loaded)
for (int i=0; i<numTypes; ++i)
{
FType ftype = fpod.types[i];
ClassType type = types[i];
type.base = type(ftype.base);
Object[] mixins = new Object[ftype.mixins.length];
for (int j=0; j<mixins.length; ++j)
mixins[j] = type(ftype.mixins[j]);
type.mixins = new List(typeType, mixins).ro();
}
} | void load(FPod fpod)
{
this.fpod = fpod;
this.typesByName = new HashMap();
int numTypes = fpod.types == null ? 0 : fpod.types.length;
types = new ClassType[numTypes];
for (int i=0; i<numTypes; ++i)
{
ClassType type = new ClassType(this, fpod.types[i]);
types[i] = type;
if (typesByName.put(type.name, type) != null)
throw Err.make("Invalid pod: " + name + " type already defined: " + type.name);
}
Type typeType = Sys.TypeType;
if (typeType == null)
typeType = (Type)typesByName.get("Type");
for (int i=0; i<numTypes; ++i)
{
FType ftype = fpod.types[i];
ClassType type = types[i];
type.base = type(ftype.base);
Object[] mixins = new Object[ftype.mixins.length];
for (int j=0; j<mixins.length; ++j)
mixins[j] = type(ftype.mixins[j]);
type.mixins = new List(typeType, mixins).ro();
}
} | void load(fpod fpod) { this.fpod = fpod; this.typesbyname = new hashmap(); int numtypes = fpod.types == null ? 0 : fpod.types.length; types = new classtype[numtypes]; for (int i=0; i<numtypes; ++i) { classtype type = new classtype(this, fpod.types[i]); types[i] = type; if (typesbyname.put(type.name, type) != null) throw err.make("invalid pod: " + name + " type already defined: " + type.name); } type typetype = sys.typetype; if (typetype == null) typetype = (type)typesbyname.get("type"); for (int i=0; i<numtypes; ++i) { ftype ftype = fpod.types[i]; classtype type = types[i]; type.base = type(ftype.base); object[] mixins = new object[ftype.mixins.length]; for (int j=0; j<mixins.length; ++j) mixins[j] = type(ftype.mixins[j]); type.mixins = new list(typetype, mixins).ro(); } } | fanx-dev/fantom | [
0,
1,
0,
0
] |
11,829 | @Override
public action to_value(action expression, origin the_origin) {
if (constraints != null) {
// We need to specially handled narrowed variables here
// because the reference type is not narrowed.
// Say the variable declaration is "string or null foo", and it's narrowed to string.
// The is_reference_type(the_type) would return a union type, which is not what we want.
action narrowed_action = can_narrow(expression, constraints);
if (narrowed_action != null) {
return narrowed_action;
}
}
type the_type = expression.result().type_bound();
if (common_types.is_reference_type(the_type)) {
// TODO: check that flavor is readonly or mutable.
type value_type = common_types.get_reference_parameter(the_type);
// TODO: replace this with a promotion lookup.
return promote(expression, value_type, the_origin);
} else {
return expression;
}
} | @Override
public action to_value(action expression, origin the_origin) {
if (constraints != null) {
action narrowed_action = can_narrow(expression, constraints);
if (narrowed_action != null) {
return narrowed_action;
}
}
type the_type = expression.result().type_bound();
if (common_types.is_reference_type(the_type)) {
type value_type = common_types.get_reference_parameter(the_type);
return promote(expression, value_type, the_origin);
} else {
return expression;
}
} | @override public action to_value(action expression, origin the_origin) { if (constraints != null) { action narrowed_action = can_narrow(expression, constraints); if (narrowed_action != null) { return narrowed_action; } } type the_type = expression.result().type_bound(); if (common_types.is_reference_type(the_type)) { type value_type = common_types.get_reference_parameter(the_type); return promote(expression, value_type, the_origin); } else { return expression; } } | dynin/ideal | [
1,
1,
0,
0
] |
20,164 | @Override
protected void reloadSettings( List<String> updatedSettings ) {
// TODO: Implement disconnect and reconnect to PostgreSQL instance.
} | @Override
protected void reloadSettings( List<String> updatedSettings ) {
} | @override protected void reloadsettings( list<string> updatedsettings ) { } | em3ndez/Polypheny-DB | [
0,
1,
0,
0
] |
20,491 | private void attemptLogin() {
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
final String email = mEmailView.getText().toString();
final String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password.
if (TextUtils.isEmpty(password)) {
mPasswordView.setError(getString(R.string.error_field_required));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
//We show the loader and hide the form
showHideView(mProgressView, mLoginFormView, true);
//We set the response listener with corresponding overridden methods
AppResponseListener<JSONObject> responseListener = new AppResponseListener<JSONObject>(getApplicationContext()){
@Override
public void onResponse(JSONObject response) {
Context context = getApplicationContext();
String firstName = null;
String lastName = null;
try {
firstName = response.getString(UserRequestManager.FIRST_NAME);
lastName = response.getString(UserRequestManager.LAST_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
//TODO: Use method UserManager.logInUser loading user from database
PrefsManager.saveUserCredentials(context, email, password);
PrefsManager.setStringPref(context, PrefsManager.PREF_USER_FIRST_NAME, firstName);
PrefsManager.setStringPref(context, PrefsManager.PREF_USER_LAST_NAME, lastName);
startActivityClosingAllOthers(DrawerActivity.class);
onPostResponse();
}
@Override
public void onUnauthorizedError(VolleyError error) {
showToast(R.string.error_wrong_credentials);
}
@Override
public void onPostResponse(){
showHideView(mLoginFormView, mProgressView, true);
}
};
//We add the request
JsonObjectRequest request = UserRequestManager.userLogInRequest(email, password, responseListener);
VolleyManager.getInstance(getApplicationContext()).addToRequestQueue(request);
}
} | private void attemptLogin() {
mEmailView.setError(null);
mPasswordView.setError(null);
final String email = mEmailView.getText().toString();
final String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
if (TextUtils.isEmpty(password)) {
mPasswordView.setError(getString(R.string.error_field_required));
focusView = mPasswordView;
cancel = true;
}
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
focusView.requestFocus();
} else {
showHideView(mProgressView, mLoginFormView, true);
AppResponseListener<JSONObject> responseListener = new AppResponseListener<JSONObject>(getApplicationContext()){
@Override
public void onResponse(JSONObject response) {
Context context = getApplicationContext();
String firstName = null;
String lastName = null;
try {
firstName = response.getString(UserRequestManager.FIRST_NAME);
lastName = response.getString(UserRequestManager.LAST_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
PrefsManager.saveUserCredentials(context, email, password);
PrefsManager.setStringPref(context, PrefsManager.PREF_USER_FIRST_NAME, firstName);
PrefsManager.setStringPref(context, PrefsManager.PREF_USER_LAST_NAME, lastName);
startActivityClosingAllOthers(DrawerActivity.class);
onPostResponse();
}
@Override
public void onUnauthorizedError(VolleyError error) {
showToast(R.string.error_wrong_credentials);
}
@Override
public void onPostResponse(){
showHideView(mLoginFormView, mProgressView, true);
}
};
JsonObjectRequest request = UserRequestManager.userLogInRequest(email, password, responseListener);
VolleyManager.getInstance(getApplicationContext()).addToRequestQueue(request);
}
} | private void attemptlogin() { memailview.seterror(null); mpasswordview.seterror(null); final string email = memailview.gettext().tostring(); final string password = mpasswordview.gettext().tostring(); boolean cancel = false; view focusview = null; if (textutils.isempty(password)) { mpasswordview.seterror(getstring(r.string.error_field_required)); focusview = mpasswordview; cancel = true; } if (textutils.isempty(email)) { memailview.seterror(getstring(r.string.error_field_required)); focusview = memailview; cancel = true; } if (cancel) { focusview.requestfocus(); } else { showhideview(mprogressview, mloginformview, true); appresponselistener<jsonobject> responselistener = new appresponselistener<jsonobject>(getapplicationcontext()){ @override public void onresponse(jsonobject response) { context context = getapplicationcontext(); string firstname = null; string lastname = null; try { firstname = response.getstring(userrequestmanager.first_name); lastname = response.getstring(userrequestmanager.last_name); } catch (jsonexception e) { e.printstacktrace(); } prefsmanager.saveusercredentials(context, email, password); prefsmanager.setstringpref(context, prefsmanager.pref_user_first_name, firstname); prefsmanager.setstringpref(context, prefsmanager.pref_user_last_name, lastname); startactivityclosingallothers(draweractivity.class); onpostresponse(); } @override public void onunauthorizederror(volleyerror error) { showtoast(r.string.error_wrong_credentials); } @override public void onpostresponse(){ showhideview(mloginformview, mprogressview, true); } }; jsonobjectrequest request = userrequestmanager.userloginrequest(email, password, responselistener); volleymanager.getinstance(getapplicationcontext()).addtorequestqueue(request); } } | edwinperaza/playmagnet | [
1,
0,
0,
0
] |
20,492 | public static boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("@");
} | public static boolean isEmailValid(String email) {
return email.contains("@");
} | public static boolean isemailvalid(string email) { return email.contains("@"); } | edwinperaza/playmagnet | [
0,
1,
0,
0
] |
20,609 | private void _setShutter(String name) {
Shutter oldValue = getShutter();
Shutter shutter = Shutter.getShutter(name, oldValue);
// XXX: Fix for older XML files saved with wrong shutter value
if (shutter == Shutter.OPEN && _lamps.size() == 1) {
Lamp lamp = _lamps.iterator().next();
if (lamp != Lamp.IR_GREY_BODY_HIGH && lamp != Lamp.IR_GREY_BODY_LOW) {
shutter = Shutter.CLOSED;
}
}
setShutter(shutter);
} | private void _setShutter(String name) {
Shutter oldValue = getShutter();
Shutter shutter = Shutter.getShutter(name, oldValue);
if (shutter == Shutter.OPEN && _lamps.size() == 1) {
Lamp lamp = _lamps.iterator().next();
if (lamp != Lamp.IR_GREY_BODY_HIGH && lamp != Lamp.IR_GREY_BODY_LOW) {
shutter = Shutter.CLOSED;
}
}
setShutter(shutter);
} | private void _setshutter(string name) { shutter oldvalue = getshutter(); shutter shutter = shutter.getshutter(name, oldvalue); if (shutter == shutter.open && _lamps.size() == 1) { lamp lamp = _lamps.iterator().next(); if (lamp != lamp.ir_grey_body_high && lamp != lamp.ir_grey_body_low) { shutter = shutter.closed; } } setshutter(shutter); } | cquiroz/ocs | [
0,
0,
1,
0
] |
20,684 | @Override
public synchronized void compress(SpdyFrame frame, int start)
throws IOException {
init(frame.version);
if (compressBuffer == null) {
compressBuffer = new byte[frame.data.length];
}
//System.out.println(HexDumpListener.getHexDump(frame.data, 0, frame.endData, true, true));
Deflater zip = zipOut;
// last byte for flush ?
zip.setInput(frame.data, start, frame.endData - start - 1);
int coff = start;
zip.setLevel(Deflater.DEFAULT_COMPRESSION);
while (true) {
int rd = zip.deflate(compressBuffer, coff, compressBuffer.length - coff);
if (rd == 0) {
// needsInput needs to be called - we're done with this frame ?
zip.setInput(frame.data, frame.endData - 1, 1);
zip.setLevel(Deflater.BEST_SPEED);
while (true) {
rd = zip.deflate(compressBuffer, coff, compressBuffer.length - coff);
coff += rd;
if (rd == 0) {
break;
}
byte[] b = new byte[compressBuffer.length * 2];
System.arraycopy(compressBuffer, 0, b, 0, coff);
compressBuffer = b;
}
zip.setLevel(Deflater.DEFAULT_COMPRESSION);
break;
}
coff += rd;
}
byte[] tmp = frame.data;
frame.data = compressBuffer;
compressBuffer = tmp;
frame.endData = coff;
} | @Override
public synchronized void compress(SpdyFrame frame, int start)
throws IOException {
init(frame.version);
if (compressBuffer == null) {
compressBuffer = new byte[frame.data.length];
}
Deflater zip = zipOut;
zip.setInput(frame.data, start, frame.endData - start - 1);
int coff = start;
zip.setLevel(Deflater.DEFAULT_COMPRESSION);
while (true) {
int rd = zip.deflate(compressBuffer, coff, compressBuffer.length - coff);
if (rd == 0) {
zip.setInput(frame.data, frame.endData - 1, 1);
zip.setLevel(Deflater.BEST_SPEED);
while (true) {
rd = zip.deflate(compressBuffer, coff, compressBuffer.length - coff);
coff += rd;
if (rd == 0) {
break;
}
byte[] b = new byte[compressBuffer.length * 2];
System.arraycopy(compressBuffer, 0, b, 0, coff);
compressBuffer = b;
}
zip.setLevel(Deflater.DEFAULT_COMPRESSION);
break;
}
coff += rd;
}
byte[] tmp = frame.data;
frame.data = compressBuffer;
compressBuffer = tmp;
frame.endData = coff;
} | @override public synchronized void compress(spdyframe frame, int start) throws ioexception { init(frame.version); if (compressbuffer == null) { compressbuffer = new byte[frame.data.length]; } deflater zip = zipout; zip.setinput(frame.data, start, frame.enddata - start - 1); int coff = start; zip.setlevel(deflater.default_compression); while (true) { int rd = zip.deflate(compressbuffer, coff, compressbuffer.length - coff); if (rd == 0) { zip.setinput(frame.data, frame.enddata - 1, 1); zip.setlevel(deflater.best_speed); while (true) { rd = zip.deflate(compressbuffer, coff, compressbuffer.length - coff); coff += rd; if (rd == 0) { break; } byte[] b = new byte[compressbuffer.length * 2]; system.arraycopy(compressbuffer, 0, b, 0, coff); compressbuffer = b; } zip.setlevel(deflater.default_compression); break; } coff += rd; } byte[] tmp = frame.data; frame.data = compressbuffer; compressbuffer = tmp; frame.enddata = coff; } | costinm/tomcat | [
1,
0,
0,
0
] |
12,650 | @Test
public void test() throws Exception {
// Workaround for failing tests. When these tests are executed in
// separate test methods, only the first one passes successfully.
testLogDebug();
testLogError();
testLogWarn();
testLogInfo();
testLogTrace();
testLogDebugWithThrowable();
testLogErrorWithThrowable();
testLogWarnWithThrowable();
testLogInfoWithThrowable();
testLogTraceWithThrowable();
} | @Test
public void test() throws Exception {
testLogDebug();
testLogError();
testLogWarn();
testLogInfo();
testLogTrace();
testLogDebugWithThrowable();
testLogErrorWithThrowable();
testLogWarnWithThrowable();
testLogInfoWithThrowable();
testLogTraceWithThrowable();
} | @test public void test() throws exception { testlogdebug(); testlogerror(); testlogwarn(); testloginfo(); testlogtrace(); testlogdebugwiththrowable(); testlogerrorwiththrowable(); testlogwarnwiththrowable(); testloginfowiththrowable(); testlogtracewiththrowable(); } | delchev/cloud-dirigible | [
0,
0,
0,
1
] |
20,936 | public static void addFuncprodutividade() {
funcionarios[1] = new FuncProdutividade(JOptionPane.showInputDialog("Numero do BI do funcionario produtividade"), JOptionPane.showInputDialog("Data de ingresso do funcionario produtividade"), Double.parseDouble(JOptionPane.showInputDialog("Salario do funcionario produtividade")), Integer.parseInt(JOptionPane.showInputDialog("Unidade produzida do funcionario produtividade")), Double.parseDouble(JOptionPane.showInputDialog("Valor da unidade produzida funcionario produtividade")));
} | public static void addFuncprodutividade() {
funcionarios[1] = new FuncProdutividade(JOptionPane.showInputDialog("Numero do BI do funcionario produtividade"), JOptionPane.showInputDialog("Data de ingresso do funcionario produtividade"), Double.parseDouble(JOptionPane.showInputDialog("Salario do funcionario produtividade")), Integer.parseInt(JOptionPane.showInputDialog("Unidade produzida do funcionario produtividade")), Double.parseDouble(JOptionPane.showInputDialog("Valor da unidade produzida funcionario produtividade")));
} | public static void addfuncprodutividade() { funcionarios[1] = new funcprodutividade(joptionpane.showinputdialog("numero do bi do funcionario produtividade"), joptionpane.showinputdialog("data de ingresso do funcionario produtividade"), double.parsedouble(joptionpane.showinputdialog("salario do funcionario produtividade")), integer.parseint(joptionpane.showinputdialog("unidade produzida do funcionario produtividade")), double.parsedouble(joptionpane.showinputdialog("valor da unidade produzida funcionario produtividade"))); } | fernandogomesfg/Algoritmos-em-Java | [
1,
0,
0,
0
] |
20,938 | public static void printSalarioProdutividade() {
for (int i = 0; i < funcionarios.length; i++) {
if (funcionarios[i] instanceof FuncProdutividade) {
System.out.println(funcionarios[i].calcularRemuneracao());
}
}
} | public static void printSalarioProdutividade() {
for (int i = 0; i < funcionarios.length; i++) {
if (funcionarios[i] instanceof FuncProdutividade) {
System.out.println(funcionarios[i].calcularRemuneracao());
}
}
} | public static void printsalarioprodutividade() { for (int i = 0; i < funcionarios.length; i++) { if (funcionarios[i] instanceof funcprodutividade) { system.out.println(funcionarios[i].calcularremuneracao()); } } } | fernandogomesfg/Algoritmos-em-Java | [
1,
0,
0,
0
] |
12,906 | private void distribute(Distribution[] distributionList, int iterationNum) {
Distribution[] busy = null; //*TODO CONSIDER USE LIST WITH INITIAL CAP SIZE
for (int inc = 0; inc < distributionList.length; inc++) {
if (distributionList[inc] == null)
continue;
if (!distributionList[inc].getiStepDecorator().offerQueueSubjectUpdate(distributionList[inc].getData(), distributionList[inc].getSubject())) {
if (busy == null) {
busy = new Distribution[distributionList.length];
}
busy[inc] = distributionList[inc];
logger.debug("Distribution not succeeded. Moving to Deceleration Mode for Subject: " + busy[inc].getSubject() + ". Iteration number - " + iterationNum + "/" + MAXIMUM_OFFERS_RETRIES);
}
}
if (!isEmpty(busy)) {
//* ***** Deceleration Mode *****
if (iterationNum >= MAXIMUM_OFFERS_RETRIES) {
logger.debug("Deceleration Mode failed after " + iterationNum + "/" + MAXIMUM_OFFERS_RETRIES + " retries. Moving back to normal distribution");
for (Distribution dist : distributionList) {
if (dist == null)
continue;
dist.getiStepDecorator().queueSubjectUpdate(dist.getData(), dist.getSubject());
}
}
try {
logger.debug("Retarding the distribution for " + WAIT_PERIOD_MILLI * iterationNum + " milliseconds");
Thread.sleep(WAIT_PERIOD_MILLI * iterationNum);
} catch (InterruptedException e) {
throw new SteppingSystemException("Distribution timeout failed");
}
distribute(busy, ++iterationNum);
}
} | private void distribute(Distribution[] distributionList, int iterationNum) {
Distribution[] busy = null;
for (int inc = 0; inc < distributionList.length; inc++) {
if (distributionList[inc] == null)
continue;
if (!distributionList[inc].getiStepDecorator().offerQueueSubjectUpdate(distributionList[inc].getData(), distributionList[inc].getSubject())) {
if (busy == null) {
busy = new Distribution[distributionList.length];
}
busy[inc] = distributionList[inc];
logger.debug("Distribution not succeeded. Moving to Deceleration Mode for Subject: " + busy[inc].getSubject() + ". Iteration number - " + iterationNum + "/" + MAXIMUM_OFFERS_RETRIES);
}
}
if (!isEmpty(busy)) {
if (iterationNum >= MAXIMUM_OFFERS_RETRIES) {
logger.debug("Deceleration Mode failed after " + iterationNum + "/" + MAXIMUM_OFFERS_RETRIES + " retries. Moving back to normal distribution");
for (Distribution dist : distributionList) {
if (dist == null)
continue;
dist.getiStepDecorator().queueSubjectUpdate(dist.getData(), dist.getSubject());
}
}
try {
logger.debug("Retarding the distribution for " + WAIT_PERIOD_MILLI * iterationNum + " milliseconds");
Thread.sleep(WAIT_PERIOD_MILLI * iterationNum);
} catch (InterruptedException e) {
throw new SteppingSystemException("Distribution timeout failed");
}
distribute(busy, ++iterationNum);
}
} | private void distribute(distribution[] distributionlist, int iterationnum) { distribution[] busy = null; for (int inc = 0; inc < distributionlist.length; inc++) { if (distributionlist[inc] == null) continue; if (!distributionlist[inc].getistepdecorator().offerqueuesubjectupdate(distributionlist[inc].getdata(), distributionlist[inc].getsubject())) { if (busy == null) { busy = new distribution[distributionlist.length]; } busy[inc] = distributionlist[inc]; logger.debug("distribution not succeeded. moving to deceleration mode for subject: " + busy[inc].getsubject() + ". iteration number - " + iterationnum + "/" + maximum_offers_retries); } } if (!isempty(busy)) { if (iterationnum >= maximum_offers_retries) { logger.debug("deceleration mode failed after " + iterationnum + "/" + maximum_offers_retries + " retries. moving back to normal distribution"); for (distribution dist : distributionlist) { if (dist == null) continue; dist.getistepdecorator().queuesubjectupdate(dist.getdata(), dist.getsubject()); } } try { logger.debug("retarding the distribution for " + wait_period_milli * iterationnum + " milliseconds"); thread.sleep(wait_period_milli * iterationnum); } catch (interruptedexception e) { throw new steppingsystemexception("distribution timeout failed"); } distribute(busy, ++iterationnum); } } | gabibeyo/stepping | [
1,
0,
0,
0
] |
13,058 | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CheckChainMap)) return false;
if (!super.equals(o)) return false;
CheckChainMap<?, ?> that = (CheckChainMap<?, ?>) o;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
return Arrays.equals(table, that.table);
} | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CheckChainMap)) return false;
if (!super.equals(o)) return false;
CheckChainMap<?, ?> that = (CheckChainMap<?, ?>) o;
return Arrays.equals(table, that.table);
} | @override public boolean equals(object o) { if (this == o) return true; if (!(o instanceof checkchainmap)) return false; if (!super.equals(o)) return false; checkchainmap<?, ?> that = (checkchainmap<?, ?>) o; return arrays.equals(table, that.table); } | finefuture/gazelle | [
1,
0,
0,
0
] |
13,286 | private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("@");
} | private boolean isEmailValid(String email) {
return email.contains("@");
} | private boolean isemailvalid(string email) { return email.contains("@"); } | eZubia/scrum-team | [
1,
0,
0,
0
] |
13,333 | public int find(V target, InclusionMode mode) {
return find(target, mode, MatchRequirement.EXACT_ONLY);
} | public int find(V target, InclusionMode mode) {
return find(target, mode, MatchRequirement.EXACT_ONLY);
} | public int find(v target, inclusionmode mode) { return find(target, mode, matchrequirement.exact_only); } | devjn/fesimplegeoprox-android-maps | [
1,
0,
0,
0
] |
13,381 | public void close(boolean removeSocket, boolean stopKeepAliveTask) {
isRunning = false;
// we need to close everything because the socket may be closed by the other end
// like in LB scenarios sending OPTIONS and killing the socket after it gets the response
if (mySock != null) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("Closing socket " + key);
try {
mySock.close();
mySock = null;
} catch (IOException ex) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("Error closing socket " + ex);
}
}
if(myParser != null) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("Closing my parser " + myParser);
myParser.close();
}
// no need to close myClientInputStream since myParser.close() above will do it
if(myClientOutputStream != null) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("Closing client output stream " + myClientOutputStream);
try {
myClientOutputStream.close();
} catch (IOException ex) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("Error closing client output stream" + ex);
}
}
if(removeSocket) {
// remove the "tcp:" part of the key to cleanup the ioHandler hashmap
String ioHandlerKey = key.substring(4);
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("Closing TCP socket " + ioHandlerKey);
// Issue 358 : remove socket and semaphore on close to avoid leaking
sipStack.ioHandler.removeSocket(ioHandlerKey);
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Closing message Channel (key = " + key +")" + this);
}
} else {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
String ioHandlerKey = key.substring(4);
logger.logDebug("not removing socket key from the cached map since it has already been updated by the iohandler.sendBytes " + ioHandlerKey);
}
}
if(stopKeepAliveTask) {
cancelPingKeepAliveTimeoutTaskIfStarted();
}
} | public void close(boolean removeSocket, boolean stopKeepAliveTask) {
isRunning = false;
if (mySock != null) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("Closing socket " + key);
try {
mySock.close();
mySock = null;
} catch (IOException ex) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("Error closing socket " + ex);
}
}
if(myParser != null) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("Closing my parser " + myParser);
myParser.close();
}
if(myClientOutputStream != null) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("Closing client output stream " + myClientOutputStream);
try {
myClientOutputStream.close();
} catch (IOException ex) {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("Error closing client output stream" + ex);
}
}
if(removeSocket) {
String ioHandlerKey = key.substring(4);
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG))
logger.logDebug("Closing TCP socket " + ioHandlerKey);
sipStack.ioHandler.removeSocket(ioHandlerKey);
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
logger.logDebug("Closing message Channel (key = " + key +")" + this);
}
} else {
if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
String ioHandlerKey = key.substring(4);
logger.logDebug("not removing socket key from the cached map since it has already been updated by the iohandler.sendBytes " + ioHandlerKey);
}
}
if(stopKeepAliveTask) {
cancelPingKeepAliveTimeoutTaskIfStarted();
}
} | public void close(boolean removesocket, boolean stopkeepalivetask) { isrunning = false; if (mysock != null) { if (logger.isloggingenabled(logwriter.trace_debug)) logger.logdebug("closing socket " + key); try { mysock.close(); mysock = null; } catch (ioexception ex) { if (logger.isloggingenabled(logwriter.trace_debug)) logger.logdebug("error closing socket " + ex); } } if(myparser != null) { if (logger.isloggingenabled(logwriter.trace_debug)) logger.logdebug("closing my parser " + myparser); myparser.close(); } if(myclientoutputstream != null) { if (logger.isloggingenabled(logwriter.trace_debug)) logger.logdebug("closing client output stream " + myclientoutputstream); try { myclientoutputstream.close(); } catch (ioexception ex) { if (logger.isloggingenabled(logwriter.trace_debug)) logger.logdebug("error closing client output stream" + ex); } } if(removesocket) { string iohandlerkey = key.substring(4); if (logger.isloggingenabled(logwriter.trace_debug)) logger.logdebug("closing tcp socket " + iohandlerkey); sipstack.iohandler.removesocket(iohandlerkey); if (logger.isloggingenabled(logwriter.trace_debug)) { logger.logdebug("closing message channel (key = " + key +")" + this); } } else { if (logger.isloggingenabled(logwriter.trace_debug)) { string iohandlerkey = key.substring(4); logger.logdebug("not removing socket key from the cached map since it has already been updated by the iohandler.sendbytes " + iohandlerkey); } } if(stopkeepalivetask) { cancelpingkeepalivetimeouttaskifstarted(); } } | fhg-fokus-nubomedia/signaling-plane | [
0,
0,
0,
0
] |
21,575 | private String getTypeString(int type, int length)
{
if (type == DataType.INT.getType()) {
return "int";
}
if (type == DataType.FLOAT.getType()) {
return "float";
}
if (type == DataType.DOUBLE.getType()) {
return "double";
}
if (type == DataType.DATE.getType()) {
return "date";
}
if (type == DataType.CHAR.getType()) {
return "char(" + length + ")";
}
if (type == DataType.VARCHAR.getType()) {
return "varchar(" + length + ")";
}
// todo add more types
return null;
} | private String getTypeString(int type, int length)
{
if (type == DataType.INT.getType()) {
return "int";
}
if (type == DataType.FLOAT.getType()) {
return "float";
}
if (type == DataType.DOUBLE.getType()) {
return "double";
}
if (type == DataType.DATE.getType()) {
return "date";
}
if (type == DataType.CHAR.getType()) {
return "char(" + length + ")";
}
if (type == DataType.VARCHAR.getType()) {
return "varchar(" + length + ")";
}
return null;
} | private string gettypestring(int type, int length) { if (type == datatype.int.gettype()) { return "int"; } if (type == datatype.float.gettype()) { return "float"; } if (type == datatype.double.gettype()) { return "double"; } if (type == datatype.date.gettype()) { return "date"; } if (type == datatype.char.gettype()) { return "char(" + length + ")"; } if (type == datatype.varchar.gettype()) { return "varchar(" + length + ")"; } return null; } | dbiir/pard | [
0,
1,
0,
0
] |
13,395 | public static int getPreOpsOutputSize(Component component, Schema schema,
TableAliasName tan) {
if (component instanceof ThetaJoinComponent)
throw new RuntimeException(
"SQL generator with Theta does not work for now!");
// TODO similar to Equijoin, but not subtracting joinColumnsLength
final Component[] parents = component.getParents();
if (parents == null)
// this is a DataSourceComponent
return getPreOpsOutputSize((DataSourceComponent) component, schema,
tan);
else if (parents.length == 1)
return getPreOpsOutputSize(parents[0], schema, tan);
else if (parents.length == 2) {
final Component firstParent = parents[0];
final Component secondParent = parents[1];
final int joinColumnsLength = firstParent.getHashIndexes().size();
return getPreOpsOutputSize(firstParent, schema, tan)
+ getPreOpsOutputSize(secondParent, schema, tan)
- joinColumnsLength;
}
throw new RuntimeException("More than two parents for a component "
+ component);
} | public static int getPreOpsOutputSize(Component component, Schema schema,
TableAliasName tan) {
if (component instanceof ThetaJoinComponent)
throw new RuntimeException(
"SQL generator with Theta does not work for now!");
final Component[] parents = component.getParents();
if (parents == null)
return getPreOpsOutputSize((DataSourceComponent) component, schema,
tan);
else if (parents.length == 1)
return getPreOpsOutputSize(parents[0], schema, tan);
else if (parents.length == 2) {
final Component firstParent = parents[0];
final Component secondParent = parents[1];
final int joinColumnsLength = firstParent.getHashIndexes().size();
return getPreOpsOutputSize(firstParent, schema, tan)
+ getPreOpsOutputSize(secondParent, schema, tan)
- joinColumnsLength;
}
throw new RuntimeException("More than two parents for a component "
+ component);
} | public static int getpreopsoutputsize(component component, schema schema, tablealiasname tan) { if (component instanceof thetajoincomponent) throw new runtimeexception( "sql generator with theta does not work for now!"); final component[] parents = component.getparents(); if (parents == null) return getpreopsoutputsize((datasourcecomponent) component, schema, tan); else if (parents.length == 1) return getpreopsoutputsize(parents[0], schema, tan); else if (parents.length == 2) { final component firstparent = parents[0]; final component secondparent = parents[1]; final int joincolumnslength = firstparent.gethashindexes().size(); return getpreopsoutputsize(firstparent, schema, tan) + getpreopsoutputsize(secondparent, schema, tan) - joincolumnslength; } throw new runtimeexception("more than two parents for a component " + component); } | epfldata/squall | [
1,
0,
0,
0
] |
21,617 | @Test
@Parameters({ "clusterName", "ambariUser", "ambariPassword", "emailNeeded",
"enableSecurity", "kerberosMasterKey", "kerberosAdmin", "kerberosPassword",
"runRecipesOnHosts" })
public void testClusterCreation(@Optional("it-cluster") String clusterName, @Optional("admin") String ambariUser,
@Optional("admin123!@#") String ambariPassword, @Optional("false") boolean emailNeeded,
@Optional("false") boolean enableSecurity, @Optional String kerberosMasterKey, @Optional String kerberosAdmin, @Optional String kerberosPassword,
@Optional("") String runRecipesOnHosts) throws Exception {
// GIVEN
IntegrationTestContext itContext = getItContext();
String stackIdStr = itContext.getContextParam(CloudbreakITContextConstants.STACK_ID);
Integer stackId = Integer.valueOf(stackIdStr);
Integer blueprintId = Integer.valueOf(itContext.getContextParam(CloudbreakITContextConstants.BLUEPRINT_ID));
List<HostGroup> hostgroups = itContext.getContextParam(CloudbreakITContextConstants.HOSTGROUP_ID, List.class);
List<Map<String, Object>> map = convertHostGroups(hostgroups, runRecipesOnHosts);
itContext.putContextParam(CloudbreakITContextConstants.AMBARI_USER_ID, ambariUser);
itContext.putContextParam(CloudbreakITContextConstants.AMBARI_PASSWORD_ID, ambariPassword);
// WHEN
// TODO email needed
CloudbreakClient client = getClient();
client.postCluster(clusterName, ambariUser, ambariPassword, blueprintId, "Cluster for integration test", Integer.valueOf(stackId), map,
enableSecurity, kerberosMasterKey, kerberosAdmin, kerberosPassword);
// THEN
CloudbreakUtil.waitAndCheckStackStatus(itContext, stackIdStr, "AVAILABLE");
CloudbreakUtil.checkClusterAvailability(client, stackIdStr, ambariUser, ambariPassword);
} | @Test
@Parameters({ "clusterName", "ambariUser", "ambariPassword", "emailNeeded",
"enableSecurity", "kerberosMasterKey", "kerberosAdmin", "kerberosPassword",
"runRecipesOnHosts" })
public void testClusterCreation(@Optional("it-cluster") String clusterName, @Optional("admin") String ambariUser,
@Optional("admin123!@#") String ambariPassword, @Optional("false") boolean emailNeeded,
@Optional("false") boolean enableSecurity, @Optional String kerberosMasterKey, @Optional String kerberosAdmin, @Optional String kerberosPassword,
@Optional("") String runRecipesOnHosts) throws Exception {
IntegrationTestContext itContext = getItContext();
String stackIdStr = itContext.getContextParam(CloudbreakITContextConstants.STACK_ID);
Integer stackId = Integer.valueOf(stackIdStr);
Integer blueprintId = Integer.valueOf(itContext.getContextParam(CloudbreakITContextConstants.BLUEPRINT_ID));
List<HostGroup> hostgroups = itContext.getContextParam(CloudbreakITContextConstants.HOSTGROUP_ID, List.class);
List<Map<String, Object>> map = convertHostGroups(hostgroups, runRecipesOnHosts);
itContext.putContextParam(CloudbreakITContextConstants.AMBARI_USER_ID, ambariUser);
itContext.putContextParam(CloudbreakITContextConstants.AMBARI_PASSWORD_ID, ambariPassword);
CloudbreakClient client = getClient();
client.postCluster(clusterName, ambariUser, ambariPassword, blueprintId, "Cluster for integration test", Integer.valueOf(stackId), map,
enableSecurity, kerberosMasterKey, kerberosAdmin, kerberosPassword);
CloudbreakUtil.waitAndCheckStackStatus(itContext, stackIdStr, "AVAILABLE");
CloudbreakUtil.checkClusterAvailability(client, stackIdStr, ambariUser, ambariPassword);
} | @test @parameters({ "clustername", "ambariuser", "ambaripassword", "emailneeded", "enablesecurity", "kerberosmasterkey", "kerberosadmin", "kerberospassword", "runrecipesonhosts" }) public void testclustercreation(@optional("it-cluster") string clustername, @optional("admin") string ambariuser, @optional("admin123!@#") string ambaripassword, @optional("false") boolean emailneeded, @optional("false") boolean enablesecurity, @optional string kerberosmasterkey, @optional string kerberosadmin, @optional string kerberospassword, @optional("") string runrecipesonhosts) throws exception { integrationtestcontext itcontext = getitcontext(); string stackidstr = itcontext.getcontextparam(cloudbreakitcontextconstants.stack_id); integer stackid = integer.valueof(stackidstr); integer blueprintid = integer.valueof(itcontext.getcontextparam(cloudbreakitcontextconstants.blueprint_id)); list<hostgroup> hostgroups = itcontext.getcontextparam(cloudbreakitcontextconstants.hostgroup_id, list.class); list<map<string, object>> map = converthostgroups(hostgroups, runrecipesonhosts); itcontext.putcontextparam(cloudbreakitcontextconstants.ambari_user_id, ambariuser); itcontext.putcontextparam(cloudbreakitcontextconstants.ambari_password_id, ambaripassword); cloudbreakclient client = getclient(); client.postcluster(clustername, ambariuser, ambaripassword, blueprintid, "cluster for integration test", integer.valueof(stackid), map, enablesecurity, kerberosmasterkey, kerberosadmin, kerberospassword); cloudbreakutil.waitandcheckstackstatus(itcontext, stackidstr, "available"); cloudbreakutil.checkclusteravailability(client, stackidstr, ambariuser, ambaripassword); } | doktoric/test123 | [
1,
0,
0,
0
] |
13,832 | private void reloadItemsList() {
documentPartsDataSource.ensureConnectionIsOpen();
List<DocumentCollectionItem> documentCollectionItems = new ArrayList<>();
Log.d("DocCollectionActivity", "Checking filetypes to add");
for (FileType fileType : SectionsProvider.getFileTypesForSectionModel(sectionModel)) {
Log.d("DocCollectionActivity", "Checking filetype: " + fileType);
// TODO: use some sort of map instead
boolean isPresent = false;
for (DocumentPart documentPart : documentPartsDataSource.getDocumentPartsForSection(sectionModel)) {
if (documentPart.getType().equals(fileType)) {
DocumentCollectionItem docData = new DocumentCollectionItem(getString(fileType.getNameResourceId()), getString(R.string.document_collection_list_item_present_title), fileType, true);
documentCollectionItems.add(docData);
isPresent = true;
break;
}
}
if (!isPresent) {
Log.d("DocCollectionActivity", "File type not found in documentparts, add as TO-DO");
DocumentCollectionItem docData = new DocumentCollectionItem(getString(fileType.getNameResourceId()), getString(R.string.document_collection_list_item_not_present_title), fileType, false);
documentCollectionItems.add(docData);
}
}
listView = (ListView) findViewById(R.id.documentlist);
DocumentCollectionViewAdapter listViewAdapter = new DocumentCollectionViewAdapter(this, R.layout.fragment_document, documentCollectionItems);
listView.setAdapter(listViewAdapter);
} | private void reloadItemsList() {
documentPartsDataSource.ensureConnectionIsOpen();
List<DocumentCollectionItem> documentCollectionItems = new ArrayList<>();
Log.d("DocCollectionActivity", "Checking filetypes to add");
for (FileType fileType : SectionsProvider.getFileTypesForSectionModel(sectionModel)) {
Log.d("DocCollectionActivity", "Checking filetype: " + fileType);
boolean isPresent = false;
for (DocumentPart documentPart : documentPartsDataSource.getDocumentPartsForSection(sectionModel)) {
if (documentPart.getType().equals(fileType)) {
DocumentCollectionItem docData = new DocumentCollectionItem(getString(fileType.getNameResourceId()), getString(R.string.document_collection_list_item_present_title), fileType, true);
documentCollectionItems.add(docData);
isPresent = true;
break;
}
}
if (!isPresent) {
Log.d("DocCollectionActivity", "File type not found in documentparts, add as TO-DO");
DocumentCollectionItem docData = new DocumentCollectionItem(getString(fileType.getNameResourceId()), getString(R.string.document_collection_list_item_not_present_title), fileType, false);
documentCollectionItems.add(docData);
}
}
listView = (ListView) findViewById(R.id.documentlist);
DocumentCollectionViewAdapter listViewAdapter = new DocumentCollectionViewAdapter(this, R.layout.fragment_document, documentCollectionItems);
listView.setAdapter(listViewAdapter);
} | private void reloaditemslist() { documentpartsdatasource.ensureconnectionisopen(); list<documentcollectionitem> documentcollectionitems = new arraylist<>(); log.d("doccollectionactivity", "checking filetypes to add"); for (filetype filetype : sectionsprovider.getfiletypesforsectionmodel(sectionmodel)) { log.d("doccollectionactivity", "checking filetype: " + filetype); boolean ispresent = false; for (documentpart documentpart : documentpartsdatasource.getdocumentpartsforsection(sectionmodel)) { if (documentpart.gettype().equals(filetype)) { documentcollectionitem docdata = new documentcollectionitem(getstring(filetype.getnameresourceid()), getstring(r.string.document_collection_list_item_present_title), filetype, true); documentcollectionitems.add(docdata); ispresent = true; break; } } if (!ispresent) { log.d("doccollectionactivity", "file type not found in documentparts, add as to-do"); documentcollectionitem docdata = new documentcollectionitem(getstring(filetype.getnameresourceid()), getstring(r.string.document_collection_list_item_not_present_title), filetype, false); documentcollectionitems.add(docdata); } } listview = (listview) findviewbyid(r.id.documentlist); documentcollectionviewadapter listviewadapter = new documentcollectionviewadapter(this, r.layout.fragment_document, documentcollectionitems); listview.setadapter(listviewadapter); } | devolksbank/NL-Help-U | [
1,
0,
0,
0
] |
22,238 | public static String replaceLeadingSpacesWithNbsps (String str)
{
// todo: support for tabs?
Matcher m = _LeadingSpacesPattern.matcher(str);
StringBuffer buf = new StringBuffer();
while (m.find()) {
int spaceCount = m.group(1).length();
m.appendReplacement(buf, AWUtil.repeatedString(" ", spaceCount));
}
m.appendTail(buf);
return buf.toString();
} | public static String replaceLeadingSpacesWithNbsps (String str)
{
Matcher m = _LeadingSpacesPattern.matcher(str);
StringBuffer buf = new StringBuffer();
while (m.find()) {
int spaceCount = m.group(1).length();
m.appendReplacement(buf, AWUtil.repeatedString(" ", spaceCount));
}
m.appendTail(buf);
return buf.toString();
} | public static string replaceleadingspaceswithnbsps (string str) { matcher m = _leadingspacespattern.matcher(str); stringbuffer buf = new stringbuffer(); while (m.find()) { int spacecount = m.group(1).length(); m.appendreplacement(buf, awutil.repeatedstring(" ", spacecount)); } m.appendtail(buf); return buf.tostring(); } | fbarthez/aribaweb | [
0,
1,
0,
0
] |
14,274 | IbisSocket connect(TcpSendPort sp, ibis.ipl.impl.ReceivePortIdentifier rip,
int timeout, boolean fillTimeout) throws IOException {
IbisIdentifier id = (IbisIdentifier) rip.ibisIdentifier();
String name = rip.name();
IbisSocketAddress idAddr;
synchronized (addresses) {
idAddr = addresses.get(id);
if (idAddr == null) {
idAddr = new IbisSocketAddress(id.getImplementationData());
addresses.put(id, idAddr);
}
}
long startTime = System.currentTimeMillis();
if (logger.isDebugEnabled()) {
logger.debug("--> Creating socket for connection to " + name
+ " at " + idAddr);
}
PortType sendPortType = sp.getPortType();
do {
DataOutputStream out = null;
IbisSocket s = null;
int result = -1;
sp.printManagementProperties(System.out);
try {
s = factory.createClientSocket(idAddr, timeout, fillTimeout,
sp.managementProperties());
s.setTcpNoDelay(true);
out = new DataOutputStream(new BufferedArrayOutputStream(
s.getOutputStream()));
out.writeUTF(name);
sp.getIdent().writeTo(out);
sendPortType.writeTo(out);
out.flush();
result = s.getInputStream().read();
switch (result) {
case ReceivePort.ACCEPTED:
return s;
case ReceivePort.ALREADY_CONNECTED:
throw new AlreadyConnectedException("Already connected",
rip);
case ReceivePort.TYPE_MISMATCH:
// Read receiveport type from input, to produce a
// better error message.
DataInputStream in = new DataInputStream(s.getInputStream());
PortType rtp = new PortType(in);
CapabilitySet s1 = rtp.unmatchedCapabilities(sendPortType);
CapabilitySet s2 = sendPortType.unmatchedCapabilities(rtp);
String message = "";
if (s1.size() != 0) {
message = message
+ "\nUnmatched receiveport capabilities: "
+ s1.toString() + ".";
}
if (s2.size() != 0) {
message = message
+ "\nUnmatched sendport capabilities: "
+ s2.toString() + ".";
}
throw new PortMismatchException(
"Cannot connect ports of different port types."
+ message, rip);
case ReceivePort.DENIED:
throw new ConnectionRefusedException(
"Receiver denied connection", rip);
case ReceivePort.NO_MANY_TO_X:
throw new ConnectionRefusedException(
"Receiver already has a connection and neither ManyToOne not ManyToMany "
+ "is set", rip);
case ReceivePort.NOT_PRESENT:
case ReceivePort.DISABLED:
// and try again if we did not reach the timeout...
if (timeout > 0
&& System.currentTimeMillis() > startTime + timeout) {
throw new ConnectionTimedOutException(
"Could not connect", rip);
}
break;
case -1:
throw new IOException("Encountered EOF in TcpIbis.connect");
default:
throw new IOException("Illegal opcode in TcpIbis.connect");
}
} catch (SocketTimeoutException e) {
throw new ConnectionTimedOutException("Could not connect", rip);
} finally {
if (result != ReceivePort.ACCEPTED) {
try {
if (out != null) {
out.close();
}
} catch (Throwable e) {
// ignored
}
try {
s.close();
} catch (Throwable e) {
// ignored
}
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// ignore
}
} while (true);
} | IbisSocket connect(TcpSendPort sp, ibis.ipl.impl.ReceivePortIdentifier rip,
int timeout, boolean fillTimeout) throws IOException {
IbisIdentifier id = (IbisIdentifier) rip.ibisIdentifier();
String name = rip.name();
IbisSocketAddress idAddr;
synchronized (addresses) {
idAddr = addresses.get(id);
if (idAddr == null) {
idAddr = new IbisSocketAddress(id.getImplementationData());
addresses.put(id, idAddr);
}
}
long startTime = System.currentTimeMillis();
if (logger.isDebugEnabled()) {
logger.debug("--> Creating socket for connection to " + name
+ " at " + idAddr);
}
PortType sendPortType = sp.getPortType();
do {
DataOutputStream out = null;
IbisSocket s = null;
int result = -1;
sp.printManagementProperties(System.out);
try {
s = factory.createClientSocket(idAddr, timeout, fillTimeout,
sp.managementProperties());
s.setTcpNoDelay(true);
out = new DataOutputStream(new BufferedArrayOutputStream(
s.getOutputStream()));
out.writeUTF(name);
sp.getIdent().writeTo(out);
sendPortType.writeTo(out);
out.flush();
result = s.getInputStream().read();
switch (result) {
case ReceivePort.ACCEPTED:
return s;
case ReceivePort.ALREADY_CONNECTED:
throw new AlreadyConnectedException("Already connected",
rip);
case ReceivePort.TYPE_MISMATCH:
DataInputStream in = new DataInputStream(s.getInputStream());
PortType rtp = new PortType(in);
CapabilitySet s1 = rtp.unmatchedCapabilities(sendPortType);
CapabilitySet s2 = sendPortType.unmatchedCapabilities(rtp);
String message = "";
if (s1.size() != 0) {
message = message
+ "\nUnmatched receiveport capabilities: "
+ s1.toString() + ".";
}
if (s2.size() != 0) {
message = message
+ "\nUnmatched sendport capabilities: "
+ s2.toString() + ".";
}
throw new PortMismatchException(
"Cannot connect ports of different port types."
+ message, rip);
case ReceivePort.DENIED:
throw new ConnectionRefusedException(
"Receiver denied connection", rip);
case ReceivePort.NO_MANY_TO_X:
throw new ConnectionRefusedException(
"Receiver already has a connection and neither ManyToOne not ManyToMany "
+ "is set", rip);
case ReceivePort.NOT_PRESENT:
case ReceivePort.DISABLED:
if (timeout > 0
&& System.currentTimeMillis() > startTime + timeout) {
throw new ConnectionTimedOutException(
"Could not connect", rip);
}
break;
case -1:
throw new IOException("Encountered EOF in TcpIbis.connect");
default:
throw new IOException("Illegal opcode in TcpIbis.connect");
}
} catch (SocketTimeoutException e) {
throw new ConnectionTimedOutException("Could not connect", rip);
} finally {
if (result != ReceivePort.ACCEPTED) {
try {
if (out != null) {
out.close();
}
} catch (Throwable e) {
}
try {
s.close();
} catch (Throwable e) {
}
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
} while (true);
} | ibissocket connect(tcpsendport sp, ibis.ipl.impl.receiveportidentifier rip, int timeout, boolean filltimeout) throws ioexception { ibisidentifier id = (ibisidentifier) rip.ibisidentifier(); string name = rip.name(); ibissocketaddress idaddr; synchronized (addresses) { idaddr = addresses.get(id); if (idaddr == null) { idaddr = new ibissocketaddress(id.getimplementationdata()); addresses.put(id, idaddr); } } long starttime = system.currenttimemillis(); if (logger.isdebugenabled()) { logger.debug("--> creating socket for connection to " + name + " at " + idaddr); } porttype sendporttype = sp.getporttype(); do { dataoutputstream out = null; ibissocket s = null; int result = -1; sp.printmanagementproperties(system.out); try { s = factory.createclientsocket(idaddr, timeout, filltimeout, sp.managementproperties()); s.settcpnodelay(true); out = new dataoutputstream(new bufferedarrayoutputstream( s.getoutputstream())); out.writeutf(name); sp.getident().writeto(out); sendporttype.writeto(out); out.flush(); result = s.getinputstream().read(); switch (result) { case receiveport.accepted: return s; case receiveport.already_connected: throw new alreadyconnectedexception("already connected", rip); case receiveport.type_mismatch: datainputstream in = new datainputstream(s.getinputstream()); porttype rtp = new porttype(in); capabilityset s1 = rtp.unmatchedcapabilities(sendporttype); capabilityset s2 = sendporttype.unmatchedcapabilities(rtp); string message = ""; if (s1.size() != 0) { message = message + "\nunmatched receiveport capabilities: " + s1.tostring() + "."; } if (s2.size() != 0) { message = message + "\nunmatched sendport capabilities: " + s2.tostring() + "."; } throw new portmismatchexception( "cannot connect ports of different port types." + message, rip); case receiveport.denied: throw new connectionrefusedexception( "receiver denied connection", rip); case receiveport.no_many_to_x: throw new connectionrefusedexception( "receiver already has a connection and neither manytoone not manytomany " + "is set", rip); case receiveport.not_present: case receiveport.disabled: if (timeout > 0 && system.currenttimemillis() > starttime + timeout) { throw new connectiontimedoutexception( "could not connect", rip); } break; case -1: throw new ioexception("encountered eof in tcpibis.connect"); default: throw new ioexception("illegal opcode in tcpibis.connect"); } } catch (sockettimeoutexception e) { throw new connectiontimedoutexception("could not connect", rip); } finally { if (result != receiveport.accepted) { try { if (out != null) { out.close(); } } catch (throwable e) { } try { s.close(); } catch (throwable e) { } } } try { thread.sleep(100); } catch (interruptedexception e) { } } while (true); } | dadepo/ipl | [
0,
0,
1,
0
] |
22,476 | @AllowedMethod
@Transactional(TransactionType.WRITE)
public String update()
{
log.debug("---------------- update()");
saveOrUpdate();
// TODO: i18n: Externalize.
// TODO: Enhance: Print link to updated shop.
addActionMessage("Shop <strong>" + escape(shop.getName()) + "</strong> updated successfully.");
return RESULT_REDIRECT_VIEW;
} | @AllowedMethod
@Transactional(TransactionType.WRITE)
public String update()
{
log.debug("---------------- update()");
saveOrUpdate();
addActionMessage("Shop <strong>" + escape(shop.getName()) + "</strong> updated successfully.");
return RESULT_REDIRECT_VIEW;
} | @allowedmethod @transactional(transactiontype.write) public string update() { log.debug("---------------- update()"); saveorupdate(); addactionmessage("shop <strong>" + escape(shop.getname()) + "</strong> updated successfully."); return result_redirect_view; } | doanhoa93/struts2shop | [
0,
1,
0,
0
] |
30,694 | public static void learnAndSaveAllModels(){
// Seleccionamos el directorio en el que se van a recoger todos los
String input_path = "data/automatic_learn/";
File[] inputFiles = new File(input_path).listFiles(x -> x.getName().endsWith(".arff"));
String output_path = "results/automatic_learn/LCM/";
for (File inputFile : inputFiles) {
try {
if (inputFile.isFile()) {
//Create the DiscreteDataSet
DiscreteDataSet data = new DiscreteDataSet(DataFileLoader.loadData(input_path + inputFile.getName(), DiscreteVariable.class));
System.out.println("------------------------------------------------------------------------------");
System.out.println("------------------------------------------------------------------------------");
System.out.println("------------------------------------------------------------------------------");
System.out.println("############## "+ data.getName() + " ############## \n");
// Learn the LTM
LTM ltm = learnBestLCMVaryingCardinality(data);
// Save it in BIF format
newBifWriter writer = new newBifWriter(new FileOutputStream(output_path + "LCM_" + FilenameUtils.removeExtension(inputFile.getName()) + ".bif"), false);
writer.write(ltm);
}
}catch(Exception e){
System.out.println("Error with " + inputFile.getName());
e.printStackTrace();
}
}
} | public static void learnAndSaveAllModels(){
String input_path = "data/automatic_learn/";
File[] inputFiles = new File(input_path).listFiles(x -> x.getName().endsWith(".arff"));
String output_path = "results/automatic_learn/LCM/";
for (File inputFile : inputFiles) {
try {
if (inputFile.isFile()) {
DiscreteDataSet data = new DiscreteDataSet(DataFileLoader.loadData(input_path + inputFile.getName(), DiscreteVariable.class));
System.out.println("------------------------------------------------------------------------------");
System.out.println("------------------------------------------------------------------------------");
System.out.println("------------------------------------------------------------------------------");
System.out.println("############## "+ data.getName() + " ############## \n");
LTM ltm = learnBestLCMVaryingCardinality(data);
newBifWriter writer = new newBifWriter(new FileOutputStream(output_path + "LCM_" + FilenameUtils.removeExtension(inputFile.getName()) + ".bif"), false);
writer.write(ltm);
}
}catch(Exception e){
System.out.println("Error with " + inputFile.getName());
e.printStackTrace();
}
}
} | public static void learnandsaveallmodels(){ string input_path = "data/automatic_learn/"; file[] inputfiles = new file(input_path).listfiles(x -> x.getname().endswith(".arff")); string output_path = "results/automatic_learn/lcm/"; for (file inputfile : inputfiles) { try { if (inputfile.isfile()) { discretedataset data = new discretedataset(datafileloader.loaddata(input_path + inputfile.getname(), discretevariable.class)); system.out.println("------------------------------------------------------------------------------"); system.out.println("------------------------------------------------------------------------------"); system.out.println("------------------------------------------------------------------------------"); system.out.println("############## "+ data.getname() + " ############## \n"); ltm ltm = learnbestlcmvaryingcardinality(data); newbifwriter writer = new newbifwriter(new fileoutputstream(output_path + "lcm_" + filenameutils.removeextension(inputfile.getname()) + ".bif"), false); writer.write(ltm); } }catch(exception e){ system.out.println("error with " + inputfile.getname()); e.printstacktrace(); } } } | fernandoj92/mvca-parkinson | [
1,
0,
0,
0
] |
22,578 | public void sendLevelFinish() {
TaskQueue.getTaskQueue()
.push(
new Task() {
public void execute() {
try {
// for thread safety
final Level level = World.getWorld().getLevel();
PacketBuilder bldr =
new PacketBuilder(
PersistingPacketManager.getPacketManager().getOutgoingPacket(4));
bldr.putShort("width", level.getWidth());
bldr.putShort("height", level.getHeight());
bldr.putShort("depth", level.getDepth());
session.send(bldr.toPacket());
Position spawn = level.getSpawnPosition();
Rotation r = level.getSpawnRotation();
sendSpawn(
(byte) -1,
session.getPlayer().nameId,
session.getPlayer().getColoredName(),
session.getPlayer().getTeamName(),
session.getPlayer().getName(),
session.getPlayer().getListName(),
session.getPlayer().getSkinUrl(),
spawn.getX(),
spawn.getY(),
spawn.getZ(),
(byte) r.getRotation(),
(byte) r.getLook(),
false,
true);
// now load the player's game (TODO in the future do this in parallel with loading
// the
// level)
SavedGameManager.getSavedGameManager()
.queuePersistenceRequest(new LoadPersistenceRequest(session.getPlayer()));
session.setReady();
World.getWorld().completeRegistration(session);
} catch (Exception ex) {
Server.log(ex);
}
}
});
} | public void sendLevelFinish() {
TaskQueue.getTaskQueue()
.push(
new Task() {
public void execute() {
try {
final Level level = World.getWorld().getLevel();
PacketBuilder bldr =
new PacketBuilder(
PersistingPacketManager.getPacketManager().getOutgoingPacket(4));
bldr.putShort("width", level.getWidth());
bldr.putShort("height", level.getHeight());
bldr.putShort("depth", level.getDepth());
session.send(bldr.toPacket());
Position spawn = level.getSpawnPosition();
Rotation r = level.getSpawnRotation();
sendSpawn(
(byte) -1,
session.getPlayer().nameId,
session.getPlayer().getColoredName(),
session.getPlayer().getTeamName(),
session.getPlayer().getName(),
session.getPlayer().getListName(),
session.getPlayer().getSkinUrl(),
spawn.getX(),
spawn.getY(),
spawn.getZ(),
(byte) r.getRotation(),
(byte) r.getLook(),
false,
true);
SavedGameManager.getSavedGameManager()
.queuePersistenceRequest(new LoadPersistenceRequest(session.getPlayer()));
session.setReady();
World.getWorld().completeRegistration(session);
} catch (Exception ex) {
Server.log(ex);
}
}
});
} | public void sendlevelfinish() { taskqueue.gettaskqueue() .push( new task() { public void execute() { try { final level level = world.getworld().getlevel(); packetbuilder bldr = new packetbuilder( persistingpacketmanager.getpacketmanager().getoutgoingpacket(4)); bldr.putshort("width", level.getwidth()); bldr.putshort("height", level.getheight()); bldr.putshort("depth", level.getdepth()); session.send(bldr.topacket()); position spawn = level.getspawnposition(); rotation r = level.getspawnrotation(); sendspawn( (byte) -1, session.getplayer().nameid, session.getplayer().getcoloredname(), session.getplayer().getteamname(), session.getplayer().getname(), session.getplayer().getlistname(), session.getplayer().getskinurl(), spawn.getx(), spawn.gety(), spawn.getz(), (byte) r.getrotation(), (byte) r.getlook(), false, true); savedgamemanager.getsavedgamemanager() .queuepersistencerequest(new loadpersistencerequest(session.getplayer())); session.setready(); world.getworld().completeregistration(session); } catch (exception ex) { server.log(ex); } } }); } | derekdinan/CTFServer | [
0,
1,
0,
0
] |
30,787 | private void onFrameLoad(JavaScriptObject cajaFrameObject)
{
//--- This is to catch the theoretical case where we call start and stop then start really fast,
//--- but the load call from the first start didn't finish before the first stop, and comes in between
//--- the first stop and the second start...NOTE this is just done based on my thoughts on possible fringe
//--- cases, not because I actually noticed this behavior.
//this.stop();
//m_cajaFrameObjects.push(cajaFrameObject);
} | private void onFrameLoad(JavaScriptObject cajaFrameObject)
{
} | private void onframeload(javascriptobject cajaframeobject) { } | dougkoellmer/swarm | [
1,
0,
1,
0
] |
14,459 | public void assignNurseToRegister(Patient patient, Nurse nurse)
{
VaccinationRegister registerToAssingNurse = searchForVaccinationRegister(patient);
registerToAssingNurse.assignNurse(nurse);
} | public void assignNurseToRegister(Patient patient, Nurse nurse)
{
VaccinationRegister registerToAssingNurse = searchForVaccinationRegister(patient);
registerToAssingNurse.assignNurse(nurse);
} | public void assignnursetoregister(patient patient, nurse nurse) { vaccinationregister registertoassingnurse = searchforvaccinationregister(patient); registertoassingnurse.assignnurse(nurse); } | deividgdt/UNED_II | [
0,
0,
0,
0
] |
22,775 | public List<PairIntArray> findEdges() {
// DFS search for sequential neighbors.
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
//for now, choosing to look only at the blue
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
// for each neighbor v of u
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
// if u is not in an edge already, create a new one
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
// keep the curve points ordered
// add v to the edge u if u is the last node in it's edge
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
//TODO: do we only want 1 neighbor from the 9 as a continuation?
// yes for now, but this requires edges be only 1 pixel wide
// inserting back at the top of the stack assures that the
// search continues next from an associated point
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
// count the number of points in edges
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
/*
//not necessary now that lines from CannyEdgeFilter are 1 pix width.
MiscellaneousCurveHelper ch = new MiscellaneousCurveHelper();
n = 0;
sz = output.size();
lastSize = Integer.MAX_VALUE;
while ((sz < lastSize) && (n < nIterMax)) {
lastSize = sz;
output = ch.pruneAndIncludeAdjacentCurves(output, img.getWidth());
sz = output.size();
log.log(Level.FINE, "{0}) {1} edges after prune overlapping",
new Object[]{Integer.toString(n), Integer.toString(sz)});
n++;
}
*/
// This helps to merge edges (that is extracted curves) at adjacent
// points that resemble an intersection of the lines, but it's not
// necessarily useful if only interested in corners and not inflection
// points because the curvature is determined correctly
// whether the curves are merged or not.
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
//TODO: this may need to change
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
//pruneSpurs(output);
adjustEdgesTowardsBrightPixels(output);
return output;
} | public List<PairIntArray> findEdges() {
Stack<PairInt> stack = new Stack<PairInt>();
int thresh0 = 1;
for (int i = 0; i < img.getWidth(); i++) {
for (int j = 0; j < img.getHeight(); j++) {
int bPix = img.getValue(i, j);
if (bPix >= thresh0) {
stack.add(new PairInt(i, j));
}
}
}
numberOfPixelsAboveThreshold = stack.size();
log.log(Level.FINE, "Number of pixels that exceed threshhold={0}",
Long.toString(numberOfPixelsAboveThreshold));
List<PairIntArray> output = new ArrayList<PairIntArray>();
int[] uNodeEdgeIdx = new int[img.getWidth() * img.getHeight()];
Arrays.fill(uNodeEdgeIdx, -1);
while (!stack.isEmpty()) {
PairInt uNode = stack.pop();
int uX = uNode.getX();
int uY = uNode.getY();
int uIdx = (uY * img.getWidth()) + uX;
boolean foundNeighbor = false;
for (int vX = (uX - 1); vX < (uX + 2); vX++) {
if (foundNeighbor) {
break;
}
if (vX < 0 || vX > (img.getWidth() - 1)) {
continue;
}
for (int vY = (uY - 1); vY < (uY + 2); vY++) {
if (vY < 0 || vY > (img.getHeight() - 1)) {
continue;
}
int vIdx = (vY * img.getWidth()) + vX;
if (uNodeEdgeIdx[vIdx] != -1 || (uIdx == vIdx)) {
continue;
}
if (img.getValue(vX, vY) < thresh0) {
continue;
}
if (uNodeEdgeIdx[uIdx] == -1) {
PairIntArray edge = new PairIntArray();
edge.add(uX, uY);
uNodeEdgeIdx[uIdx] = output.size();
output.add(edge);
}
PairIntArray appendToNode = output.get(uNodeEdgeIdx[uIdx]);
int aIdx = appendToNode.getN() - 1;
if ((appendToNode.getX(aIdx) != uX) ||
(appendToNode.getY(aIdx) != uY)) {
continue;
}
appendToNode.add(vX, vY);
uNodeEdgeIdx[vIdx] = uNodeEdgeIdx[uIdx];
stack.add(new PairInt(vX, vY));
foundNeighbor = true;
break;
}
}
}
log.fine(output.size() + " edges after DFS");
int nIterMax = 100;
int n, sz, lastSize;
long sum = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0} pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum),
Long.toString(numberOfPixelsAboveThreshold)});
log.log(Level.FINE, "there are {0} edges",
Integer.toString(output.size()));
output = mergeAdjacentEndPoints(output);
log.log(Level.FINE, "{0} edges after merge adjacent",
Integer.toString(output.size()));
output = connectClosestPointsIfCanTrim(output);
log.fine(output.size() + " edges after connect closest");
output = fillInGaps(output);
log.log(Level.FINE, "{0} edges after fill in gaps",
new Object[]{Integer.toString(output.size())});
removeEdgesShorterThan(output, edgeSizeLowerLimit);
sz = output.size();
log.log(Level.FINE, "{0} edges after removing those shorter",
new Object[]{Integer.toString(sz)});
long sum2 = countPixelsInEdges(output);
log.log(Level.FINE,
"==> {0}) pixels are in edges out of {1} pixels > threshhold",
new Object[]{Long.toString(sum2),
Long.toString(numberOfPixelsAboveThreshold)});
adjustEdgesTowardsBrightPixels(output);
return output;
} | public list<pairintarray> findedges() { stack<pairint> stack = new stack<pairint>(); int thresh0 = 1; for (int i = 0; i < img.getwidth(); i++) { for (int j = 0; j < img.getheight(); j++) { int bpix = img.getvalue(i, j); if (bpix >= thresh0) { stack.add(new pairint(i, j)); } } } numberofpixelsabovethreshold = stack.size(); log.log(level.fine, "number of pixels that exceed threshhold={0}", long.tostring(numberofpixelsabovethreshold)); list<pairintarray> output = new arraylist<pairintarray>(); int[] unodeedgeidx = new int[img.getwidth() * img.getheight()]; arrays.fill(unodeedgeidx, -1); while (!stack.isempty()) { pairint unode = stack.pop(); int ux = unode.getx(); int uy = unode.gety(); int uidx = (uy * img.getwidth()) + ux; boolean foundneighbor = false; for (int vx = (ux - 1); vx < (ux + 2); vx++) { if (foundneighbor) { break; } if (vx < 0 || vx > (img.getwidth() - 1)) { continue; } for (int vy = (uy - 1); vy < (uy + 2); vy++) { if (vy < 0 || vy > (img.getheight() - 1)) { continue; } int vidx = (vy * img.getwidth()) + vx; if (unodeedgeidx[vidx] != -1 || (uidx == vidx)) { continue; } if (img.getvalue(vx, vy) < thresh0) { continue; } if (unodeedgeidx[uidx] == -1) { pairintarray edge = new pairintarray(); edge.add(ux, uy); unodeedgeidx[uidx] = output.size(); output.add(edge); } pairintarray appendtonode = output.get(unodeedgeidx[uidx]); int aidx = appendtonode.getn() - 1; if ((appendtonode.getx(aidx) != ux) || (appendtonode.gety(aidx) != uy)) { continue; } appendtonode.add(vx, vy); unodeedgeidx[vidx] = unodeedgeidx[uidx]; stack.add(new pairint(vx, vy)); foundneighbor = true; break; } } } log.fine(output.size() + " edges after dfs"); int nitermax = 100; int n, sz, lastsize; long sum = countpixelsinedges(output); log.log(level.fine, "==> {0} pixels are in edges out of {1} pixels > threshhold", new object[]{long.tostring(sum), long.tostring(numberofpixelsabovethreshold)}); log.log(level.fine, "there are {0} edges", integer.tostring(output.size())); output = mergeadjacentendpoints(output); log.log(level.fine, "{0} edges after merge adjacent", integer.tostring(output.size())); output = connectclosestpointsifcantrim(output); log.fine(output.size() + " edges after connect closest"); output = fillingaps(output); log.log(level.fine, "{0} edges after fill in gaps", new object[]{integer.tostring(output.size())}); removeedgesshorterthan(output, edgesizelowerlimit); sz = output.size(); log.log(level.fine, "{0} edges after removing those shorter", new object[]{integer.tostring(sz)}); long sum2 = countpixelsinedges(output); log.log(level.fine, "==> {0}) pixels are in edges out of {1} pixels > threshhold", new object[]{long.tostring(sum2), long.tostring(numberofpixelsabovethreshold)}); adjustedgestowardsbrightpixels(output); return output; } | dukson/curvature-scale-space-corners-and-transformations | [
1,
0,
0,
0
] |
22,779 | public void fillPath(DirectionRobot robot, int endX, int endY) {
int width = robot.getX() - endX;
int height = robot.getY() - endY;
//todo refactor logic
//select direction
AbstractRobot.Direction abstractDirection = robot.getDirection();
System.out.println("first!");
if (width < 0) {
//start on the left side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateRightComand(robot));
}
break;
case LEFT: {
this.addComand(new RotateRightComand(robot));
this.addComand(new RotateRightComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.RIGHT;
}
if (width > 0) {
//start on the right side
switch (abstractDirection) {
case UP: {
this.addComand(new RotateLeftComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
//move X
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
//select direction again
if (height < 0) {
//if start above end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
// abstractDirection = AbstractRobot.Direction.DOWN;
}
if (height > 0) {
//if start below end
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot)); //done
}
break;
}
// abstractDirection = AbstractRobot.Direction.UP;
}
//move Y
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} | public void fillPath(DirectionRobot robot, int endX, int endY) {
int width = robot.getX() - endX;
int height = robot.getY() - endY;
AbstractRobot.Direction abstractDirection = robot.getDirection();
System.out.println("first!");
if (width < 0) {
switch (abstractDirection) {
case UP: {
this.addComand(new RotateRightComand(robot));
}
break;
case LEFT: {
this.addComand(new RotateRightComand(robot));
this.addComand(new RotateRightComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.RIGHT;
}
if (width > 0) {
switch (abstractDirection) {
case UP: {
this.addComand(new RotateLeftComand(robot));
}
break;
case DOWN: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
this.addComand(new RotateLeftComand(robot));
}
break;
}
abstractDirection = AbstractRobot.Direction.LEFT;
}
System.out.println(width);
for (int i = 0; i < abs(width); i++) {
this.addComand(new MoveForwardComand(robot));
}
if (height < 0) {
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateLeftComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateRightComand(robot));
}
break;
}
}
if (height > 0) {
switch (abstractDirection) {
case LEFT: {
this.addComand(new RotateRightComand(robot));
}
break;
case RIGHT: {
this.addComand(new RotateLeftComand(robot));
}
break;
}
}
System.out.println(height);
for (int i = 0; i < abs(height); i++) {
this.addComand(new MoveForwardComand(robot));
}
} | public void fillpath(directionrobot robot, int endx, int endy) { int width = robot.getx() - endx; int height = robot.gety() - endy; abstractrobot.direction abstractdirection = robot.getdirection(); system.out.println("first!"); if (width < 0) { switch (abstractdirection) { case up: { this.addcomand(new rotaterightcomand(robot)); } break; case left: { this.addcomand(new rotaterightcomand(robot)); this.addcomand(new rotaterightcomand(robot)); } break; case down: { this.addcomand(new rotateleftcomand(robot)); } break; } abstractdirection = abstractrobot.direction.right; } if (width > 0) { switch (abstractdirection) { case up: { this.addcomand(new rotateleftcomand(robot)); } break; case down: { this.addcomand(new rotaterightcomand(robot)); } break; case right: { this.addcomand(new rotateleftcomand(robot)); this.addcomand(new rotateleftcomand(robot)); } break; } abstractdirection = abstractrobot.direction.left; } system.out.println(width); for (int i = 0; i < abs(width); i++) { this.addcomand(new moveforwardcomand(robot)); } if (height < 0) { switch (abstractdirection) { case left: { this.addcomand(new rotateleftcomand(robot)); } break; case right: { this.addcomand(new rotaterightcomand(robot)); } break; } } if (height > 0) { switch (abstractdirection) { case left: { this.addcomand(new rotaterightcomand(robot)); } break; case right: { this.addcomand(new rotateleftcomand(robot)); } break; } } system.out.println(height); for (int i = 0; i < abs(height); i++) { this.addcomand(new moveforwardcomand(robot)); } } | defoltbmd/SimpleRobot | [
1,
0,
0,
0
] |
14,669 | public Dimension preferredLayoutSize(Container parent)
{
/* Sync the (now obsolete) policy fields with the
* JScrollPane.
*/
JScrollPane scrollPane = (JScrollPane)parent;
vsbPolicy = scrollPane.getVerticalScrollBarPolicy();
hsbPolicy = scrollPane.getHorizontalScrollBarPolicy();
Insets insets = parent.getInsets();
int prefWidth = insets.left + insets.right;
int prefHeight = insets.top + insets.bottom;
/* Note that viewport.getViewSize() is equivalent to
* viewport.getView().getPreferredSize() modulo a null
* view or a view whose size was explicitly set.
*/
Dimension extentSize = null;
Dimension viewSize = null;
Component view = null;
if (viewport != null) {
extentSize = viewport.getPreferredSize();
//Bug fix: always use the preferred size for the client.
//viewSize = viewport.getViewSize();
viewSize = viewport.getView().getPreferredSize();
view = viewport.getView();
}
/* If there's a viewport add its preferredSize.
*/
if (extentSize != null) {
prefWidth += extentSize.width;
prefHeight += extentSize.height;
}
/* If there's a JScrollPane.viewportBorder, add its insets.
*/
Border viewportBorder = scrollPane.getViewportBorder();
if (viewportBorder != null) {
Insets vpbInsets = viewportBorder.getBorderInsets(parent);
prefWidth += vpbInsets.left + vpbInsets.right;
prefHeight += vpbInsets.top + vpbInsets.bottom;
}
/* If a header exists and it's visible, factor its
* preferred size in.
*/
if ((rowHead != null) && rowHead.isVisible()) {
prefWidth += rowHead.getPreferredSize().width;
}
if ((colHead != null) && colHead.isVisible()) {
prefHeight += colHead.getPreferredSize().height;
}
/* If a scrollbar is going to appear, factor its preferred size in.
* If the scrollbars policy is AS_NEEDED, this can be a little
* tricky:
*
* - If the view is a Scrollable then scrollableTracksViewportWidth
* and scrollableTracksViewportHeight can be used to effectively
* disable scrolling (if they're true) in their respective dimensions.
*
* - Assuming that a scrollbar hasn't been disabled by the
* previous constraint, we need to decide if the scrollbar is going
* to appear to correctly compute the JScrollPanes preferred size.
* To do this we compare the preferredSize of the viewport (the
* extentSize) to the preferredSize of the view. Although we're
* not responsible for laying out the view we'll assume that the
* JViewport will always give it its preferredSize.
*/
if ((vsb != null) && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) {
prefWidth += vsb.getPreferredSize().width;
}
else if ((viewSize != null) && (extentSize != null)) {
boolean canScroll = true;
if (view instanceof Scrollable) {
canScroll = !((Scrollable)view).getScrollableTracksViewportHeight();
}
if (canScroll && (viewSize.height > extentSize.height)) {
prefWidth += vsb.getPreferredSize().width;
}
}
}
if ((hsb != null) && (hsbPolicy != HORIZONTAL_SCROLLBAR_NEVER)) {
if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) {
prefHeight += hsb.getPreferredSize().height;
}
else if ((viewSize != null) && (extentSize != null)) {
boolean canScroll = true;
if (view instanceof Scrollable) {
canScroll = !((Scrollable)view).getScrollableTracksViewportWidth();
}
if (canScroll && (viewSize.width > extentSize.width)) {
prefHeight += hsb.getPreferredSize().height;
}
}
}
Dimension dim = new Dimension(prefWidth, prefHeight);
return dim;
} | public Dimension preferredLayoutSize(Container parent)
{
JScrollPane scrollPane = (JScrollPane)parent;
vsbPolicy = scrollPane.getVerticalScrollBarPolicy();
hsbPolicy = scrollPane.getHorizontalScrollBarPolicy();
Insets insets = parent.getInsets();
int prefWidth = insets.left + insets.right;
int prefHeight = insets.top + insets.bottom;
Dimension extentSize = null;
Dimension viewSize = null;
Component view = null;
if (viewport != null) {
extentSize = viewport.getPreferredSize();
viewSize = viewport.getView().getPreferredSize();
view = viewport.getView();
}
if (extentSize != null) {
prefWidth += extentSize.width;
prefHeight += extentSize.height;
}
Border viewportBorder = scrollPane.getViewportBorder();
if (viewportBorder != null) {
Insets vpbInsets = viewportBorder.getBorderInsets(parent);
prefWidth += vpbInsets.left + vpbInsets.right;
prefHeight += vpbInsets.top + vpbInsets.bottom;
}
if ((rowHead != null) && rowHead.isVisible()) {
prefWidth += rowHead.getPreferredSize().width;
}
if ((colHead != null) && colHead.isVisible()) {
prefHeight += colHead.getPreferredSize().height;
}
if ((vsb != null) && (vsbPolicy != VERTICAL_SCROLLBAR_NEVER)) {
if (vsbPolicy == VERTICAL_SCROLLBAR_ALWAYS) {
prefWidth += vsb.getPreferredSize().width;
}
else if ((viewSize != null) && (extentSize != null)) {
boolean canScroll = true;
if (view instanceof Scrollable) {
canScroll = !((Scrollable)view).getScrollableTracksViewportHeight();
}
if (canScroll && (viewSize.height > extentSize.height)) {
prefWidth += vsb.getPreferredSize().width;
}
}
}
if ((hsb != null) && (hsbPolicy != HORIZONTAL_SCROLLBAR_NEVER)) {
if (hsbPolicy == HORIZONTAL_SCROLLBAR_ALWAYS) {
prefHeight += hsb.getPreferredSize().height;
}
else if ((viewSize != null) && (extentSize != null)) {
boolean canScroll = true;
if (view instanceof Scrollable) {
canScroll = !((Scrollable)view).getScrollableTracksViewportWidth();
}
if (canScroll && (viewSize.width > extentSize.width)) {
prefHeight += hsb.getPreferredSize().height;
}
}
}
Dimension dim = new Dimension(prefWidth, prefHeight);
return dim;
} | public dimension preferredlayoutsize(container parent) { jscrollpane scrollpane = (jscrollpane)parent; vsbpolicy = scrollpane.getverticalscrollbarpolicy(); hsbpolicy = scrollpane.gethorizontalscrollbarpolicy(); insets insets = parent.getinsets(); int prefwidth = insets.left + insets.right; int prefheight = insets.top + insets.bottom; dimension extentsize = null; dimension viewsize = null; component view = null; if (viewport != null) { extentsize = viewport.getpreferredsize(); viewsize = viewport.getview().getpreferredsize(); view = viewport.getview(); } if (extentsize != null) { prefwidth += extentsize.width; prefheight += extentsize.height; } border viewportborder = scrollpane.getviewportborder(); if (viewportborder != null) { insets vpbinsets = viewportborder.getborderinsets(parent); prefwidth += vpbinsets.left + vpbinsets.right; prefheight += vpbinsets.top + vpbinsets.bottom; } if ((rowhead != null) && rowhead.isvisible()) { prefwidth += rowhead.getpreferredsize().width; } if ((colhead != null) && colhead.isvisible()) { prefheight += colhead.getpreferredsize().height; } if ((vsb != null) && (vsbpolicy != vertical_scrollbar_never)) { if (vsbpolicy == vertical_scrollbar_always) { prefwidth += vsb.getpreferredsize().width; } else if ((viewsize != null) && (extentsize != null)) { boolean canscroll = true; if (view instanceof scrollable) { canscroll = !((scrollable)view).getscrollabletracksviewportheight(); } if (canscroll && (viewsize.height > extentsize.height)) { prefwidth += vsb.getpreferredsize().width; } } } if ((hsb != null) && (hsbpolicy != horizontal_scrollbar_never)) { if (hsbpolicy == horizontal_scrollbar_always) { prefheight += hsb.getpreferredsize().height; } else if ((viewsize != null) && (extentsize != null)) { boolean canscroll = true; if (view instanceof scrollable) { canscroll = !((scrollable)view).getscrollabletracksviewportwidth(); } if (canscroll && (viewsize.width > extentsize.width)) { prefheight += hsb.getpreferredsize().height; } } } dimension dim = new dimension(prefwidth, prefheight); return dim; } | dannyhx/artisynth_core | [
0,
0,
1,
0
] |
31,217 | @Override
protected Void doInBackground(String... args) {
if (isCancelled()) {
return null;
}
// TODO subscribe to network events instead of using this
if (!networkAvailable) {
Toast.makeText(
context,
getString(R.string.toast_nonetwork),
Toast.LENGTH_LONG).show();
} else {
// TODO remove this but with caution
updateUIBean = new UpdateUIBean();
// TODO to test different configs change the files poiting by CONFIG_FILE
// avoid changing the code directly
Config.readConfigFile(ReplayConstants.CONFIG_FILE, context);
SharedPreferences sharedPrefs =
PreferenceManager.getDefaultSharedPreferences(context);
try {
// metadata here is user's network type device used geolocation if permitted etc
// Google storage forbids to store user related data
// So we send that data to a private server
server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi");
metadataServer = "wehe-metadata.meddle.mobi";
// We first resolve the IP of the server and then communicate with the server
// Using IP only, because we have multiple server under same domain and we want
// the client not to switch server during a test run
// TODO come up with a better way to handle Inet related queries, since this
// introduced inefficiency
final InetAddress[] address = {null, null};
new Thread() {
public void run() {
while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) {
try {
server = InetAddress.getByName(server).getHostAddress();
address[0] = InetAddress.getByName(server);
} catch (UnknownHostException e) {
Log.w("GetReplayServerIP", "get IP of replay server failed!");
e.printStackTrace();
}
}
}
}.start();
new Thread() {
public void run() {
while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) {
try {
metadataServer = InetAddress.getByName(metadataServer).getHostAddress();
address[1] = InetAddress.getByName(metadataServer);
} catch (UnknownHostException e) {
Log.w("GetReplayServerIP", "get IP of replay server failed!");
e.printStackTrace();
}
}
}
}.start();
int maxWaitTime = 5000;
int currentWaitTime = 500;
while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)
&& !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) {
try {
if (currentWaitTime <= maxWaitTime) {
Thread.sleep(currentWaitTime);
currentWaitTime += 500;
} else {
Toast.makeText(context, R.string.server_unavailable,
Toast.LENGTH_LONG).show();
return null;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (address[0] instanceof Inet6Address)
server = "[" + server + "]";
if (address[1] instanceof Inet6Address)
metadataServer = "[" + metadataServer + "]";
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate ca;
try (InputStream caInput = getResources().openRawResource(R.raw.main)) {
ca = cf.generateCertificate(caInput);
System.out.println("main=" + ((X509Certificate) ca).getIssuerDN());
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("main", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
sslSocketFactory = context.getSocketFactory();
hostnameVerifier = (hostname, session) -> true;
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate ca;
try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) {
ca = cf.generateCertificate(caInput);
System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN());
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("metadata", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
metadataSocketFactory = context.getSocketFactory();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("GetReplayServerIP", "Server IP: " + server);
} catch (NullPointerException e) {
e.printStackTrace();
Log.w("GetReplayServerIP", "Invalid IP address!");
}
// Extract data that was sent by previous activity. In our case, list of
// apps, server and timing
enableTiming = "true";
doTest = false;
int port = Integer.valueOf(Config.get("result_port"));
analyzerServerUrl = ("https://" + server + ":" + port + "/Results");
date = new Date();
results = new JSONArray();
Log.d("Result Channel",
"path: " + server + " port: " + port);
confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true);
// generate or retrieve an id for this phone
boolean hasID = sharedPrefs.getBoolean("hasID", false);
if (!hasID) {
randomID = new RandomString(10).nextString();
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putBoolean("hasID", true);
editor.putString("ID", randomID);
editor.apply();
} else {
randomID = sharedPrefs.getString("ID", null);
}
a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10")));
ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5")));
confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true);
// to get historyCount
settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE);
// generate or retrieve an historyCount for this phone
boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false);
if (!hasHistoryCount) {
historyCount = 0;
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("hasHistoryCount", true);
editor.putInt("historyCount", historyCount);
editor.apply();
} else {
historyCount = settings.getInt("historyCount", -1);
}
// check if retrieve historyCount succeeded
if (historyCount == -1)
throw new RuntimeException();
Config.set("timing", enableTiming);
// make sure server is initialized!
while (server == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Config.set("server", server);
Config.set("jitter", "true");
Config.set("publicIP", "");
new Thread(new Runnable() {
public void run() {
Config.set("publicIP", getPublicIP("80"));
}
}).start();
// Find a way to switch to no wait
while (Config.get("publicIP").equals("")) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.d("Replay", "public IP: " + Config.get("publicIP"));
}
for (ApplicationBean app : selectedApps) {
rerun = false;
// Set the app to run test for
this.app = app;
// Run the test on this.app
runTest();
}
// Keep checking if the user exited from ReplayActivity or not
// TODO find a better way stop the tests immediately without continues checking
if (isCancelled()) {
return null;
}
if (results.length() > 0) {
Log.d("Result Channel", "Storing results");
saveResults();
}
if (isCancelled()) {
return null;
}
showFinishDialog();
Log.d("Result Channel", "Exiting normally");
return null;
} | @Override
protected Void doInBackground(String... args) {
if (isCancelled()) {
return null;
}
if (!networkAvailable) {
Toast.makeText(
context,
getString(R.string.toast_nonetwork),
Toast.LENGTH_LONG).show();
} else {
updateUIBean = new UpdateUIBean();
Config.readConfigFile(ReplayConstants.CONFIG_FILE, context);
SharedPreferences sharedPrefs =
PreferenceManager.getDefaultSharedPreferences(context);
try {
server = sharedPrefs.getString("pref_server", "wehe2.meddle.mobi");
metadataServer = "wehe-metadata.meddle.mobi";
final InetAddress[] address = {null, null};
new Thread() {
public void run() {
while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)) {
try {
server = InetAddress.getByName(server).getHostAddress();
address[0] = InetAddress.getByName(server);
} catch (UnknownHostException e) {
Log.w("GetReplayServerIP", "get IP of replay server failed!");
e.printStackTrace();
}
}
}
}.start();
new Thread() {
public void run() {
while (!(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) {
try {
metadataServer = InetAddress.getByName(metadataServer).getHostAddress();
address[1] = InetAddress.getByName(metadataServer);
} catch (UnknownHostException e) {
Log.w("GetReplayServerIP", "get IP of replay server failed!");
e.printStackTrace();
}
}
}
}.start();
int maxWaitTime = 5000;
int currentWaitTime = 500;
while (!(address[0] instanceof Inet4Address || address[0] instanceof Inet6Address)
&& !(address[1] instanceof Inet4Address || address[1] instanceof Inet6Address)) {
try {
if (currentWaitTime <= maxWaitTime) {
Thread.sleep(currentWaitTime);
currentWaitTime += 500;
} else {
Toast.makeText(context, R.string.server_unavailable,
Toast.LENGTH_LONG).show();
return null;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (address[0] instanceof Inet6Address)
server = "[" + server + "]";
if (address[1] instanceof Inet6Address)
metadataServer = "[" + metadataServer + "]";
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate ca;
try (InputStream caInput = getResources().openRawResource(R.raw.main)) {
ca = cf.generateCertificate(caInput);
System.out.println("main=" + ((X509Certificate) ca).getIssuerDN());
}
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("main", ca);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
sslSocketFactory = context.getSocketFactory();
hostnameVerifier = (hostname, session) -> true;
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate ca;
try (InputStream caInput = getResources().openRawResource(R.raw.metadata)) {
ca = cf.generateCertificate(caInput);
System.out.println("metadata=" + ((X509Certificate) ca).getIssuerDN());
}
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("metadata", ca);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
metadataSocketFactory = context.getSocketFactory();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("GetReplayServerIP", "Server IP: " + server);
} catch (NullPointerException e) {
e.printStackTrace();
Log.w("GetReplayServerIP", "Invalid IP address!");
}
enableTiming = "true";
doTest = false;
int port = Integer.valueOf(Config.get("result_port"));
analyzerServerUrl = ("https://" + server + ":" + port + "/Results");
date = new Date();
results = new JSONArray();
Log.d("Result Channel",
"path: " + server + " port: " + port);
confirmationReplays = sharedPrefs.getBoolean("confirmationReplays", true);
boolean hasID = sharedPrefs.getBoolean("hasID", false);
if (!hasID) {
randomID = new RandomString(10).nextString();
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putBoolean("hasID", true);
editor.putString("ID", randomID);
editor.apply();
} else {
randomID = sharedPrefs.getString("ID", null);
}
a_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_area", "10")));
ks2pvalue_threshold = Integer.parseInt(Objects.requireNonNull(sharedPrefs.getString("pref_threshold_ks2p", "5")));
confirmationReplays = sharedPrefs.getBoolean("pref_multiple_tests", true);
settings = getSharedPreferences(STATUS, Context.MODE_PRIVATE);
boolean hasHistoryCount = settings.getBoolean("hasHistoryCount", false);
if (!hasHistoryCount) {
historyCount = 0;
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("hasHistoryCount", true);
editor.putInt("historyCount", historyCount);
editor.apply();
} else {
historyCount = settings.getInt("historyCount", -1);
}
if (historyCount == -1)
throw new RuntimeException();
Config.set("timing", enableTiming);
while (server == null) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Config.set("server", server);
Config.set("jitter", "true");
Config.set("publicIP", "");
new Thread(new Runnable() {
public void run() {
Config.set("publicIP", getPublicIP("80"));
}
}).start();
while (Config.get("publicIP").equals("")) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.d("Replay", "public IP: " + Config.get("publicIP"));
}
for (ApplicationBean app : selectedApps) {
rerun = false;
this.app = app;
runTest();
}
if (isCancelled()) {
return null;
}
if (results.length() > 0) {
Log.d("Result Channel", "Storing results");
saveResults();
}
if (isCancelled()) {
return null;
}
showFinishDialog();
Log.d("Result Channel", "Exiting normally");
return null;
} | @override protected void doinbackground(string... args) { if (iscancelled()) { return null; } if (!networkavailable) { toast.maketext( context, getstring(r.string.toast_nonetwork), toast.length_long).show(); } else { updateuibean = new updateuibean(); config.readconfigfile(replayconstants.config_file, context); sharedpreferences sharedprefs = preferencemanager.getdefaultsharedpreferences(context); try { server = sharedprefs.getstring("pref_server", "wehe2.meddle.mobi"); metadataserver = "wehe-metadata.meddle.mobi"; final inetaddress[] address = {null, null}; new thread() { public void run() { while (!(address[0] instanceof inet4address || address[0] instanceof inet6address)) { try { server = inetaddress.getbyname(server).gethostaddress(); address[0] = inetaddress.getbyname(server); } catch (unknownhostexception e) { log.w("getreplayserverip", "get ip of replay server failed!"); e.printstacktrace(); } } } }.start(); new thread() { public void run() { while (!(address[1] instanceof inet4address || address[1] instanceof inet6address)) { try { metadataserver = inetaddress.getbyname(metadataserver).gethostaddress(); address[1] = inetaddress.getbyname(metadataserver); } catch (unknownhostexception e) { log.w("getreplayserverip", "get ip of replay server failed!"); e.printstacktrace(); } } } }.start(); int maxwaittime = 5000; int currentwaittime = 500; while (!(address[0] instanceof inet4address || address[0] instanceof inet6address) && !(address[1] instanceof inet4address || address[1] instanceof inet6address)) { try { if (currentwaittime <= maxwaittime) { thread.sleep(currentwaittime); currentwaittime += 500; } else { toast.maketext(context, r.string.server_unavailable, toast.length_long).show(); return null; } } catch (interruptedexception e) { e.printstacktrace(); } } if (address[0] instanceof inet6address) server = "[" + server + "]"; if (address[1] instanceof inet6address) metadataserver = "[" + metadataserver + "]"; try { certificatefactory cf = certificatefactory.getinstance("x.509"); certificate ca; try (inputstream cainput = getresources().openrawresource(r.raw.main)) { ca = cf.generatecertificate(cainput); system.out.println("main=" + ((x509certificate) ca).getissuerdn()); } string keystoretype = keystore.getdefaulttype(); keystore keystore = keystore.getinstance(keystoretype); keystore.load(null, null); keystore.setcertificateentry("main", ca); string tmfalgorithm = trustmanagerfactory.getdefaultalgorithm(); trustmanagerfactory tmf = trustmanagerfactory.getinstance(tmfalgorithm); tmf.init(keystore); sslcontext context = sslcontext.getinstance("tls"); context.init(null, tmf.gettrustmanagers(), null); sslsocketfactory = context.getsocketfactory(); hostnameverifier = (hostname, session) -> true; } catch (certificateexception e) { e.printstacktrace(); } catch (nosuchalgorithmexception e) { e.printstacktrace(); } catch (keystoreexception e) { e.printstacktrace(); } catch (keymanagementexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } try { certificatefactory cf = certificatefactory.getinstance("x.509"); certificate ca; try (inputstream cainput = getresources().openrawresource(r.raw.metadata)) { ca = cf.generatecertificate(cainput); system.out.println("metadata=" + ((x509certificate) ca).getissuerdn()); } string keystoretype = keystore.getdefaulttype(); keystore keystore = keystore.getinstance(keystoretype); keystore.load(null, null); keystore.setcertificateentry("metadata", ca); string tmfalgorithm = trustmanagerfactory.getdefaultalgorithm(); trustmanagerfactory tmf = trustmanagerfactory.getinstance(tmfalgorithm); tmf.init(keystore); sslcontext context = sslcontext.getinstance("tls"); context.init(null, tmf.gettrustmanagers(), null); metadatasocketfactory = context.getsocketfactory(); } catch (certificateexception e) { e.printstacktrace(); } catch (nosuchalgorithmexception e) { e.printstacktrace(); } catch (keystoreexception e) { e.printstacktrace(); } catch (keymanagementexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } log.d("getreplayserverip", "server ip: " + server); } catch (nullpointerexception e) { e.printstacktrace(); log.w("getreplayserverip", "invalid ip address!"); } enabletiming = "true"; dotest = false; int port = integer.valueof(config.get("result_port")); analyzerserverurl = ("https://" + server + ":" + port + "/results"); date = new date(); results = new jsonarray(); log.d("result channel", "path: " + server + " port: " + port); confirmationreplays = sharedprefs.getboolean("confirmationreplays", true); boolean hasid = sharedprefs.getboolean("hasid", false); if (!hasid) { randomid = new randomstring(10).nextstring(); sharedpreferences.editor editor = sharedprefs.edit(); editor.putboolean("hasid", true); editor.putstring("id", randomid); editor.apply(); } else { randomid = sharedprefs.getstring("id", null); } a_threshold = integer.parseint(objects.requirenonnull(sharedprefs.getstring("pref_threshold_area", "10"))); ks2pvalue_threshold = integer.parseint(objects.requirenonnull(sharedprefs.getstring("pref_threshold_ks2p", "5"))); confirmationreplays = sharedprefs.getboolean("pref_multiple_tests", true); settings = getsharedpreferences(status, context.mode_private); boolean hashistorycount = settings.getboolean("hashistorycount", false); if (!hashistorycount) { historycount = 0; sharedpreferences.editor editor = settings.edit(); editor.putboolean("hashistorycount", true); editor.putint("historycount", historycount); editor.apply(); } else { historycount = settings.getint("historycount", -1); } if (historycount == -1) throw new runtimeexception(); config.set("timing", enabletiming); while (server == null) { try { thread.sleep(1000); } catch (interruptedexception e) { e.printstacktrace(); } } config.set("server", server); config.set("jitter", "true"); config.set("publicip", ""); new thread(new runnable() { public void run() { config.set("publicip", getpublicip("80")); } }).start(); while (config.get("publicip").equals("")) { try { thread.sleep(500); } catch (interruptedexception e) { e.printstacktrace(); } } log.d("replay", "public ip: " + config.get("publicip")); } for (applicationbean app : selectedapps) { rerun = false; this.app = app; runtest(); } if (iscancelled()) { return null; } if (results.length() > 0) { log.d("result channel", "storing results"); saveresults(); } if (iscancelled()) { return null; } showfinishdialog(); log.d("result channel", "exiting normally"); return null; } | dng24/wehe-android | [
1,
1,
0,
1
] |
23,038 | @Override
public void resetToPreferredSizes() {
Insets i = getInsets();
if (getOrientation() == VERTICAL_SPLIT) {
int h = getHeight() - i.top - i.bottom - getDividerSize();
int topH = getTopComponent().getPreferredSize().height;
int bottomH = getBottomComponent().getPreferredSize().height;
int extraSpace = h - topH - bottomH;
// we have more space than necessary; resize to give each at least
// preferred size
if (extraSpace >= 0) {
setDividerLocation(i.top + topH
+ ((int) (extraSpace * getResizeWeight() + .5)));
}
// TODO implement shrinking excess space to ensure that one has
// preferred and nothing more
} else {
int w = getWidth() - i.left - i.right - getDividerSize();
int leftH = getLeftComponent().getPreferredSize().width;
int rightH = getRightComponent().getPreferredSize().width;
int extraSpace = w - leftH - rightH;
// we have more space than necessary; resize to give each at least
// preferred size
if (extraSpace >= 0) {
setDividerLocation(i.left + leftH
+ ((int) (extraSpace * getResizeWeight() + .5)));
}
// TODO implement shrinking excess space to ensure that one has
// preferred and nothing more
}
} | @Override
public void resetToPreferredSizes() {
Insets i = getInsets();
if (getOrientation() == VERTICAL_SPLIT) {
int h = getHeight() - i.top - i.bottom - getDividerSize();
int topH = getTopComponent().getPreferredSize().height;
int bottomH = getBottomComponent().getPreferredSize().height;
int extraSpace = h - topH - bottomH;
if (extraSpace >= 0) {
setDividerLocation(i.top + topH
+ ((int) (extraSpace * getResizeWeight() + .5)));
}
} else {
int w = getWidth() - i.left - i.right - getDividerSize();
int leftH = getLeftComponent().getPreferredSize().width;
int rightH = getRightComponent().getPreferredSize().width;
int extraSpace = w - leftH - rightH;
if (extraSpace >= 0) {
setDividerLocation(i.left + leftH
+ ((int) (extraSpace * getResizeWeight() + .5)));
}
}
} | @override public void resettopreferredsizes() { insets i = getinsets(); if (getorientation() == vertical_split) { int h = getheight() - i.top - i.bottom - getdividersize(); int toph = gettopcomponent().getpreferredsize().height; int bottomh = getbottomcomponent().getpreferredsize().height; int extraspace = h - toph - bottomh; if (extraspace >= 0) { setdividerlocation(i.top + toph + ((int) (extraspace * getresizeweight() + .5))); } } else { int w = getwidth() - i.left - i.right - getdividersize(); int lefth = getleftcomponent().getpreferredsize().width; int righth = getrightcomponent().getpreferredsize().width; int extraspace = w - lefth - righth; if (extraspace >= 0) { setdividerlocation(i.left + lefth + ((int) (extraspace * getresizeweight() + .5))); } } } | g-pechorin/flexdock | [
0,
1,
0,
0
] |
23,040 | @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// Update each of the widgets with the remote adapter
for (int i = 0; i < appWidgetIds.length; ++i) {
RemoteViews layout = buildLayout(context, appWidgetIds[i]);
appWidgetManager.updateAppWidget(appWidgetIds[i], layout);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
// wtf another google bug?
this.onEnabled(context);
} | @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int i = 0; i < appWidgetIds.length; ++i) {
RemoteViews layout = buildLayout(context, appWidgetIds[i]);
appWidgetManager.updateAppWidget(appWidgetIds[i], layout);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
this.onEnabled(context);
} | @override public void onupdate(context context, appwidgetmanager appwidgetmanager, int[] appwidgetids) { for (int i = 0; i < appwidgetids.length; ++i) { remoteviews layout = buildlayout(context, appwidgetids[i]); appwidgetmanager.updateappwidget(appwidgetids[i], layout); } super.onupdate(context, appwidgetmanager, appwidgetids); this.onenabled(context); } | ekux44/LampShade | [
0,
0,
1,
0
] |
14,870 | private void onApnChanged() {
DctConstants.State overallState = getOverallState();
boolean isDisconnected = (overallState == DctConstants.State.IDLE ||
overallState == DctConstants.State.FAILED);
if (mPhone instanceof GSMPhone) {
// The "current" may no longer be valid. MMS depends on this to send properly. TBD
((GSMPhone)mPhone).updateCurrentCarrierInProvider();
}
// TODO: It'd be nice to only do this if the changed entrie(s)
// match the current operator.
if (DBG) log("onApnChanged: createAllApnList and cleanUpAllConnections");
createAllApnList();
setInitialAttachApn();
cleanUpAllConnections(!isDisconnected, Phone.REASON_APN_CHANGED);
if (isDisconnected) {
setupDataOnConnectableApns(Phone.REASON_APN_CHANGED);
}
} | private void onApnChanged() {
DctConstants.State overallState = getOverallState();
boolean isDisconnected = (overallState == DctConstants.State.IDLE ||
overallState == DctConstants.State.FAILED);
if (mPhone instanceof GSMPhone) {
((GSMPhone)mPhone).updateCurrentCarrierInProvider();
}
if (DBG) log("onApnChanged: createAllApnList and cleanUpAllConnections");
createAllApnList();
setInitialAttachApn();
cleanUpAllConnections(!isDisconnected, Phone.REASON_APN_CHANGED);
if (isDisconnected) {
setupDataOnConnectableApns(Phone.REASON_APN_CHANGED);
}
} | private void onapnchanged() { dctconstants.state overallstate = getoverallstate(); boolean isdisconnected = (overallstate == dctconstants.state.idle || overallstate == dctconstants.state.failed); if (mphone instanceof gsmphone) { ((gsmphone)mphone).updatecurrentcarrierinprovider(); } if (dbg) log("onapnchanged: createallapnlist and cleanupallconnections"); createallapnlist(); setinitialattachapn(); cleanupallconnections(!isdisconnected, phone.reason_apn_changed); if (isdisconnected) { setupdataonconnectableapns(phone.reason_apn_changed); } } | efortuna/AndroidSDKClone | [
1,
0,
0,
0
] |
14,914 | public static Class<?> getRawType(Type type) {
if (type instanceof Class<?>) {
// type is a normal class.
return (Class<?>)type;
}
else if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType)type;
// I'm not exactly sure why getRawType() returns Type instead of Class.
// Neal isn't either but suspects some pathological case related
// to nested classes exists.
Type rawType = parameterizedType.getRawType();
Asserts.isTrue(rawType instanceof Class);
return (Class<?>)rawType;
}
else if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType)type).getGenericComponentType();
return Array.newInstance(getRawType(componentType), 0).getClass();
}
else if (type instanceof TypeVariable) {
// we could use the variable's bounds, but that won't work if there are multiple.
// having a raw type that's more general than necessary is okay
return Object.class;
}
else if (type instanceof WildcardType) {
return getRawType(((WildcardType)type).getUpperBounds()[0]);
}
else {
String className = type == null ? "null" : type.getClass().getName();
throw new IllegalArgumentException("Expected a Class, ParameterizedType, or "
+ "GenericArrayType, but <" + type + "> is of type " + className);
}
} | public static Class<?> getRawType(Type type) {
if (type instanceof Class<?>) {
return (Class<?>)type;
}
else if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType)type;
Type rawType = parameterizedType.getRawType();
Asserts.isTrue(rawType instanceof Class);
return (Class<?>)rawType;
}
else if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType)type).getGenericComponentType();
return Array.newInstance(getRawType(componentType), 0).getClass();
}
else if (type instanceof TypeVariable) {
return Object.class;
}
else if (type instanceof WildcardType) {
return getRawType(((WildcardType)type).getUpperBounds()[0]);
}
else {
String className = type == null ? "null" : type.getClass().getName();
throw new IllegalArgumentException("Expected a Class, ParameterizedType, or "
+ "GenericArrayType, but <" + type + "> is of type " + className);
}
} | public static class<?> getrawtype(type type) { if (type instanceof class<?>) { return (class<?>)type; } else if (type instanceof parameterizedtype) { parameterizedtype parameterizedtype = (parameterizedtype)type; type rawtype = parameterizedtype.getrawtype(); asserts.istrue(rawtype instanceof class); return (class<?>)rawtype; } else if (type instanceof genericarraytype) { type componenttype = ((genericarraytype)type).getgenericcomponenttype(); return array.newinstance(getrawtype(componenttype), 0).getclass(); } else if (type instanceof typevariable) { return object.class; } else if (type instanceof wildcardtype) { return getrawtype(((wildcardtype)type).getupperbounds()[0]); } else { string classname = type == null ? "null" : type.getclass().getname(); throw new illegalargumentexception("expected a class, parameterizedtype, or " + "genericarraytype, but <" + type + "> is of type " + classname); } } | foolite/panda | [
1,
0,
0,
0
] |
31,546 | private void processResponseBody(List<AudioGson> audioGsons) {
Log.i(getClass().getName(), "processResponseBody");
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
@Override
public void run() {
Log.i(getClass().getName(), "run");
RoomDb roomDb = RoomDb.getDatabase(getContext());
AudioDao audioDao = roomDb.audioDao();
// Empty the database table before downloading up-to-date content
audioDao.deleteAll();
// TODO: also delete corresponding audio files (only those that are no longer used)
for (AudioGson audioGson : audioGsons) {
Log.i(getClass().getName(), "audioGson.getId(): " + audioGson.getId());
Audio audio = GsonToRoomConverter.getAudio(audioGson);
// Check if the corresponding audio file has already been downloaded
File audioFile = FileHelper.getAudioFile(audioGson, getContext());
Log.i(getClass().getName(), "audioFile: " + audioFile);
Log.i(getClass().getName(), "audioFile.exists(): " + audioFile.exists());
if (!audioFile.exists()) {
// Download file bytes
BaseApplication baseApplication = (BaseApplication) getActivity().getApplication();
String downloadUrl = baseApplication.getBaseUrl() + audioGson.getBytesUrl();
Log.i(getClass().getName(), "downloadUrl: " + downloadUrl);
byte[] bytes = MultimediaDownloader.downloadFileBytes(downloadUrl);
Log.i(getClass().getName(), "bytes.length: " + bytes.length);
// Store the downloaded file in the external storage directory
try {
FileOutputStream fileOutputStream = new FileOutputStream(audioFile);
fileOutputStream.write(bytes);
} catch (FileNotFoundException e) {
Log.e(getClass().getName(), null, e);
} catch (IOException e) {
Log.e(getClass().getName(), null, e);
}
Log.i(getClass().getName(), "audioFile.exists(): " + audioFile.exists());
}
// Store the Audio in the database
audioDao.insert(audio);
Log.i(getClass().getName(), "Stored Audio in database with ID " + audio.getId());
}
// Update the UI
List<Audio> audios = audioDao.loadAll();
Log.i(getClass().getName(), "audios.size(): " + audios.size());
getActivity().runOnUiThread(() -> {
textView.setText("audios.size(): " + audios.size());
Snackbar.make(textView, "audios.size(): " + audios.size(), Snackbar.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
});
}
});
} | private void processResponseBody(List<AudioGson> audioGsons) {
Log.i(getClass().getName(), "processResponseBody");
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
@Override
public void run() {
Log.i(getClass().getName(), "run");
RoomDb roomDb = RoomDb.getDatabase(getContext());
AudioDao audioDao = roomDb.audioDao();
audioDao.deleteAll();
for (AudioGson audioGson : audioGsons) {
Log.i(getClass().getName(), "audioGson.getId(): " + audioGson.getId());
Audio audio = GsonToRoomConverter.getAudio(audioGson);
File audioFile = FileHelper.getAudioFile(audioGson, getContext());
Log.i(getClass().getName(), "audioFile: " + audioFile);
Log.i(getClass().getName(), "audioFile.exists(): " + audioFile.exists());
if (!audioFile.exists()) {
BaseApplication baseApplication = (BaseApplication) getActivity().getApplication();
String downloadUrl = baseApplication.getBaseUrl() + audioGson.getBytesUrl();
Log.i(getClass().getName(), "downloadUrl: " + downloadUrl);
byte[] bytes = MultimediaDownloader.downloadFileBytes(downloadUrl);
Log.i(getClass().getName(), "bytes.length: " + bytes.length);
try {
FileOutputStream fileOutputStream = new FileOutputStream(audioFile);
fileOutputStream.write(bytes);
} catch (FileNotFoundException e) {
Log.e(getClass().getName(), null, e);
} catch (IOException e) {
Log.e(getClass().getName(), null, e);
}
Log.i(getClass().getName(), "audioFile.exists(): " + audioFile.exists());
}
audioDao.insert(audio);
Log.i(getClass().getName(), "Stored Audio in database with ID " + audio.getId());
}
List<Audio> audios = audioDao.loadAll();
Log.i(getClass().getName(), "audios.size(): " + audios.size());
getActivity().runOnUiThread(() -> {
textView.setText("audios.size(): " + audios.size());
Snackbar.make(textView, "audios.size(): " + audios.size(), Snackbar.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
});
}
});
} | private void processresponsebody(list<audiogson> audiogsons) { log.i(getclass().getname(), "processresponsebody"); executorservice executorservice = executors.newsinglethreadexecutor(); executorservice.execute(new runnable() { @override public void run() { log.i(getclass().getname(), "run"); roomdb roomdb = roomdb.getdatabase(getcontext()); audiodao audiodao = roomdb.audiodao(); audiodao.deleteall(); for (audiogson audiogson : audiogsons) { log.i(getclass().getname(), "audiogson.getid(): " + audiogson.getid()); audio audio = gsontoroomconverter.getaudio(audiogson); file audiofile = filehelper.getaudiofile(audiogson, getcontext()); log.i(getclass().getname(), "audiofile: " + audiofile); log.i(getclass().getname(), "audiofile.exists(): " + audiofile.exists()); if (!audiofile.exists()) { baseapplication baseapplication = (baseapplication) getactivity().getapplication(); string downloadurl = baseapplication.getbaseurl() + audiogson.getbytesurl(); log.i(getclass().getname(), "downloadurl: " + downloadurl); byte[] bytes = multimediadownloader.downloadfilebytes(downloadurl); log.i(getclass().getname(), "bytes.length: " + bytes.length); try { fileoutputstream fileoutputstream = new fileoutputstream(audiofile); fileoutputstream.write(bytes); } catch (filenotfoundexception e) { log.e(getclass().getname(), null, e); } catch (ioexception e) { log.e(getclass().getname(), null, e); } log.i(getclass().getname(), "audiofile.exists(): " + audiofile.exists()); } audiodao.insert(audio); log.i(getclass().getname(), "stored audio in database with id " + audio.getid()); } list<audio> audios = audiodao.loadall(); log.i(getclass().getname(), "audios.size(): " + audios.size()); getactivity().runonuithread(() -> { textview.settext("audios.size(): " + audios.size()); snackbar.make(textview, "audios.size(): " + audios.size(), snackbar.length_long).show(); progressbar.setvisibility(view.gone); }); } }); } | elimu-ai/content-provider | [
0,
1,
0,
0
] |
15,539 | @Override
protected EntityManager getEntityManager() {
return entityManager;
} | @Override
protected EntityManager getEntityManager() {
return entityManager;
} | @override protected entitymanager getentitymanager() { return entitymanager; } | dwws-ufes/2020-doeLivro | [
0,
0,
0,
0
] |
15,540 | @Override
public List<Book> getBookByTitle(String title) {
// FIXME: auto-generated method stub
return null;
} | @Override
public List<Book> getBookByTitle(String title) {
return null;
} | @override public list<book> getbookbytitle(string title) { return null; } | dwws-ufes/2020-doeLivro | [
1,
0,
0,
0
] |
15,541 | @Override
public List<Book> getBookByAuthor(String author) {
// FIXME: auto-generated method stub
return null;
} | @Override
public List<Book> getBookByAuthor(String author) {
return null;
} | @override public list<book> getbookbyauthor(string author) { return null; } | dwws-ufes/2020-doeLivro | [
0,
1,
0,
0
] |
15,542 | @Override
public List<Book> getBookList() {
// FIXME: auto-generated method stub
return null;
} | @Override
public List<Book> getBookList() {
return null;
} | @override public list<book> getbooklist() { return null; } | dwws-ufes/2020-doeLivro | [
0,
1,
0,
0
] |
31,991 | public static void doGoTo( String strQualifedType )
{
EditorUtilities.showWaitCursor( true );
try
{
IType type = TypeSystem.getByFullNameIfValid( strQualifedType );
if( type == null )
{
return;
}
IFile[] sourceFiles = type.getSourceFiles();
if( sourceFiles != null && sourceFiles.length > 0 )
{
//## todo: maybe support multiple files here?
IFile sourceFile = sourceFiles[0];
LabFrame.instance().openFile( PathUtil.create( sourceFile.toURI() ) );
}
}
catch( Exception e )
{
throw new RuntimeException( e );
}
finally
{
EditorUtilities.showWaitCursor( false );
}
} | public static void doGoTo( String strQualifedType )
{
EditorUtilities.showWaitCursor( true );
try
{
IType type = TypeSystem.getByFullNameIfValid( strQualifedType );
if( type == null )
{
return;
}
IFile[] sourceFiles = type.getSourceFiles();
if( sourceFiles != null && sourceFiles.length > 0 )
{
IFile sourceFile = sourceFiles[0];
LabFrame.instance().openFile( PathUtil.create( sourceFile.toURI() ) );
}
}
catch( Exception e )
{
throw new RuntimeException( e );
}
finally
{
EditorUtilities.showWaitCursor( false );
}
} | public static void dogoto( string strqualifedtype ) { editorutilities.showwaitcursor( true ); try { itype type = typesystem.getbyfullnameifvalid( strqualifedtype ); if( type == null ) { return; } ifile[] sourcefiles = type.getsourcefiles(); if( sourcefiles != null && sourcefiles.length > 0 ) { ifile sourcefile = sourcefiles[0]; labframe.instance().openfile( pathutil.create( sourcefile.touri() ) ); } } catch( exception e ) { throw new runtimeexception( e ); } finally { editorutilities.showwaitcursor( false ); } } | dmcreyno/gosu-lang | [
1,
0,
0,
0
] |
15,967 | public Table<Locator, String, String> getMetadataValues(Set<Locator> locators) {
ColumnFamily CF = CassandraModel.CF_METRIC_METADATA;
boolean isBatch = locators.size() > 1;
Table<Locator, String, String> metaTable = HashBasedTable.create();
Timer.Context ctx = isBatch ? Instrumentation.getBatchReadTimerContext(CF) : Instrumentation.getReadTimerContext(CF);
try {
// We don't paginate this call. So we should make sure the number of reads is tolerable.
// TODO: Think about paginating this call.
OperationResult<Rows<Locator, String>> query = keyspace
.prepareQuery(CF)
.getKeySlice(locators)
.execute();
for (Row<Locator, String> row : query.getResult()) {
ColumnList<String> columns = row.getColumns();
for (Column<String> column : columns) {
String metaValue = column.getValue(StringMetadataSerializer.get());
String metaKey = column.getName();
metaTable.put(row.getKey(), metaKey, metaValue);
}
}
} catch (ConnectionException e) {
if (e instanceof NotFoundException) { // TODO: Not really sure what happens when one of the keys is not found.
Instrumentation.markNotFound(CF);
} else {
if (isBatch) { Instrumentation.markBatchReadError(e); }
else { Instrumentation.markReadError(e); }
}
log.warn((isBatch ? "Batch " : "") + " read query failed for column family " + CF.getName(), e);
} finally {
ctx.stop();
}
return metaTable;
} | public Table<Locator, String, String> getMetadataValues(Set<Locator> locators) {
ColumnFamily CF = CassandraModel.CF_METRIC_METADATA;
boolean isBatch = locators.size() > 1;
Table<Locator, String, String> metaTable = HashBasedTable.create();
Timer.Context ctx = isBatch ? Instrumentation.getBatchReadTimerContext(CF) : Instrumentation.getReadTimerContext(CF);
try {
OperationResult<Rows<Locator, String>> query = keyspace
.prepareQuery(CF)
.getKeySlice(locators)
.execute();
for (Row<Locator, String> row : query.getResult()) {
ColumnList<String> columns = row.getColumns();
for (Column<String> column : columns) {
String metaValue = column.getValue(StringMetadataSerializer.get());
String metaKey = column.getName();
metaTable.put(row.getKey(), metaKey, metaValue);
}
}
} catch (ConnectionException e) {
if (e instanceof NotFoundException) {
Instrumentation.markNotFound(CF);
} else {
if (isBatch) { Instrumentation.markBatchReadError(e); }
else { Instrumentation.markReadError(e); }
}
log.warn((isBatch ? "Batch " : "") + " read query failed for column family " + CF.getName(), e);
} finally {
ctx.stop();
}
return metaTable;
} | public table<locator, string, string> getmetadatavalues(set<locator> locators) { columnfamily cf = cassandramodel.cf_metric_metadata; boolean isbatch = locators.size() > 1; table<locator, string, string> metatable = hashbasedtable.create(); timer.context ctx = isbatch ? instrumentation.getbatchreadtimercontext(cf) : instrumentation.getreadtimercontext(cf); try { operationresult<rows<locator, string>> query = keyspace .preparequery(cf) .getkeyslice(locators) .execute(); for (row<locator, string> row : query.getresult()) { columnlist<string> columns = row.getcolumns(); for (column<string> column : columns) { string metavalue = column.getvalue(stringmetadataserializer.get()); string metakey = column.getname(); metatable.put(row.getkey(), metakey, metavalue); } } } catch (connectionexception e) { if (e instanceof notfoundexception) { instrumentation.marknotfound(cf); } else { if (isbatch) { instrumentation.markbatchreaderror(e); } else { instrumentation.markreaderror(e); } } log.warn((isbatch ? "batch " : "") + " read query failed for column family " + cf.getname(), e); } finally { ctx.stop(); } return metatable; } | dlobue/blueflood | [
1,
0,
0,
0
] |
15,968 | private Map<Locator, ColumnList<Long>> getColumnsFromDB(List<Locator> locators, ColumnFamily<Locator, Long> CF,
Range range) {
if (range.getStart() > range.getStop()) {
throw new RuntimeException(String.format("Invalid rollup range: ", range.toString()));
}
boolean isBatch = locators.size() != 1;
final Map<Locator, ColumnList<Long>> columns = new HashMap<Locator, ColumnList<Long>>();
final RangeBuilder rangeBuilder = new RangeBuilder().setStart(range.getStart()).setEnd(range.getStop());
Timer.Context ctx = isBatch ? Instrumentation.getBatchReadTimerContext(CF) : Instrumentation.getReadTimerContext(CF);
try {
// We don't paginate this call. So we should make sure the number of reads is tolerable.
// TODO: Think about paginating this call.
OperationResult<Rows<Locator, Long>> query = keyspace
.prepareQuery(CF)
.getKeySlice(locators)
.withColumnRange(rangeBuilder.build())
.execute();
for (Row<Locator, Long> row : query.getResult()) {
columns.put(row.getKey(), row.getColumns());
}
} catch (ConnectionException e) {
if (e instanceof NotFoundException) { // TODO: Not really sure what happens when one of the keys is not found.
Instrumentation.markNotFound(CF);
} else {
if (isBatch) { Instrumentation.markBatchReadError(e); }
else { Instrumentation.markReadError(e); }
}
log.warn((isBatch ? "Batch " : "") + " read query failed for column family " + CF.getName(), e);
} finally {
ctx.stop();
}
return columns;
} | private Map<Locator, ColumnList<Long>> getColumnsFromDB(List<Locator> locators, ColumnFamily<Locator, Long> CF,
Range range) {
if (range.getStart() > range.getStop()) {
throw new RuntimeException(String.format("Invalid rollup range: ", range.toString()));
}
boolean isBatch = locators.size() != 1;
final Map<Locator, ColumnList<Long>> columns = new HashMap<Locator, ColumnList<Long>>();
final RangeBuilder rangeBuilder = new RangeBuilder().setStart(range.getStart()).setEnd(range.getStop());
Timer.Context ctx = isBatch ? Instrumentation.getBatchReadTimerContext(CF) : Instrumentation.getReadTimerContext(CF);
try {
OperationResult<Rows<Locator, Long>> query = keyspace
.prepareQuery(CF)
.getKeySlice(locators)
.withColumnRange(rangeBuilder.build())
.execute();
for (Row<Locator, Long> row : query.getResult()) {
columns.put(row.getKey(), row.getColumns());
}
} catch (ConnectionException e) {
if (e instanceof NotFoundException) {
Instrumentation.markNotFound(CF);
} else {
if (isBatch) { Instrumentation.markBatchReadError(e); }
else { Instrumentation.markReadError(e); }
}
log.warn((isBatch ? "Batch " : "") + " read query failed for column family " + CF.getName(), e);
} finally {
ctx.stop();
}
return columns;
} | private map<locator, columnlist<long>> getcolumnsfromdb(list<locator> locators, columnfamily<locator, long> cf, range range) { if (range.getstart() > range.getstop()) { throw new runtimeexception(string.format("invalid rollup range: ", range.tostring())); } boolean isbatch = locators.size() != 1; final map<locator, columnlist<long>> columns = new hashmap<locator, columnlist<long>>(); final rangebuilder rangebuilder = new rangebuilder().setstart(range.getstart()).setend(range.getstop()); timer.context ctx = isbatch ? instrumentation.getbatchreadtimercontext(cf) : instrumentation.getreadtimercontext(cf); try { operationresult<rows<locator, long>> query = keyspace .preparequery(cf) .getkeyslice(locators) .withcolumnrange(rangebuilder.build()) .execute(); for (row<locator, long> row : query.getresult()) { columns.put(row.getkey(), row.getcolumns()); } } catch (connectionexception e) { if (e instanceof notfoundexception) { instrumentation.marknotfound(cf); } else { if (isbatch) { instrumentation.markbatchreaderror(e); } else { instrumentation.markreaderror(e); } } log.warn((isbatch ? "batch " : "") + " read query failed for column family " + cf.getname(), e); } finally { ctx.stop(); } return columns; } | dlobue/blueflood | [
1,
0,
0,
0
] |
16,078 | void SetupDataDialog_componentAdded(java.awt.event.ContainerEvent event)
{
// to do: code goes here.
} | void SetupDataDialog_componentAdded(java.awt.event.ContainerEvent event)
{
} | void setupdatadialog_componentadded(java.awt.event.containerevent event) { } | fluffynukeit/mdsplus | [
0,
1,
0,
0
] |
7,897 | private Set<String> getSpammyItems() {
Set<String> spammyItems = null;
try {
spammyItems = new HashSet<String>(Files.readAllLines(SPAMMY_ITEM_FILE.toPath()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// TODO: Do something intelligent.
}
return spammyItems;
} | private Set<String> getSpammyItems() {
Set<String> spammyItems = null;
try {
spammyItems = new HashSet<String>(Files.readAllLines(SPAMMY_ITEM_FILE.toPath()));
} catch (IOException e) {
e.printStackTrace();
}
return spammyItems;
} | private set<string> getspammyitems() { set<string> spammyitems = null; try { spammyitems = new hashset<string>(files.readalllines(spammy_item_file.topath())); } catch (ioexception e) { e.printstacktrace(); } return spammyitems; } | edmazur/everquest-robot-stanvern | [
1,
0,
0,
0
] |
7,896 | public void initialize() {
PayloadTrieBuilder<Item> itemsByNameBuilder = PayloadTrie.builder();
itemsByNameBuilder
.ignoreCase()
.ignoreOverlaps();
spammyItems = getSpammyItems();
BufferedReader bufferedReader;
try {
bufferedReader = new BufferedReader(new FileReader(ITEM_FILE));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
String[] parts = line.split("\t");
String name = parts[0];
String url = parts[1];
Item item = new Item(name, url);
itemsByNameBuilder.addKeyword(normalize(name), item);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
// TODO: Do something intelligent.
} catch (IOException e) {
e.printStackTrace();
// TODO: Do something intelligent.
}
itemsByName = itemsByNameBuilder.build();
} | public void initialize() {
PayloadTrieBuilder<Item> itemsByNameBuilder = PayloadTrie.builder();
itemsByNameBuilder
.ignoreCase()
.ignoreOverlaps();
spammyItems = getSpammyItems();
BufferedReader bufferedReader;
try {
bufferedReader = new BufferedReader(new FileReader(ITEM_FILE));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
String[] parts = line.split("\t");
String name = parts[0];
String url = parts[1];
Item item = new Item(name, url);
itemsByNameBuilder.addKeyword(normalize(name), item);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
itemsByName = itemsByNameBuilder.build();
} | public void initialize() { payloadtriebuilder<item> itemsbynamebuilder = payloadtrie.builder(); itemsbynamebuilder .ignorecase() .ignoreoverlaps(); spammyitems = getspammyitems(); bufferedreader bufferedreader; try { bufferedreader = new bufferedreader(new filereader(item_file)); string line = null; while ((line = bufferedreader.readline()) != null) { string[] parts = line.split("\t"); string name = parts[0]; string url = parts[1]; item item = new item(name, url); itemsbynamebuilder.addkeyword(normalize(name), item); } } catch (filenotfoundexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } itemsbyname = itemsbynamebuilder.build(); } | edmazur/everquest-robot-stanvern | [
1,
0,
0,
0
] |
24,462 | private void bordersChanged() {
JComponent component = (JComponent)toAWTComponent();
component.setBorder(JBUI.Borders.empty());
Collection<BorderInfo> borders = dataObject().getBorders();
Map<BorderPosition, Integer> emptyBorders = new LinkedHashMap<>();
for (BorderInfo border : borders) {
if (border.getBorderStyle() == BorderStyle.EMPTY) {
emptyBorders.put(border.getBorderPosition(), border.getWidth());
}
}
if (!emptyBorders.isEmpty()) {
component.setBorder(JBUI.Borders.empty(getBorderSize(emptyBorders, BorderPosition.TOP), getBorderSize(emptyBorders, BorderPosition.LEFT), getBorderSize(emptyBorders, BorderPosition.BOTTOM),
getBorderSize(emptyBorders, BorderPosition.RIGHT)));
return;
}
// FIXME [VISTALL] support other borders?
} | private void bordersChanged() {
JComponent component = (JComponent)toAWTComponent();
component.setBorder(JBUI.Borders.empty());
Collection<BorderInfo> borders = dataObject().getBorders();
Map<BorderPosition, Integer> emptyBorders = new LinkedHashMap<>();
for (BorderInfo border : borders) {
if (border.getBorderStyle() == BorderStyle.EMPTY) {
emptyBorders.put(border.getBorderPosition(), border.getWidth());
}
}
if (!emptyBorders.isEmpty()) {
component.setBorder(JBUI.Borders.empty(getBorderSize(emptyBorders, BorderPosition.TOP), getBorderSize(emptyBorders, BorderPosition.LEFT), getBorderSize(emptyBorders, BorderPosition.BOTTOM),
getBorderSize(emptyBorders, BorderPosition.RIGHT)));
return;
}
} | private void borderschanged() { jcomponent component = (jcomponent)toawtcomponent(); component.setborder(jbui.borders.empty()); collection<borderinfo> borders = dataobject().getborders(); map<borderposition, integer> emptyborders = new linkedhashmap<>(); for (borderinfo border : borders) { if (border.getborderstyle() == borderstyle.empty) { emptyborders.put(border.getborderposition(), border.getwidth()); } } if (!emptyborders.isempty()) { component.setborder(jbui.borders.empty(getbordersize(emptyborders, borderposition.top), getbordersize(emptyborders, borderposition.left), getbordersize(emptyborders, borderposition.bottom), getbordersize(emptyborders, borderposition.right))); return; } } | consulo/consulo | [
0,
0,
1,
0
] |
24,543 | private void saveXML(Reference ref, FileOutputStream fos) throws JAXBException
{
JAXBContext ctx = JAXBContext.newInstance(com.digi_dmx.gen.Context.class);
Marshaller m = ctx.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.setProperty(Marshaller.JAXB_ENCODING, DEFAULT_ENCODING);
com.digi_dmx.gen.Context save = new com.digi_dmx.gen.Context();
save.setFactory(ref.getFactoryClassName());
save.setClazz(ref.getClassName());
Enumeration<RefAddr> all = ref.getAll();
while (all.hasMoreElements())
{
RefAddr refAddr = all.nextElement();
Attr attr = new Attr();
attr.setName(refAddr.getType());
Object content = refAddr.getContent();
if (content != null)
{
attr.setValue(content.toString());
}
save.addAttr(attr); // this hurts my soul
}
m.marshal(save, fos);
} | private void saveXML(Reference ref, FileOutputStream fos) throws JAXBException
{
JAXBContext ctx = JAXBContext.newInstance(com.digi_dmx.gen.Context.class);
Marshaller m = ctx.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.setProperty(Marshaller.JAXB_ENCODING, DEFAULT_ENCODING);
com.digi_dmx.gen.Context save = new com.digi_dmx.gen.Context();
save.setFactory(ref.getFactoryClassName());
save.setClazz(ref.getClassName());
Enumeration<RefAddr> all = ref.getAll();
while (all.hasMoreElements())
{
RefAddr refAddr = all.nextElement();
Attr attr = new Attr();
attr.setName(refAddr.getType());
Object content = refAddr.getContent();
if (content != null)
{
attr.setValue(content.toString());
}
save.addAttr(attr);
}
m.marshal(save, fos);
} | private void savexml(reference ref, fileoutputstream fos) throws jaxbexception { jaxbcontext ctx = jaxbcontext.newinstance(com.digi_dmx.gen.context.class); marshaller m = ctx.createmarshaller(); m.setproperty(marshaller.jaxb_formatted_output, true); m.setproperty(marshaller.jaxb_encoding, default_encoding); com.digi_dmx.gen.context save = new com.digi_dmx.gen.context(); save.setfactory(ref.getfactoryclassname()); save.setclazz(ref.getclassname()); enumeration<refaddr> all = ref.getall(); while (all.hasmoreelements()) { refaddr refaddr = all.nextelement(); attr attr = new attr(); attr.setname(refaddr.gettype()); object content = refaddr.getcontent(); if (content != null) { attr.setvalue(content.tostring()); } save.addattr(attr); } m.marshal(save, fos); } | ebardes/EasyJNDI | [
1,
0,
0,
0
] |
119 | private void reduceList(Site site, Map<String, String> zapRelations,
Map<String, Vulnerability> groupVulnerabilities) throws MalformedURLException {
/**
* De las vulnerabilidades encontradas las mapeamos a objetos
* y las agrupamos por tipo de vulnerabilidad y url
*/
for (Alert alert: site.getAlerts()) {
String nameVuln = zapRelations.get(alert.getPluginid());
if(StringUtils.isBlank(nameVuln)){
Vulnerability vulnerability = new Vulnerability();
vulnerability.setName(Constantes.COMMON_MESSAGE_NOT_FOUND + alert.getName());
vulnerability.setShortName(alert.getName());
vulnerability.setLongName(alert.getName());
//TODO: Convertir la serveridad
vulnerability.setSeverity(alert.getRiskdesc().replaceAll("\\(.*\\)", "").trim());
vulnerability.setCwe(Integer.parseInt(alert.getCweid()));
for(Endpoint endPointZap : alert.getInstances()){
if(!vulnerability.getEndpoint().stream().anyMatch(obj -> obj.getUrl().equals(getUrlWithoutParameters(endPointZap.getUrl()))
&& obj.getMethod().equals(endPointZap.getMethod()))){
vulnerability.getEndpoint().add(new Endpoint(endPointZap.getMethod(), getUrlWithoutParameters(endPointZap.getUrl())));
}
}
groupVulnerabilities.put(vulnerability.getName(), vulnerability);
} else if(groupVulnerabilities.containsKey(nameVuln)){
Vulnerability vulnerability = groupVulnerabilities.get(nameVuln);
for(Endpoint endPointZap : alert.getInstances()){
if(!vulnerability.getEndpoint().stream().anyMatch(obj -> obj.getUrl().equals(getUrlWithoutParameters(endPointZap.getUrl()))
&& obj.getMethod().equals(endPointZap.getMethod()))){
vulnerability.getEndpoint().add(new Endpoint(endPointZap.getMethod(), getUrlWithoutParameters(endPointZap.getUrl())));
}
}
} else {
Vulnerability vulnerability = new Vulnerability();
vulnerability.setShortName(alert.getName());
vulnerability.setLongName(alert.getName());
//TODO: Convertir la serveridad
vulnerability.setSeverity(alert.getRiskdesc().replaceAll("\\(.*\\)", ""));
vulnerability.setCwe(Integer.parseInt(alert.getCweid()));
for(Endpoint endPointZap : alert.getInstances()){
if(!vulnerability.getEndpoint().stream().anyMatch(obj -> obj.getUrl().equals(getUrlWithoutParameters(endPointZap.getUrl()))
&& obj.getMethod().equals(endPointZap.getMethod()))){
vulnerability.getEndpoint().add(new Endpoint(endPointZap.getMethod(), getUrlWithoutParameters(endPointZap.getUrl())));
}
}
groupVulnerabilities.put(vulnerability.getName(), vulnerability);
}
}
} | private void reduceList(Site site, Map<String, String> zapRelations,
Map<String, Vulnerability> groupVulnerabilities) throws MalformedURLException {
for (Alert alert: site.getAlerts()) {
String nameVuln = zapRelations.get(alert.getPluginid());
if(StringUtils.isBlank(nameVuln)){
Vulnerability vulnerability = new Vulnerability();
vulnerability.setName(Constantes.COMMON_MESSAGE_NOT_FOUND + alert.getName());
vulnerability.setShortName(alert.getName());
vulnerability.setLongName(alert.getName());
vulnerability.setSeverity(alert.getRiskdesc().replaceAll("\\(.*\\)", "").trim());
vulnerability.setCwe(Integer.parseInt(alert.getCweid()));
for(Endpoint endPointZap : alert.getInstances()){
if(!vulnerability.getEndpoint().stream().anyMatch(obj -> obj.getUrl().equals(getUrlWithoutParameters(endPointZap.getUrl()))
&& obj.getMethod().equals(endPointZap.getMethod()))){
vulnerability.getEndpoint().add(new Endpoint(endPointZap.getMethod(), getUrlWithoutParameters(endPointZap.getUrl())));
}
}
groupVulnerabilities.put(vulnerability.getName(), vulnerability);
} else if(groupVulnerabilities.containsKey(nameVuln)){
Vulnerability vulnerability = groupVulnerabilities.get(nameVuln);
for(Endpoint endPointZap : alert.getInstances()){
if(!vulnerability.getEndpoint().stream().anyMatch(obj -> obj.getUrl().equals(getUrlWithoutParameters(endPointZap.getUrl()))
&& obj.getMethod().equals(endPointZap.getMethod()))){
vulnerability.getEndpoint().add(new Endpoint(endPointZap.getMethod(), getUrlWithoutParameters(endPointZap.getUrl())));
}
}
} else {
Vulnerability vulnerability = new Vulnerability();
vulnerability.setShortName(alert.getName());
vulnerability.setLongName(alert.getName());
vulnerability.setSeverity(alert.getRiskdesc().replaceAll("\\(.*\\)", ""));
vulnerability.setCwe(Integer.parseInt(alert.getCweid()));
for(Endpoint endPointZap : alert.getInstances()){
if(!vulnerability.getEndpoint().stream().anyMatch(obj -> obj.getUrl().equals(getUrlWithoutParameters(endPointZap.getUrl()))
&& obj.getMethod().equals(endPointZap.getMethod()))){
vulnerability.getEndpoint().add(new Endpoint(endPointZap.getMethod(), getUrlWithoutParameters(endPointZap.getUrl())));
}
}
groupVulnerabilities.put(vulnerability.getName(), vulnerability);
}
}
} | private void reducelist(site site, map<string, string> zaprelations, map<string, vulnerability> groupvulnerabilities) throws malformedurlexception { for (alert alert: site.getalerts()) { string namevuln = zaprelations.get(alert.getpluginid()); if(stringutils.isblank(namevuln)){ vulnerability vulnerability = new vulnerability(); vulnerability.setname(constantes.common_message_not_found + alert.getname()); vulnerability.setshortname(alert.getname()); vulnerability.setlongname(alert.getname()); vulnerability.setseverity(alert.getriskdesc().replaceall("\\(.*\\)", "").trim()); vulnerability.setcwe(integer.parseint(alert.getcweid())); for(endpoint endpointzap : alert.getinstances()){ if(!vulnerability.getendpoint().stream().anymatch(obj -> obj.geturl().equals(geturlwithoutparameters(endpointzap.geturl())) && obj.getmethod().equals(endpointzap.getmethod()))){ vulnerability.getendpoint().add(new endpoint(endpointzap.getmethod(), geturlwithoutparameters(endpointzap.geturl()))); } } groupvulnerabilities.put(vulnerability.getname(), vulnerability); } else if(groupvulnerabilities.containskey(namevuln)){ vulnerability vulnerability = groupvulnerabilities.get(namevuln); for(endpoint endpointzap : alert.getinstances()){ if(!vulnerability.getendpoint().stream().anymatch(obj -> obj.geturl().equals(geturlwithoutparameters(endpointzap.geturl())) && obj.getmethod().equals(endpointzap.getmethod()))){ vulnerability.getendpoint().add(new endpoint(endpointzap.getmethod(), geturlwithoutparameters(endpointzap.geturl()))); } } } else { vulnerability vulnerability = new vulnerability(); vulnerability.setshortname(alert.getname()); vulnerability.setlongname(alert.getname()); vulnerability.setseverity(alert.getriskdesc().replaceall("\\(.*\\)", "")); vulnerability.setcwe(integer.parseint(alert.getcweid())); for(endpoint endpointzap : alert.getinstances()){ if(!vulnerability.getendpoint().stream().anymatch(obj -> obj.geturl().equals(geturlwithoutparameters(endpointzap.geturl())) && obj.getmethod().equals(endpointzap.getmethod()))){ vulnerability.getendpoint().add(new endpoint(endpointzap.getmethod(), geturlwithoutparameters(endpointzap.geturl()))); } } groupvulnerabilities.put(vulnerability.getname(), vulnerability); } } } | hackshieldteam/sisifo | [
0,
1,
0,
0
] |
24,712 | public void deleteAll(User user, Conversation conversation) {
// TODO: optimize
messageRepository.getAllBySenderAndConversation(user, conversation)
.stream()
.parallel()
.forEach(this::delete);
} | public void deleteAll(User user, Conversation conversation) {
messageRepository.getAllBySenderAndConversation(user, conversation)
.stream()
.parallel()
.forEach(this::delete);
} | public void deleteall(user user, conversation conversation) { messagerepository.getallbysenderandconversation(user, conversation) .stream() .parallel() .foreach(this::delete); } | ivanjermakov/letter-core | [
1,
0,
0,
0
] |
24,736 | @Test
public void testLANG1292() {
// Prior to fix, this was throwing StringIndexOutOfBoundsException
Wrap.wrap("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 70);
} | @Test
public void testLANG1292() {
Wrap.wrap("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 70);
} | @test public void testlang1292() { wrap.wrap("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", 70); } | jgallimore/crest | [
0,
0,
1,
0
] |
24,737 | @Test
public void testLANG1397() {
// Prior to fix, this was throwing StringIndexOutOfBoundsException
Wrap.wrap("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", Integer.MAX_VALUE);
} | @Test
public void testLANG1397() {
Wrap.wrap("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
+ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", Integer.MAX_VALUE);
} | @test public void testlang1397() { wrap.wrap("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa " + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", integer.max_value); } | jgallimore/crest | [
0,
0,
1,
0
] |
16,576 | public void dumpDecrements(Block block, RCTracker increments) {
// TODO: can we guarantee that the refcount var is available in the
// current scope?
for (RefCountType rcType: RefcountPass.RC_TYPES) {
for (Entry<AliasKey, Long> e: increments.rcIter(rcType, RCDir.DECR)) {
assert (e.getValue() <= 0);
Var var = increments.getRefCountVar(e.getKey());
if (RefCounting.trackRefCount(var, rcType)) {
Arg amount = Arg.newInt(e.getValue() * -1);
block.addCleanup(var, RefCountOp.decrRef(rcType, var, amount));
}
}
}
// Clear out all decrements
increments.resetAll(RCDir.DECR);
} | public void dumpDecrements(Block block, RCTracker increments) {
for (RefCountType rcType: RefcountPass.RC_TYPES) {
for (Entry<AliasKey, Long> e: increments.rcIter(rcType, RCDir.DECR)) {
assert (e.getValue() <= 0);
Var var = increments.getRefCountVar(e.getKey());
if (RefCounting.trackRefCount(var, rcType)) {
Arg amount = Arg.newInt(e.getValue() * -1);
block.addCleanup(var, RefCountOp.decrRef(rcType, var, amount));
}
}
}
increments.resetAll(RCDir.DECR);
} | public void dumpdecrements(block block, rctracker increments) { for (refcounttype rctype: refcountpass.rc_types) { for (entry<aliaskey, long> e: increments.rciter(rctype, rcdir.decr)) { assert (e.getvalue() <= 0); var var = increments.getrefcountvar(e.getkey()); if (refcounting.trackrefcount(var, rctype)) { arg amount = arg.newint(e.getvalue() * -1); block.addcleanup(var, refcountop.decrref(rctype, var, amount)); } } } increments.resetall(rcdir.decr); } | hsphcdm/swift-t | [
1,
0,
0,
0
] |