method
stringlengths 13
441k
| clean_method
stringlengths 7
313k
| doc
stringlengths 17
17.3k
| comment
stringlengths 3
1.42k
| method_name
stringlengths 1
273
| extra
dict | imports
sequence | imports_info
stringlengths 19
34.8k
| cluster_imports_info
stringlengths 15
3.66k
| libraries
sequence | libraries_info
stringlengths 6
661
| id
int64 0
2.92M
|
---|---|---|---|---|---|---|---|---|---|---|---|
public void test_getInt_typeMisMatch() {
Exception ex = null;
try {
System.setProperty("org.apache.wink.common.model.json.factory.impl", "org.apache.wink.json4j.compat.impl.ApacheJSONFactory");
JSONFactory factory = JSONFactory.newInstance();
JSONObject jObject = factory.createJSONObject("{\"int\":\"1\"}");
assertTrue(jObject.getLong("int") == 1);
} catch (Exception ex1) {
ex = ex1;
}
assertTrue(ex instanceof JSONException);
} | void function() { Exception ex = null; try { System.setProperty(STR, STR); JSONFactory factory = JSONFactory.newInstance(); JSONObject jObject = factory.createJSONObject("{\"int\":\"1\"}"); assertTrue(jObject.getLong("int") == 1); } catch (Exception ex1) { ex = ex1; } assertTrue(ex instanceof JSONException); } | /**
* Test a basic JSON Object construction and helper 'get' function failure due to type mismatch
*/ | Test a basic JSON Object construction and helper 'get' function failure due to type mismatch | test_getInt_typeMisMatch | {
"repo_name": "apache/wink",
"path": "wink-json4j/src/test/java/org/apache/wink/json4j/compat/tests/ApacheJSONObjectTest.java",
"license": "apache-2.0",
"size": 39515
} | [
"org.apache.wink.json4j.compat.JSONException",
"org.apache.wink.json4j.compat.JSONFactory",
"org.apache.wink.json4j.compat.JSONObject"
] | import org.apache.wink.json4j.compat.JSONException; import org.apache.wink.json4j.compat.JSONFactory; import org.apache.wink.json4j.compat.JSONObject; | import org.apache.wink.json4j.compat.*; | [
"org.apache.wink"
] | org.apache.wink; | 2,846,368 |
public static MozuClient<com.mozu.api.contracts.sitesettings.general.TaxableTerritory> addTaxableTerritoryClient(com.mozu.api.contracts.sitesettings.general.TaxableTerritory taxableTerritory) throws Exception
{
return addTaxableTerritoryClient( taxableTerritory, null);
} | static MozuClient<com.mozu.api.contracts.sitesettings.general.TaxableTerritory> function(com.mozu.api.contracts.sitesettings.general.TaxableTerritory taxableTerritory) throws Exception { return addTaxableTerritoryClient( taxableTerritory, null); } | /**
* Creates a new territory for which to calculate sales tax.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.sitesettings.general.TaxableTerritory> mozuClient=AddTaxableTerritoryClient( taxableTerritory);
* client.setBaseAddress(url);
* client.executeRequest();
* TaxableTerritory taxableTerritory = client.Result();
* </code></pre></p>
* @param taxableTerritory Properties of the taxable territory to create.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.sitesettings.general.TaxableTerritory>
* @see com.mozu.api.contracts.sitesettings.general.TaxableTerritory
* @see com.mozu.api.contracts.sitesettings.general.TaxableTerritory
*/ | Creates a new territory for which to calculate sales tax. <code><code> MozuClient mozuClient=AddTaxableTerritoryClient( taxableTerritory); client.setBaseAddress(url); client.executeRequest(); TaxableTerritory taxableTerritory = client.Result(); </code></code> | addTaxableTerritoryClient | {
"repo_name": "eileenzhuang1/mozu-java",
"path": "mozu-java-core/src/main/java/com/mozu/api/clients/commerce/settings/general/TaxableTerritoryClient.java",
"license": "mit",
"size": 5654
} | [
"com.mozu.api.MozuClient"
] | import com.mozu.api.MozuClient; | import com.mozu.api.*; | [
"com.mozu.api"
] | com.mozu.api; | 355,072 |
private void saveFlexibleElement(ProjectModel projectModel, EntityManager em) {
// ProjectModel --> Banner --> Layout --> Groups --> Constraints
if (projectModel.getProjectBanner() != null && projectModel.getProjectBanner().getLayout() != null) {
List<LayoutGroup> bannerLayoutGroups = projectModel.getProjectBanner().getLayout().getGroups();
if (bannerLayoutGroups != null) {
for (LayoutGroup layoutGroup : bannerLayoutGroups) {
List<LayoutConstraint> layoutConstraints = layoutGroup.getConstraints();
if (layoutConstraints != null) {
for (LayoutConstraint layoutConstraint : layoutConstraints) {
if (layoutConstraint.getElement() != null) {
if (layoutConstraint.getElement() instanceof QuestionElement) {
List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint
.getElement()).getChoices();
CategoryType type = ((QuestionElement) layoutConstraint.getElement())
.getCategoryType();
if (questionChoiceElements != null || type != null) {
FlexibleElement parent = (FlexibleElement) layoutConstraint.getElement();
((QuestionElement) parent).setChoices(null);
((QuestionElement) parent).setCategoryType(null);
em.persist(parent);
// Save QuestionChoiceElement with their
// QuestionElement parent(saved above)
if (questionChoiceElements != null) {
for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) {
if (questionChoiceElement != null) {
questionChoiceElement.setId(null);
questionChoiceElement.setParentQuestion((QuestionElement) parent);
CategoryElement categoryElement = questionChoiceElement
.getCategoryElement();
if (categoryElement != null) {
questionChoiceElement.setCategoryElement(null);
em.persist(questionChoiceElement);
saveProjectModelCategoryElement(categoryElement, em);
questionChoiceElement.setCategoryElement(categoryElement);
em.merge(questionChoiceElement);
} else {
em.persist(questionChoiceElement);
}
}
}
// Set saved QuestionChoiceElement
// to QuestionElement parent and
// update it
((QuestionElement) parent).setChoices(questionChoiceElements);
}
// Save the Category type of
// QuestionElement parent(saved above)
if (type != null) {
// Set the saved CategoryType to
// QuestionElement parent and update
// it
((QuestionElement) parent).setCategoryType(type);
}
// Update the QuestionElement parent
em.merge(parent);
} else {
em.persist(layoutConstraint.getElement());
}
} else if (layoutConstraint.getElement() instanceof BudgetElement) {
List<BudgetSubField> budgetSubFields = ((BudgetElement) layoutConstraint
.getElement()).getBudgetSubFields();
if (budgetSubFields != null) {
FlexibleElement parent = (FlexibleElement) layoutConstraint.getElement();
((BudgetElement) parent).setBudgetSubFields(null);
((BudgetElement) parent).setRatioDividend(null);
((BudgetElement) parent).setRatioDivisor(null);
if (budgetSubFields != null) {
for (BudgetSubField budgetSubField : budgetSubFields) {
if (budgetSubField != null) {
budgetSubField.setId(null);
if (budgetSubField.getType() != null) {
switch (budgetSubField.getType()) {
case PLANNED:
((BudgetElement) parent).setRatioDivisor(budgetSubField);
break;
case RECEIVED:
break;
case SPENT:
((BudgetElement) parent).setRatioDividend(budgetSubField);
break;
default:
break;
}
}
budgetSubField.setBudgetElement((BudgetElement) parent);
em.persist(budgetSubField);
}
}
}
} else {
em.persist(layoutConstraint.getElement());
}
}
}
}
}
}
}
// ProjectModel --> Detail --> Layout --> Groups --> Constraints
if (projectModel.getProjectDetails() != null && projectModel.getProjectDetails().getLayout() != null) {
List<LayoutGroup> detailLayoutGroups = projectModel.getProjectDetails().getLayout().getGroups();
if (detailLayoutGroups != null) {
for (LayoutGroup layoutGroup : detailLayoutGroups) {
List<LayoutConstraint> layoutConstraints = layoutGroup.getConstraints();
if (layoutConstraints != null) {
for (LayoutConstraint layoutConstraint : layoutConstraints) {
if (layoutConstraint.getElement() != null) {
if (layoutConstraint.getElement() instanceof QuestionElement) {
List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint
.getElement()).getChoices();
CategoryType type = ((QuestionElement) layoutConstraint.getElement())
.getCategoryType();
if (questionChoiceElements != null || type != null) {
FlexibleElement parent = (FlexibleElement) layoutConstraint.getElement();
((QuestionElement) parent).setChoices(null);
((QuestionElement) parent).setCategoryType(null);
em.persist(parent);
// Save QuestionChoiceElement with
// their
// QuestionElement parent(saved
// above)
if (questionChoiceElements != null) {
for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) {
if (questionChoiceElement != null) {
questionChoiceElement.setId(null);
questionChoiceElement
.setParentQuestion((QuestionElement) parent);
CategoryElement categoryElement = questionChoiceElement
.getCategoryElement();
if (categoryElement != null) {
questionChoiceElement.setCategoryElement(null);
em.persist(questionChoiceElement);
saveProjectModelCategoryElement(categoryElement, em);
questionChoiceElement.setCategoryElement(categoryElement);
em.merge(questionChoiceElement);
} else {
em.persist(questionChoiceElement);
}
}
}
// Set saved
// QuestionChoiceElement
// to QuestionElement parent and
// update it
((QuestionElement) parent).setChoices(questionChoiceElements);
}
// Save the Category type of
// QuestionElement parent(saved
// above)
if (type != null) {
// Set the saved CategoryType to
// QuestionElement parent and
// update
// it
((QuestionElement) parent).setCategoryType(type);
}
// Update the QuestionElement parent
em.merge(parent);
} else {
em.persist(layoutConstraint.getElement());
}
} else if (layoutConstraint.getElement() instanceof BudgetElement) {
List<BudgetSubField> budgetSubFields = ((BudgetElement) layoutConstraint
.getElement()).getBudgetSubFields();
if (budgetSubFields != null) {
FlexibleElement parent = (FlexibleElement) layoutConstraint.getElement();
((BudgetElement) parent).setBudgetSubFields(null);
((BudgetElement) parent).setRatioDividend(null);
((BudgetElement) parent).setRatioDivisor(null);
for (BudgetSubField budgetSubField : budgetSubFields) {
if (budgetSubField != null) {
budgetSubField.setId(null);
if (budgetSubField.getType() != null) {
switch (budgetSubField.getType()) {
case PLANNED:
((BudgetElement) parent).setRatioDivisor(budgetSubField);
break;
case RECEIVED:
break;
case SPENT:
((BudgetElement) parent).setRatioDividend(budgetSubField);
break;
default:
break;
}
}
budgetSubField.setBudgetElement((BudgetElement) parent);
em.persist(budgetSubField);
}
}
} else {
em.persist(layoutConstraint.getElement());
}
} else {
em.persist(layoutConstraint.getElement());
}
}
}
}
}
}
}
// ProjectModel --> Phases --> Layout --> Groups --> Constraints
List<PhaseModel> phases = projectModel.getPhases();
if (phases != null) {
projectModel.setPhases(null);
em.persist(projectModel);
for (PhaseModel phase : phases) {
phase.setParentProjectModel(projectModel);
if (phase.getLayout() != null) {
List<LayoutGroup> phaseLayoutGroups = phase.getLayout().getGroups();
if (phaseLayoutGroups != null) {
for (LayoutGroup layoutGroup : phaseLayoutGroups) {
List<LayoutConstraint> layoutConstraints = layoutGroup.getConstraints();
if (layoutConstraints != null) {
for (LayoutConstraint layoutConstraint : layoutConstraints) {
if (layoutConstraint.getElement() != null) {
// Save parent QuestionElement like
// a
// FlexibleElement
if (layoutConstraint.getElement() instanceof QuestionElement) {
List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint
.getElement()).getChoices();
CategoryType type = ((QuestionElement) layoutConstraint.getElement())
.getCategoryType();
if (questionChoiceElements != null || type != null) {
FlexibleElement parent = (FlexibleElement) layoutConstraint
.getElement();
((QuestionElement) parent).setChoices(null);
((QuestionElement) parent).setCategoryType(null);
em.persist(parent);
// Save
// QuestionChoiceElement
// with their
// QuestionElement
// parent(saved above)
if (questionChoiceElements != null) {
for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) {
if (questionChoiceElement != null) {
questionChoiceElement.setId(null);
questionChoiceElement
.setParentQuestion((QuestionElement) parent);
CategoryElement categoryElement = questionChoiceElement
.getCategoryElement();
if (categoryElement != null) {
questionChoiceElement.setCategoryElement(null);
em.persist(questionChoiceElement);
saveProjectModelCategoryElement(categoryElement, em);
questionChoiceElement
.setCategoryElement(categoryElement);
em.merge(questionChoiceElement);
} else {
em.persist(questionChoiceElement);
}
}
}
// Set saved
// QuestionChoiceElement
// to
// QuestionElement
// parent
// and update it
((QuestionElement) parent).setChoices(questionChoiceElements);
}
// Save the Category type of
// QuestionElement
// parent(saved
// above)
if (type != null) {
// Set the saved
// CategoryType to
// QuestionElement
// parent
// and update it
((QuestionElement) parent).setCategoryType(type);
}
// Update the
// QuestionElement
// parent
em.merge(parent);
} else {
em.persist(layoutConstraint.getElement());
}
} else if (layoutConstraint.getElement() instanceof BudgetElement) {
List<BudgetSubField> budgetSubFields = ((BudgetElement) layoutConstraint
.getElement()).getBudgetSubFields();
if (budgetSubFields != null) {
FlexibleElement parent = (FlexibleElement) layoutConstraint
.getElement();
((BudgetElement) parent).setBudgetSubFields(null);
((BudgetElement) parent).setRatioDividend(null);
((BudgetElement) parent).setRatioDivisor(null);
for (BudgetSubField budgetSubField : budgetSubFields) {
if (budgetSubField != null) {
budgetSubField.setId(null);
if (budgetSubField.getType() != null) {
switch (budgetSubField.getType()) {
case PLANNED:
((BudgetElement) parent)
.setRatioDivisor(budgetSubField);
break;
case RECEIVED:
break;
case SPENT:
((BudgetElement) parent)
.setRatioDividend(budgetSubField);
break;
default:
break;
}
}
budgetSubField.setBudgetElement((BudgetElement) parent);
em.persist(budgetSubField);
}
}
em.persist(parent);
} else {
em.persist(layoutConstraint.getElement());
}
} else {
em.persist(layoutConstraint.getElement());
}
}
}
}
}
}
}
if (phase.getDefinition() != null) {
em.persist(phase.getDefinition());
}
em.persist(phase);
}
projectModel.setPhases(phases);
}
}
}
| void function(ProjectModel projectModel, EntityManager em) { if (projectModel.getProjectBanner() != null && projectModel.getProjectBanner().getLayout() != null) { List<LayoutGroup> bannerLayoutGroups = projectModel.getProjectBanner().getLayout().getGroups(); if (bannerLayoutGroups != null) { for (LayoutGroup layoutGroup : bannerLayoutGroups) { List<LayoutConstraint> layoutConstraints = layoutGroup.getConstraints(); if (layoutConstraints != null) { for (LayoutConstraint layoutConstraint : layoutConstraints) { if (layoutConstraint.getElement() != null) { if (layoutConstraint.getElement() instanceof QuestionElement) { List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint .getElement()).getChoices(); CategoryType type = ((QuestionElement) layoutConstraint.getElement()) .getCategoryType(); if (questionChoiceElements != null type != null) { FlexibleElement parent = (FlexibleElement) layoutConstraint.getElement(); ((QuestionElement) parent).setChoices(null); ((QuestionElement) parent).setCategoryType(null); em.persist(parent); if (questionChoiceElements != null) { for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) { if (questionChoiceElement != null) { questionChoiceElement.setId(null); questionChoiceElement.setParentQuestion((QuestionElement) parent); CategoryElement categoryElement = questionChoiceElement .getCategoryElement(); if (categoryElement != null) { questionChoiceElement.setCategoryElement(null); em.persist(questionChoiceElement); saveProjectModelCategoryElement(categoryElement, em); questionChoiceElement.setCategoryElement(categoryElement); em.merge(questionChoiceElement); } else { em.persist(questionChoiceElement); } } } ((QuestionElement) parent).setChoices(questionChoiceElements); } if (type != null) { ((QuestionElement) parent).setCategoryType(type); } em.merge(parent); } else { em.persist(layoutConstraint.getElement()); } } else if (layoutConstraint.getElement() instanceof BudgetElement) { List<BudgetSubField> budgetSubFields = ((BudgetElement) layoutConstraint .getElement()).getBudgetSubFields(); if (budgetSubFields != null) { FlexibleElement parent = (FlexibleElement) layoutConstraint.getElement(); ((BudgetElement) parent).setBudgetSubFields(null); ((BudgetElement) parent).setRatioDividend(null); ((BudgetElement) parent).setRatioDivisor(null); if (budgetSubFields != null) { for (BudgetSubField budgetSubField : budgetSubFields) { if (budgetSubField != null) { budgetSubField.setId(null); if (budgetSubField.getType() != null) { switch (budgetSubField.getType()) { case PLANNED: ((BudgetElement) parent).setRatioDivisor(budgetSubField); break; case RECEIVED: break; case SPENT: ((BudgetElement) parent).setRatioDividend(budgetSubField); break; default: break; } } budgetSubField.setBudgetElement((BudgetElement) parent); em.persist(budgetSubField); } } } } else { em.persist(layoutConstraint.getElement()); } } } } } } } if (projectModel.getProjectDetails() != null && projectModel.getProjectDetails().getLayout() != null) { List<LayoutGroup> detailLayoutGroups = projectModel.getProjectDetails().getLayout().getGroups(); if (detailLayoutGroups != null) { for (LayoutGroup layoutGroup : detailLayoutGroups) { List<LayoutConstraint> layoutConstraints = layoutGroup.getConstraints(); if (layoutConstraints != null) { for (LayoutConstraint layoutConstraint : layoutConstraints) { if (layoutConstraint.getElement() != null) { if (layoutConstraint.getElement() instanceof QuestionElement) { List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint .getElement()).getChoices(); CategoryType type = ((QuestionElement) layoutConstraint.getElement()) .getCategoryType(); if (questionChoiceElements != null type != null) { FlexibleElement parent = (FlexibleElement) layoutConstraint.getElement(); ((QuestionElement) parent).setChoices(null); ((QuestionElement) parent).setCategoryType(null); em.persist(parent); if (questionChoiceElements != null) { for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) { if (questionChoiceElement != null) { questionChoiceElement.setId(null); questionChoiceElement .setParentQuestion((QuestionElement) parent); CategoryElement categoryElement = questionChoiceElement .getCategoryElement(); if (categoryElement != null) { questionChoiceElement.setCategoryElement(null); em.persist(questionChoiceElement); saveProjectModelCategoryElement(categoryElement, em); questionChoiceElement.setCategoryElement(categoryElement); em.merge(questionChoiceElement); } else { em.persist(questionChoiceElement); } } } ((QuestionElement) parent).setChoices(questionChoiceElements); } if (type != null) { ((QuestionElement) parent).setCategoryType(type); } em.merge(parent); } else { em.persist(layoutConstraint.getElement()); } } else if (layoutConstraint.getElement() instanceof BudgetElement) { List<BudgetSubField> budgetSubFields = ((BudgetElement) layoutConstraint .getElement()).getBudgetSubFields(); if (budgetSubFields != null) { FlexibleElement parent = (FlexibleElement) layoutConstraint.getElement(); ((BudgetElement) parent).setBudgetSubFields(null); ((BudgetElement) parent).setRatioDividend(null); ((BudgetElement) parent).setRatioDivisor(null); for (BudgetSubField budgetSubField : budgetSubFields) { if (budgetSubField != null) { budgetSubField.setId(null); if (budgetSubField.getType() != null) { switch (budgetSubField.getType()) { case PLANNED: ((BudgetElement) parent).setRatioDivisor(budgetSubField); break; case RECEIVED: break; case SPENT: ((BudgetElement) parent).setRatioDividend(budgetSubField); break; default: break; } } budgetSubField.setBudgetElement((BudgetElement) parent); em.persist(budgetSubField); } } } else { em.persist(layoutConstraint.getElement()); } } else { em.persist(layoutConstraint.getElement()); } } } } } } } List<PhaseModel> phases = projectModel.getPhases(); if (phases != null) { projectModel.setPhases(null); em.persist(projectModel); for (PhaseModel phase : phases) { phase.setParentProjectModel(projectModel); if (phase.getLayout() != null) { List<LayoutGroup> phaseLayoutGroups = phase.getLayout().getGroups(); if (phaseLayoutGroups != null) { for (LayoutGroup layoutGroup : phaseLayoutGroups) { List<LayoutConstraint> layoutConstraints = layoutGroup.getConstraints(); if (layoutConstraints != null) { for (LayoutConstraint layoutConstraint : layoutConstraints) { if (layoutConstraint.getElement() != null) { if (layoutConstraint.getElement() instanceof QuestionElement) { List<QuestionChoiceElement> questionChoiceElements = ((QuestionElement) layoutConstraint .getElement()).getChoices(); CategoryType type = ((QuestionElement) layoutConstraint.getElement()) .getCategoryType(); if (questionChoiceElements != null type != null) { FlexibleElement parent = (FlexibleElement) layoutConstraint .getElement(); ((QuestionElement) parent).setChoices(null); ((QuestionElement) parent).setCategoryType(null); em.persist(parent); if (questionChoiceElements != null) { for (QuestionChoiceElement questionChoiceElement : questionChoiceElements) { if (questionChoiceElement != null) { questionChoiceElement.setId(null); questionChoiceElement .setParentQuestion((QuestionElement) parent); CategoryElement categoryElement = questionChoiceElement .getCategoryElement(); if (categoryElement != null) { questionChoiceElement.setCategoryElement(null); em.persist(questionChoiceElement); saveProjectModelCategoryElement(categoryElement, em); questionChoiceElement .setCategoryElement(categoryElement); em.merge(questionChoiceElement); } else { em.persist(questionChoiceElement); } } } ((QuestionElement) parent).setChoices(questionChoiceElements); } if (type != null) { ((QuestionElement) parent).setCategoryType(type); } em.merge(parent); } else { em.persist(layoutConstraint.getElement()); } } else if (layoutConstraint.getElement() instanceof BudgetElement) { List<BudgetSubField> budgetSubFields = ((BudgetElement) layoutConstraint .getElement()).getBudgetSubFields(); if (budgetSubFields != null) { FlexibleElement parent = (FlexibleElement) layoutConstraint .getElement(); ((BudgetElement) parent).setBudgetSubFields(null); ((BudgetElement) parent).setRatioDividend(null); ((BudgetElement) parent).setRatioDivisor(null); for (BudgetSubField budgetSubField : budgetSubFields) { if (budgetSubField != null) { budgetSubField.setId(null); if (budgetSubField.getType() != null) { switch (budgetSubField.getType()) { case PLANNED: ((BudgetElement) parent) .setRatioDivisor(budgetSubField); break; case RECEIVED: break; case SPENT: ((BudgetElement) parent) .setRatioDividend(budgetSubField); break; default: break; } } budgetSubField.setBudgetElement((BudgetElement) parent); em.persist(budgetSubField); } } em.persist(parent); } else { em.persist(layoutConstraint.getElement()); } } else { em.persist(layoutConstraint.getElement()); } } } } } } } if (phase.getDefinition() != null) { em.persist(phase.getDefinition()); } em.persist(phase); } projectModel.setPhases(phases); } } } | /**
* Save the flexible elements of imported project model.
*
* @param projectModel
* the imported project model
* @param em
* the entity manager
*/ | Save the flexible elements of imported project model | saveFlexibleElement | {
"repo_name": "spMohanty/sigmah_svn_to_git_migration_test",
"path": "sigmah/src/main/java/org/sigmah/server/endpoint/gwtrpc/handler/GetProjectModelCopyHandler.java",
"license": "gpl-3.0",
"size": 20776
} | [
"java.util.List",
"javax.persistence.EntityManager",
"org.sigmah.shared.domain.PhaseModel",
"org.sigmah.shared.domain.ProjectModel",
"org.sigmah.shared.domain.category.CategoryElement",
"org.sigmah.shared.domain.category.CategoryType",
"org.sigmah.shared.domain.element.BudgetElement",
"org.sigmah.shared.domain.element.BudgetSubField",
"org.sigmah.shared.domain.element.FlexibleElement",
"org.sigmah.shared.domain.element.QuestionChoiceElement",
"org.sigmah.shared.domain.element.QuestionElement",
"org.sigmah.shared.domain.layout.LayoutConstraint",
"org.sigmah.shared.domain.layout.LayoutGroup"
] | import java.util.List; import javax.persistence.EntityManager; import org.sigmah.shared.domain.PhaseModel; import org.sigmah.shared.domain.ProjectModel; import org.sigmah.shared.domain.category.CategoryElement; import org.sigmah.shared.domain.category.CategoryType; import org.sigmah.shared.domain.element.BudgetElement; import org.sigmah.shared.domain.element.BudgetSubField; import org.sigmah.shared.domain.element.FlexibleElement; import org.sigmah.shared.domain.element.QuestionChoiceElement; import org.sigmah.shared.domain.element.QuestionElement; import org.sigmah.shared.domain.layout.LayoutConstraint; import org.sigmah.shared.domain.layout.LayoutGroup; | import java.util.*; import javax.persistence.*; import org.sigmah.shared.domain.*; import org.sigmah.shared.domain.category.*; import org.sigmah.shared.domain.element.*; import org.sigmah.shared.domain.layout.*; | [
"java.util",
"javax.persistence",
"org.sigmah.shared"
] | java.util; javax.persistence; org.sigmah.shared; | 1,068,864 |
@Test
public void testMaxBlock() {
Assert.assertEquals(2, instance.maxBlock("hoopla"));
Assert.assertEquals(3, instance.maxBlock("abbCCCddBBBxx"));
Assert.assertEquals(0, instance.maxBlock(""));
Assert.assertEquals(1, instance.maxBlock("xyz"));
Assert.assertEquals(2, instance.maxBlock("xxyz"));
Assert.assertEquals(2, instance.maxBlock("xyzz"));
Assert.assertEquals(3, instance.maxBlock("abbbcbbbxbbbx"));
Assert.assertEquals(3, instance.maxBlock("XXBBBbbxx"));
Assert.assertEquals(4, instance.maxBlock("XXBBBBbbxx"));
Assert.assertEquals(4, instance.maxBlock("XXBBBbbxxXXXX"));
Assert.assertEquals(4, instance.maxBlock("XX2222BBBbbXX2222"));
}
| void function() { Assert.assertEquals(2, instance.maxBlock(STR)); Assert.assertEquals(3, instance.maxBlock(STR)); Assert.assertEquals(0, instance.maxBlock(STRxyzSTRxxyzSTRxyzzSTRabbbcbbbxbbbxSTRXXBBBbbxxSTRXXBBBBbbxxSTRXXBBBbbxxXXXXSTRXX2222BBBbbXX2222")); } | /**
* Test method for {@link String3#maxBlock(String)}.
*/ | Test method for <code>String3#maxBlock(String)</code> | testMaxBlock | {
"repo_name": "antalpeti/CodingBat",
"path": "src/test/com/codingbat/java/String3Test.java",
"license": "mit",
"size": 12008
} | [
"org.junit.Assert"
] | import org.junit.Assert; | import org.junit.*; | [
"org.junit"
] | org.junit; | 287,767 |
@Nullable
public static Revision max(@Nullable Revision a,
@Nullable Revision b,
@NotNull Comparator<Revision> c) {
if (a == null) {
return b;
} else if (b == null) {
return a;
}
return c.compare(a, b) >= 0 ? a : b;
} | static Revision function(@Nullable Revision a, @Nullable Revision b, @NotNull Comparator<Revision> c) { if (a == null) { return b; } else if (b == null) { return a; } return c.compare(a, b) >= 0 ? a : b; } | /**
* Returns the revision which is considered more recent or {@code null} if
* both revisions are {@code null}. The implementation will return the first
* revision if both are considered equal. The comparison is done using the
* provided comparator.
*
* @param a the first revision (or {@code null}).
* @param b the second revision (or {@code null}).
* @param c the comparator.
* @return the revision considered more recent.
*/ | Returns the revision which is considered more recent or null if both revisions are null. The implementation will return the first revision if both are considered equal. The comparison is done using the provided comparator | max | {
"repo_name": "trekawek/jackrabbit-oak",
"path": "oak-store-document/src/main/java/org/apache/jackrabbit/oak/plugins/document/util/Utils.java",
"license": "apache-2.0",
"size": 39873
} | [
"java.util.Comparator",
"org.apache.jackrabbit.oak.plugins.document.Revision",
"org.jetbrains.annotations.NotNull",
"org.jetbrains.annotations.Nullable"
] | import java.util.Comparator; import org.apache.jackrabbit.oak.plugins.document.Revision; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; | import java.util.*; import org.apache.jackrabbit.oak.plugins.document.*; import org.jetbrains.annotations.*; | [
"java.util",
"org.apache.jackrabbit",
"org.jetbrains.annotations"
] | java.util; org.apache.jackrabbit; org.jetbrains.annotations; | 2,781,771 |
@Test
public void testGetDatasourceFullWithIncompleteSegment()
{
Map<String, Object> actual = resource.getDatasource(dataSource, "2015-04-03/2015-04-05", "true");
Map<String, Object> expected = ImmutableMap.of();
EasyMock.verify(serverInventoryView, timelineServerView);
Assert.assertEquals(expected, actual);
} | void function() { Map<String, Object> actual = resource.getDatasource(dataSource, STR, "true"); Map<String, Object> expected = ImmutableMap.of(); EasyMock.verify(serverInventoryView, timelineServerView); Assert.assertEquals(expected, actual); } | /**
* If "full" is specified, then dimensions/metrics that exist in an incompelte segment should be ingored
*/ | If "full" is specified, then dimensions/metrics that exist in an incompelte segment should be ingored | testGetDatasourceFullWithIncompleteSegment | {
"repo_name": "fjy/druid",
"path": "server/src/test/java/io/druid/server/ClientInfoResourceTest.java",
"license": "apache-2.0",
"size": 17028
} | [
"com.google.common.collect.ImmutableMap",
"java.util.Map",
"org.easymock.EasyMock",
"org.junit.Assert"
] | import com.google.common.collect.ImmutableMap; import java.util.Map; import org.easymock.EasyMock; import org.junit.Assert; | import com.google.common.collect.*; import java.util.*; import org.easymock.*; import org.junit.*; | [
"com.google.common",
"java.util",
"org.easymock",
"org.junit"
] | com.google.common; java.util; org.easymock; org.junit; | 1,681,451 |
Set<ConnectPoint> sources(McastRoute route, HostId hostId); | Set<ConnectPoint> sources(McastRoute route, HostId hostId); | /**
* Find the set of connect points for a given source for this route.
*
* @param route a Multicast route
* @param hostId the host
* @return a list of connect points
*/ | Find the set of connect points for a given source for this route | sources | {
"repo_name": "gkatsikas/onos",
"path": "apps/mcast/api/src/main/java/org/onosproject/mcast/api/MulticastRouteService.java",
"license": "apache-2.0",
"size": 7274
} | [
"java.util.Set",
"org.onosproject.net.ConnectPoint",
"org.onosproject.net.HostId"
] | import java.util.Set; import org.onosproject.net.ConnectPoint; import org.onosproject.net.HostId; | import java.util.*; import org.onosproject.net.*; | [
"java.util",
"org.onosproject.net"
] | java.util; org.onosproject.net; | 2,255,786 |
@Override
public Histogram histogram(final String name) {
return getOrAdd(name, MetricBuilder.HISTOGRAMS);
} | Histogram function(final String name) { return getOrAdd(name, MetricBuilder.HISTOGRAMS); } | /**
* Get the histogram associated with the given name.
*
* @param name the name of the histogram
* @return the histogram associated with the given name
*/ | Get the histogram associated with the given name | histogram | {
"repo_name": "koshalt/modules",
"path": "metrics/src/main/java/org/motechproject/metrics/service/impl/MetricRegistryServiceImpl.java",
"license": "bsd-3-clause",
"size": 10065
} | [
"org.motechproject.metrics.api.Histogram"
] | import org.motechproject.metrics.api.Histogram; | import org.motechproject.metrics.api.*; | [
"org.motechproject.metrics"
] | org.motechproject.metrics; | 1,319,610 |
public int read(byte[] buf, int off, int len) throws IOException {
len = in.read(buf, off, len);
if (len != -1) {
cksum.update(buf, off, len);
}
return len;
} | int function(byte[] buf, int off, int len) throws IOException { len = in.read(buf, off, len); if (len != -1) { cksum.update(buf, off, len); } return len; } | /**
* Reads into an array of bytes. If <code>len</code> is not zero, the method
* blocks until some input is available; otherwise, no
* bytes are read and <code>0</code> is returned.
* @param buf the buffer into which the data is read
* @param off the start offset in the destination array <code>b</code>
* @param len the maximum number of bytes read
* @return the actual number of bytes read, or -1 if the end
* of the stream is reached.
* @exception NullPointerException If <code>buf</code> is <code>null</code>.
* @exception IndexOutOfBoundsException If <code>off</code> is negative,
* <code>len</code> is negative, or <code>len</code> is greater than
* <code>buf.length - off</code>
* @exception IOException if an I/O error has occurred
*/ | Reads into an array of bytes. If <code>len</code> is not zero, the method blocks until some input is available; otherwise, no bytes are read and <code>0</code> is returned | read | {
"repo_name": "shun634501730/java_source_cn",
"path": "src_en/java/util/zip/CheckedInputStream.java",
"license": "apache-2.0",
"size": 3078
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 1,542,082 |
@BeforeClass
public static void setupCluster() throws Exception {
setupConf(UTIL.getConfiguration());
UTIL.startMiniZKCluster();
CONNECTION = (ClusterConnection)ConnectionFactory.createConnection(UTIL.getConfiguration());
archivingClient = new ZKTableArchiveClient(UTIL.getConfiguration(), CONNECTION);
// make hfile archiving node so we can archive files
ZKWatcher watcher = UTIL.getZooKeeperWatcher();
String archivingZNode = ZKTableArchiveClient.getArchiveZNode(UTIL.getConfiguration(), watcher);
ZKUtil.createWithParents(watcher, archivingZNode);
rss = mock(RegionServerServices.class);
} | static void function() throws Exception { setupConf(UTIL.getConfiguration()); UTIL.startMiniZKCluster(); CONNECTION = (ClusterConnection)ConnectionFactory.createConnection(UTIL.getConfiguration()); archivingClient = new ZKTableArchiveClient(UTIL.getConfiguration(), CONNECTION); ZKWatcher watcher = UTIL.getZooKeeperWatcher(); String archivingZNode = ZKTableArchiveClient.getArchiveZNode(UTIL.getConfiguration(), watcher); ZKUtil.createWithParents(watcher, archivingZNode); rss = mock(RegionServerServices.class); } | /**
* Setup the config for the cluster
*/ | Setup the config for the cluster | setupCluster | {
"repo_name": "Eshcar/hbase",
"path": "hbase-server/src/test/java/org/apache/hadoop/hbase/backup/example/TestZooKeeperTableArchiveClient.java",
"license": "apache-2.0",
"size": 18551
} | [
"org.apache.hadoop.hbase.client.ClusterConnection",
"org.apache.hadoop.hbase.client.ConnectionFactory",
"org.apache.hadoop.hbase.regionserver.RegionServerServices",
"org.apache.hadoop.hbase.zookeeper.ZKUtil",
"org.apache.hadoop.hbase.zookeeper.ZKWatcher",
"org.mockito.Mockito"
] | import org.apache.hadoop.hbase.client.ClusterConnection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.regionserver.RegionServerServices; import org.apache.hadoop.hbase.zookeeper.ZKUtil; import org.apache.hadoop.hbase.zookeeper.ZKWatcher; import org.mockito.Mockito; | import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.regionserver.*; import org.apache.hadoop.hbase.zookeeper.*; import org.mockito.*; | [
"org.apache.hadoop",
"org.mockito"
] | org.apache.hadoop; org.mockito; | 308,027 |
Map<String, String> extractUriTemplateVariables(String pattern, String path);
/**
* Given a full path, returns a {@link Comparator} suitable for sorting patterns
* in order of explicitness for that path.
* <p>The full algorithm used depends on the underlying implementation, but generally,
* the returned {@code Comparator} will
* {@linkplain java.util.Collections#sort(java.util.List, Comparator) sort} | Map<String, String> extractUriTemplateVariables(String pattern, String path); /** * Given a full path, returns a {@link Comparator} suitable for sorting patterns * in order of explicitness for that path. * <p>The full algorithm used depends on the underlying implementation, but generally, * the returned {@code Comparator} will * {@linkplain java.util.Collections#sort(java.util.List, Comparator) sort} | /**
* Given a pattern and a full path, extract the URI template variables. URI template
* variables are expressed through curly brackets ('{' and '}').
* <p>For example: For pattern "/hotels/{hotel}" and path "/hotels/1", this method will
* return a map containing "hotel"->"1".
* @param pattern the path pattern, possibly containing URI templates
* @param path the full path to extract template variables from
* @return a map, containing variable names as keys; variables values as values
*/ | Given a pattern and a full path, extract the URI template variables. URI template variables are expressed through curly brackets ('{' and '}'). For example: For pattern "/hotels/{hotel}" and path "/hotels/1", this method will return a map containing "hotel"->"1" | extractUriTemplateVariables | {
"repo_name": "sdeleuze/rxweb",
"path": "src/main/java/rxweb/support/PathMatcher.java",
"license": "apache-2.0",
"size": 5208
} | [
"java.util.Comparator",
"java.util.Map"
] | import java.util.Comparator; import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 2,150,019 |
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
} | void function(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } | /**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | This adds <code>org.eclipse.emf.edit.command.CommandParameter</code>s describing the children that can be created under this object. | collectNewChildDescriptors | {
"repo_name": "KAMP-Research/KAMP",
"path": "bundles/Toometa/toometa.qualities.edit/src/qualities/provider/UnderstandabilityItemProvider.java",
"license": "apache-2.0",
"size": 2614
} | [
"java.util.Collection"
] | import java.util.Collection; | import java.util.*; | [
"java.util"
] | java.util; | 528,102 |
public String toString() {
return "null";
}
}
private Map map;
public static final Object NULL = new Null();
public JSONObject() {
this.map = new HashMap();
}
public JSONObject(JSONObject jo, String[] names) throws JSONException {
this();
for (int i = 0; i < names.length; i += 1) {
putOnce(names[i], jo.opt(names[i]));
}
}
public JSONObject(JSONTokener x) throws JSONException {
this();
char c;
String key;
if (x.nextClean() != '{') {
throw x.syntaxError("A JSONObject text must begin with '{'");
}
for (;;) {
c = x.nextClean();
switch (c) {
case 0:
throw x.syntaxError("A JSONObject text must end with '}'");
case '}':
return;
default:
x.back();
key = x.nextValue().toString();
}
c = x.nextClean();
if (c == '=') {
if (x.next() != '>') {
x.back();
}
} else if (c != ':') {
throw x.syntaxError("Expected a ':' after a key");
}
putOnce(key, x.nextValue());
switch (x.nextClean()) {
case ';':
case ',':
if (x.nextClean() == '}') {
return;
}
x.back();
break;
case '}':
return;
default:
throw x.syntaxError("Expected a ',' or '}'");
}
}
}
public JSONObject(Map map) {
this.map = (map == null) ? new HashMap() : map;
}
public JSONObject(Map map, boolean includeSuperClass) {
this.map = new HashMap();
if (map != null) {
Iterator i = map.entrySet().iterator();
while (i.hasNext()) {
Map.Entry e = (Map.Entry)i.next();
if (isStandardProperty(e.getValue().getClass())) {
this.map.put(e.getKey(), e.getValue());
} else {
this.map.put(e.getKey(), new JSONObject(e.getValue(),
includeSuperClass));
}
}
}
}
public JSONObject(Object bean) {
this();
populateInternalMap(bean, false);
}
public JSONObject(Object bean, boolean includeSuperClass) {
this();
populateInternalMap(bean, includeSuperClass);
} | String function() { return "null"; } } private Map map; public static final Object NULL = new Null(); public JSONObject() { this.map = new HashMap(); } public JSONObject(JSONObject jo, String[] names) throws JSONException { this(); for (int i = 0; i < names.length; i += 1) { putOnce(names[i], jo.opt(names[i])); } } public JSONObject(JSONTokener x) throws JSONException { this(); char c; String key; if (x.nextClean() != '{') { throw x.syntaxError(STR); } for (;;) { c = x.nextClean(); switch (c) { case 0: throw x.syntaxError(STR); case '}': return; default: x.back(); key = x.nextValue().toString(); } c = x.nextClean(); if (c == '=') { if (x.next() != '>') { x.back(); } } else if (c != ':') { throw x.syntaxError(STR); } putOnce(key, x.nextValue()); switch (x.nextClean()) { case ';': case ',': if (x.nextClean() == '}') { return; } x.back(); break; case '}': return; default: throw x.syntaxError(STR); } } } public JSONObject(Map map) { this.map = (map == null) ? new HashMap() : map; } public JSONObject(Map map, boolean includeSuperClass) { this.map = new HashMap(); if (map != null) { Iterator i = map.entrySet().iterator(); while (i.hasNext()) { Map.Entry e = (Map.Entry)i.next(); if (isStandardProperty(e.getValue().getClass())) { this.map.put(e.getKey(), e.getValue()); } else { this.map.put(e.getKey(), new JSONObject(e.getValue(), includeSuperClass)); } } } } public JSONObject(Object bean) { this(); populateInternalMap(bean, false); } public JSONObject(Object bean, boolean includeSuperClass) { this(); populateInternalMap(bean, includeSuperClass); } | /**
* Get the "null" string value.
* @return The string "null".
*/ | Get the "null" string value | toString | {
"repo_name": "LuckyStars/nbc",
"path": "function-cardmanage/src/main/com/nbcedu/function/cardmanage/core/util/jsons/JSONObject.java",
"license": "gpl-2.0",
"size": 53212
} | [
"java.util.HashMap",
"java.util.Iterator",
"java.util.Map"
] | import java.util.HashMap; import java.util.Iterator; import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 413,938 |
RiverMouth setIndexSettings(Settings indexSettings); | RiverMouth setIndexSettings(Settings indexSettings); | /**
* Set index settings
*
* @param indexSettings the index settings
* @return this river mouth
*/ | Set index settings | setIndexSettings | {
"repo_name": "zuoyebushiwo/elasticsearch-1.5.0",
"path": "src/main/java/org/xbib/elasticsearch/river/jdbc/RiverMouth.java",
"license": "apache-2.0",
"size": 4771
} | [
"org.elasticsearch.common.settings.Settings"
] | import org.elasticsearch.common.settings.Settings; | import org.elasticsearch.common.settings.*; | [
"org.elasticsearch.common"
] | org.elasticsearch.common; | 2,806,248 |
public static void setDefaultUri(Configuration conf, URI uri) {
conf.set(FS_DEFAULT_NAME_KEY, uri.toString());
} | static void function(Configuration conf, URI uri) { conf.set(FS_DEFAULT_NAME_KEY, uri.toString()); } | /** Set the default filesystem URI in a configuration.
* @param conf the configuration to alter
* @param uri the new default filesystem uri
*/ | Set the default filesystem URI in a configuration | setDefaultUri | {
"repo_name": "ouyangjie/hadoop",
"path": "hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FileSystem.java",
"license": "apache-2.0",
"size": 116983
} | [
"org.apache.hadoop.conf.Configuration"
] | import org.apache.hadoop.conf.Configuration; | import org.apache.hadoop.conf.*; | [
"org.apache.hadoop"
] | org.apache.hadoop; | 1,213,053 |
public List<FeedbackResponseAttributes> getFeedbackResponsesFromStudentOrTeamForQuestion(
FeedbackQuestionAttributes question, StudentAttributes student) {
assert question != null;
assert student != null;
return feedbackResponsesLogic.getFeedbackResponsesFromStudentOrTeamForQuestion(question, student);
} | List<FeedbackResponseAttributes> function( FeedbackQuestionAttributes question, StudentAttributes student) { assert question != null; assert student != null; return feedbackResponsesLogic.getFeedbackResponsesFromStudentOrTeamForQuestion(question, student); } | /**
* Get existing feedback responses from student or his team for the given question.
*/ | Get existing feedback responses from student or his team for the given question | getFeedbackResponsesFromStudentOrTeamForQuestion | {
"repo_name": "TEAMMATES/teammates",
"path": "src/main/java/teammates/logic/api/Logic.java",
"license": "gpl-2.0",
"size": 53736
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 2,144,038 |
public void loadCurrentPods() {
List<Pod> pods = podSelectionAssert.getPods();
for (Pod pod : pods) {
String name = getName(pod);
if (!podAsserts.containsKey(name)) {
onPod(name, pod);
}
}
} | void function() { List<Pod> pods = podSelectionAssert.getPods(); for (Pod pod : pods) { String name = getName(pod); if (!podAsserts.containsKey(name)) { onPod(name, pod); } } } | /**
* Lets load the current pods as we don't get watch events for current pods
*/ | Lets load the current pods as we don't get watch events for current pods | loadCurrentPods | {
"repo_name": "dhirajsb/fabric8",
"path": "components/kubernetes-assertions/src/main/java/io/fabric8/kubernetes/assertions/support/PodWatcher.java",
"license": "apache-2.0",
"size": 8365
} | [
"io.fabric8.kubernetes.api.KubernetesHelper",
"io.fabric8.kubernetes.api.model.Pod",
"java.util.List"
] | import io.fabric8.kubernetes.api.KubernetesHelper; import io.fabric8.kubernetes.api.model.Pod; import java.util.List; | import io.fabric8.kubernetes.api.*; import io.fabric8.kubernetes.api.model.*; import java.util.*; | [
"io.fabric8.kubernetes",
"java.util"
] | io.fabric8.kubernetes; java.util; | 2,685,435 |
@Override
public void setAsText( String text ) throws IllegalArgumentException {
if ( allowEmpty && !StringUtils.hasText(text) ) {
// Treat empty String as null value.
setValue(null);
} else {
setValue(new LocalDateTime(formatter.parseDateTime(text)));
}
} | void function( String text ) throws IllegalArgumentException { if ( allowEmpty && !StringUtils.hasText(text) ) { setValue(null); } else { setValue(new LocalDateTime(formatter.parseDateTime(text))); } } | /**
* Parse the value from the given text, using the specified format.
*
* @param text the text to format
* @throws IllegalArgumentException
*/ | Parse the value from the given text, using the specified format | setAsText | {
"repo_name": "brunoquadrotti/menuber",
"path": "src/main/java/br/com/menuber/web/propertyeditors/LocaleDateTimeEditor.java",
"license": "mit",
"size": 2020
} | [
"org.joda.time.LocalDateTime",
"org.springframework.util.StringUtils"
] | import org.joda.time.LocalDateTime; import org.springframework.util.StringUtils; | import org.joda.time.*; import org.springframework.util.*; | [
"org.joda.time",
"org.springframework.util"
] | org.joda.time; org.springframework.util; | 59,562 |
public static DirBuilderFactory getInstance() {
return (DirBuilderFactory) Implementation.findFactory(
"dcm4che.media.DirBuilderFactory");
} | static DirBuilderFactory function() { return (DirBuilderFactory) Implementation.findFactory( STR); } | /**
* Obtain a new instance of a <code>DirBuilderFactory</code>.
* This static method creates a new factory instance.
*
* @return new DirBuilderFactory instance, never null.
*/ | Obtain a new instance of a <code>DirBuilderFactory</code>. This static method creates a new factory instance | getInstance | {
"repo_name": "medicayun/medicayundicom",
"path": "dcm4che14/trunk/src/java/org/dcm4che/media/DirBuilderFactory.java",
"license": "apache-2.0",
"size": 7749
} | [
"org.dcm4che.Implementation"
] | import org.dcm4che.Implementation; | import org.dcm4che.*; | [
"org.dcm4che"
] | org.dcm4che; | 1,863,791 |
public static String toString(String name, Object value, Object... otherPairs) {
final JsonBuffer buffer = new JsonBuffer();
buffer.add(name, value);
for (int i = 0; i < otherPairs.length; i += 2) {
buffer.add(Objects.toString(otherPairs[i]), otherPairs[i + 1]);
}
return buffer.toString();
} | static String function(String name, Object value, Object... otherPairs) { final JsonBuffer buffer = new JsonBuffer(); buffer.add(name, value); for (int i = 0; i < otherPairs.length; i += 2) { buffer.add(Objects.toString(otherPairs[i]), otherPairs[i + 1]); } return buffer.toString(); } | /** Build the Json string representation of the given pairs.
*
* @param name the name of the first attribute.
* @param value the value of the first attribute.
* @param otherPairs the other pairs.
* @return the string representation.
*/ | Build the Json string representation of the given pairs | toString | {
"repo_name": "gallandarakhneorg/afc",
"path": "core/vmutils/src/main/java/org/arakhne/afc/vmutil/json/JsonBuffer.java",
"license": "apache-2.0",
"size": 7282
} | [
"java.util.Objects"
] | import java.util.Objects; | import java.util.*; | [
"java.util"
] | java.util; | 581,098 |
public static boolean isAjax(final HttpServletRequest request) {
String ajaxHeaderName = (String)ReflectionUtils.getConfigProperty("ajaxHeader");
// check the current request's headers
if ("XMLHttpRequest".equals(request.getHeader(ajaxHeaderName))) {
return true;
}
Object ajaxCheckClosure = ReflectionUtils.getConfigProperty("ajaxCheckClosure");
if (ajaxCheckClosure instanceof Closure) {
Object result = ((Closure<?>)ajaxCheckClosure).call(request);
if (result instanceof Boolean && ((Boolean)result)) {
return true;
}
}
// look for an ajax=true parameter
if ("true".equals(request.getParameter("ajax"))) {
return true;
}
// process multipart requests
MultipartHttpServletRequest multipart = ((MultipartHttpServletRequest)request.getAttribute("org.springframework.web.multipart.MultipartHttpServletRequest"));
if (multipart != null && "true".equals(multipart.getParameter("ajax"))) {
return true;
}
// check the SavedRequest's headers
HttpSession httpSession = request.getSession(false);
if (httpSession != null) {
SavedRequest savedRequest = (SavedRequest)httpSession.getAttribute(SAVED_REQUEST);
if (savedRequest != null) {
return !savedRequest.getHeaderValues(ajaxHeaderName).isEmpty();
}
}
return false;
} | static boolean function(final HttpServletRequest request) { String ajaxHeaderName = (String)ReflectionUtils.getConfigProperty(STR); if (STR.equals(request.getHeader(ajaxHeaderName))) { return true; } Object ajaxCheckClosure = ReflectionUtils.getConfigProperty(STR); if (ajaxCheckClosure instanceof Closure) { Object result = ((Closure<?>)ajaxCheckClosure).call(request); if (result instanceof Boolean && ((Boolean)result)) { return true; } } if ("true".equals(request.getParameter("ajax"))) { return true; } MultipartHttpServletRequest multipart = ((MultipartHttpServletRequest)request.getAttribute(STR)); if (multipart != null && "true".equals(multipart.getParameter("ajax"))) { return true; } HttpSession httpSession = request.getSession(false); if (httpSession != null) { SavedRequest savedRequest = (SavedRequest)httpSession.getAttribute(SAVED_REQUEST); if (savedRequest != null) { return !savedRequest.getHeaderValues(ajaxHeaderName).isEmpty(); } } return false; } | /**
* Check if the request was triggered by an Ajax call.
* @param request the request
* @return <code>true</code> if Ajax
*/ | Check if the request was triggered by an Ajax call | isAjax | {
"repo_name": "ParadigmasAMW/pp-forum",
"path": "target/work/plugins/spring-security-core-2.0-RC4/src/java/grails/plugin/springsecurity/SpringSecurityUtils.java",
"license": "gpl-2.0",
"size": 27009
} | [
"groovy.lang.Closure",
"javax.servlet.http.HttpServletRequest",
"javax.servlet.http.HttpSession",
"org.springframework.security.web.savedrequest.SavedRequest",
"org.springframework.web.multipart.MultipartHttpServletRequest"
] | import groovy.lang.Closure; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.security.web.savedrequest.SavedRequest; import org.springframework.web.multipart.MultipartHttpServletRequest; | import groovy.lang.*; import javax.servlet.http.*; import org.springframework.security.web.savedrequest.*; import org.springframework.web.multipart.*; | [
"groovy.lang",
"javax.servlet",
"org.springframework.security",
"org.springframework.web"
] | groovy.lang; javax.servlet; org.springframework.security; org.springframework.web; | 2,251,150 |
@Override
public void close() throws IOException {
if (process == null)
return;
try {
if (error)
process.inputClient.abort();
else
process.inputClient.complete();
process.outputService.waitForFinish();
} catch (InterruptedException e) {
throw new IOException(e);
} finally {
process.close();
}
} | void function() throws IOException { if (process == null) return; try { if (error) process.inputClient.abort(); else process.inputClient.complete(); process.outputService.waitForFinish(); } catch (InterruptedException e) { throw new IOException(e); } finally { process.close(); } } | /**
* Handle the end of the input by closing down the application.
*/ | Handle the end of the input by closing down the application | close | {
"repo_name": "apache/avro",
"path": "lang/java/mapred/src/main/java/org/apache/avro/mapred/tether/TetherReducer.java",
"license": "apache-2.0",
"size": 2534
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 189,622 |
public String toXMLFragment() {
StringBuffer xml = new StringBuffer();
java.util.List<Order> orderList = getOrder();
for (Order order : orderList) {
xml.append("<Order>");
xml.append(order.toXMLFragment());
xml.append("</Order>");
}
return xml.toString();
} | String function() { StringBuffer xml = new StringBuffer(); java.util.List<Order> orderList = getOrder(); for (Order order : orderList) { xml.append(STR); xml.append(order.toXMLFragment()); xml.append(STR); } return xml.toString(); } | /**
*
* XML fragment representation of this object
*
* @return XML fragment for this object. Name for outer
* tag expected to be set by calling method. This fragment
* returns inner properties representation only
*/ | XML fragment representation of this object | toXMLFragment | {
"repo_name": "VDuda/SyncRunner-Pub",
"path": "src/API/amazon/mws/orders/model/OrderList.java",
"license": "mit",
"size": 6522
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 1,677,034 |
public static Method getMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException {
Class<?>[] primitiveTypes = DataType.getPrimitive(parameterTypes);
for (Method method : clazz.getMethods()) {
if (!method.getName().equals(methodName) || !DataType.compare(DataType.getPrimitive(method.getParameterTypes()), primitiveTypes)) {
continue;
}
return method;
}
throw new NoSuchMethodException("There is no such method in this class with the specified name and parameter types");
} | static Method function(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException { Class<?>[] primitiveTypes = DataType.getPrimitive(parameterTypes); for (Method method : clazz.getMethods()) { if (!method.getName().equals(methodName) !DataType.compare(DataType.getPrimitive(method.getParameterTypes()), primitiveTypes)) { continue; } return method; } throw new NoSuchMethodException(STR); } | /**
* Returns a method of a class with the given parameter types
*
* @param clazz Target class
* @param methodName Name of the desired method
* @param parameterTypes Parameter types of the desired method
* @return The method of the target class with the specified name and parameter types
* @throws NoSuchMethodException If the desired method of the target class with the specified name and parameter types cannot be found
* @see DataType#getPrimitive(Class[])
* @see DataType#compare(Class[], Class[])
*/ | Returns a method of a class with the given parameter types | getMethod | {
"repo_name": "NavidK0/PSCiv",
"path": "src/main/java/com/lastabyss/psciv/util/ParticleEffect.java",
"license": "mit",
"size": 96450
} | [
"java.lang.reflect.Method"
] | import java.lang.reflect.Method; | import java.lang.reflect.*; | [
"java.lang"
] | java.lang; | 2,105,525 |
private void verifyEvaluationDBO(EvaluationDBO dbo) {
EvaluationUtils.ensureNotNull(dbo.getId(), "ID");
EvaluationUtils.ensureNotNull(dbo.getEtag(), "etag");
EvaluationUtils.ensureNotNull(dbo.getName(), "name");
EvaluationUtils.ensureNotNull(dbo.getOwnerId(), "ownerID");
EvaluationUtils.ensureNotNull(dbo.getCreatedOn(), "creation date");
EvaluationUtils.ensureNotNull(dbo.getContentSource(), "content source");
EvaluationUtils.ensureNotNull(dbo.getStatusEnum(), "status");
}
| void function(EvaluationDBO dbo) { EvaluationUtils.ensureNotNull(dbo.getId(), "ID"); EvaluationUtils.ensureNotNull(dbo.getEtag(), "etag"); EvaluationUtils.ensureNotNull(dbo.getName(), "name"); EvaluationUtils.ensureNotNull(dbo.getOwnerId(), STR); EvaluationUtils.ensureNotNull(dbo.getCreatedOn(), STR); EvaluationUtils.ensureNotNull(dbo.getContentSource(), STR); EvaluationUtils.ensureNotNull(dbo.getStatusEnum(), STR); } | /**
* Ensure that a EvaluationDBO object has all required components
*
* @param dbo
*/ | Ensure that a EvaluationDBO object has all required components | verifyEvaluationDBO | {
"repo_name": "hhu94/Synapse-Repository-Services",
"path": "lib/jdomodels/src/main/java/org/sagebionetworks/evaluation/dao/EvaluationDAOImpl.java",
"license": "apache-2.0",
"size": 15567
} | [
"org.sagebionetworks.evaluation.dbo.EvaluationDBO",
"org.sagebionetworks.evaluation.util.EvaluationUtils"
] | import org.sagebionetworks.evaluation.dbo.EvaluationDBO; import org.sagebionetworks.evaluation.util.EvaluationUtils; | import org.sagebionetworks.evaluation.dbo.*; import org.sagebionetworks.evaluation.util.*; | [
"org.sagebionetworks.evaluation"
] | org.sagebionetworks.evaluation; | 288,976 |
Expression record(List<Expression> expressions); | Expression record(List<Expression> expressions); | /** Generates an expression that creates a record for a row, initializing
* its fields with the given expressions. There must be one expression per
* field.
*
* @param expressions Expression to initialize each field
* @return Expression to create a row
*/ | Generates an expression that creates a record for a row, initializing its fields with the given expressions. There must be one expression per field | record | {
"repo_name": "xhoong/incubator-calcite",
"path": "core/src/main/java/org/apache/calcite/adapter/enumerable/PhysType.java",
"license": "apache-2.0",
"size": 8052
} | [
"java.util.List",
"org.apache.calcite.linq4j.tree.Expression"
] | import java.util.List; import org.apache.calcite.linq4j.tree.Expression; | import java.util.*; import org.apache.calcite.linq4j.tree.*; | [
"java.util",
"org.apache.calcite"
] | java.util; org.apache.calcite; | 1,139,304 |
public static final URI getCleanURI( URI uri )
{
if( uri == null ) {
return uri;
}
try {
return new URI( uri.getScheme(), uri.getAuthority(), uri.getPath(), null, null );
}
catch( URISyntaxException x ) {
throw new IllegalArgumentException( x.getMessage(), x );
}
} | static final URI function( URI uri ) { if( uri == null ) { return uri; } try { return new URI( uri.getScheme(), uri.getAuthority(), uri.getPath(), null, null ); } catch( URISyntaxException x ) { throw new IllegalArgumentException( x.getMessage(), x ); } } | /**
* Returns a clean URI. This uri will be the supplied one with no query string or fragment.
*
* @param uri
*
* @return
*/ | Returns a clean URI. This uri will be the supplied one with no query string or fragment | getCleanURI | {
"repo_name": "peter-mount/filesystem",
"path": "filesystem-core/src/main/java/onl/area51/filesystem/FileSystemUtils.java",
"license": "apache-2.0",
"size": 14784
} | [
"java.net.URISyntaxException"
] | import java.net.URISyntaxException; | import java.net.*; | [
"java.net"
] | java.net; | 2,313,632 |
public void createGene(final InputStream inputDoc, final InputStream inputVary) {
// _baseGene = new Gene(inputDoc, inputVary);
// todo: reinstate this
}
| void function(final InputStream inputDoc, final InputStream inputVary) { } | /**
* set the data streams necessary to create the gene
*
*/ | set the data streams necessary to create the gene | createGene | {
"repo_name": "debrief/debrief",
"path": "org.mwc.asset.legacy/src/ASSET/Scenario/Genetic/GeneticAlgorithm.java",
"license": "epl-1.0",
"size": 26654
} | [
"java.io.InputStream"
] | import java.io.InputStream; | import java.io.*; | [
"java.io"
] | java.io; | 1,853,041 |
private void showToast(String text) {
if (LogUtil.isDebug()) Log.e(TAG, "### showToast() ###");
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
} | void function(String text) { if (LogUtil.isDebug()) Log.e(TAG, STR); Toast.makeText(this, text, Toast.LENGTH_SHORT).show(); } | /**
* Show toast with param string.
*
* @param text String to toast Display.
*/ | Show toast with param string | showToast | {
"repo_name": "TweetMap/TweetMapForAndroid",
"path": "app/src/main/java/jp/co/tweetmap/TwitterOAuthActivity.java",
"license": "apache-2.0",
"size": 9735
} | [
"android.util.Log",
"android.widget.Toast",
"jp.co.tweetmap.util.LogUtil"
] | import android.util.Log; import android.widget.Toast; import jp.co.tweetmap.util.LogUtil; | import android.util.*; import android.widget.*; import jp.co.tweetmap.util.*; | [
"android.util",
"android.widget",
"jp.co.tweetmap"
] | android.util; android.widget; jp.co.tweetmap; | 1,304,232 |
public OffsetDateTime createdOn() {
return this.createdOn;
} | OffsetDateTime function() { return this.createdOn; } | /**
* Get the createdOn property: When private cloud was created.
*
* @return the createdOn value.
*/ | Get the createdOn property: When private cloud was created | createdOn | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/vmwarecloudsimple/azure-resourcemanager-vmwarecloudsimple/src/main/java/com/azure/resourcemanager/vmwarecloudsimple/fluent/models/PrivateCloudInner.java",
"license": "mit",
"size": 20718
} | [
"java.time.OffsetDateTime"
] | import java.time.OffsetDateTime; | import java.time.*; | [
"java.time"
] | java.time; | 2,318,034 |
@SuppressWarnings("GoodTime") // this is a legacy conversion API
public static long toSeconds(Timestamp timestamp) {
return checkValid(timestamp).getSeconds();
} | @SuppressWarnings(STR) static long function(Timestamp timestamp) { return checkValid(timestamp).getSeconds(); } | /**
* Convert a Timestamp to the number of seconds elapsed from the epoch.
*
* <p>The result will be rounded down to the nearest second. E.g., if the timestamp represents
* "1969-12-31T23:59:59.999999999Z", it will be rounded to -1 second.
*/ | Convert a Timestamp to the number of seconds elapsed from the epoch. The result will be rounded down to the nearest second. E.g., if the timestamp represents "1969-12-31T23:59:59.999999999Z", it will be rounded to -1 second | toSeconds | {
"repo_name": "nwjs/chromium.src",
"path": "third_party/protobuf/java/util/src/main/java/com/google/protobuf/util/Timestamps.java",
"license": "bsd-3-clause",
"size": 17642
} | [
"com.google.protobuf.Timestamp"
] | import com.google.protobuf.Timestamp; | import com.google.protobuf.*; | [
"com.google.protobuf"
] | com.google.protobuf; | 156,553 |
public long getTimeInMillis(Calendar startInstant)
{
Calendar cal = (Calendar) startInstant.clone();
long t1 = cal.getTimeInMillis();
addTo(cal);
long t2 = cal.getTimeInMillis();
return t2 - t1;
} | long function(Calendar startInstant) { Calendar cal = (Calendar) startInstant.clone(); long t1 = cal.getTimeInMillis(); addTo(cal); long t2 = cal.getTimeInMillis(); return t2 - t1; } | /**
* Returns the duration length in milliseconds.
* Because the length of a month or year may vary depending on the year,
* the <code>startInstant</code> parameter is used to specify the duration
* offset.
*/ | Returns the duration length in milliseconds. Because the length of a month or year may vary depending on the year, the <code>startInstant</code> parameter is used to specify the duration offset | getTimeInMillis | {
"repo_name": "SanDisk-Open-Source/SSD_Dashboard",
"path": "uefi/gcc/gcc-4.6.3/libjava/classpath/javax/xml/datatype/Duration.java",
"license": "gpl-2.0",
"size": 8271
} | [
"java.util.Calendar"
] | import java.util.Calendar; | import java.util.*; | [
"java.util"
] | java.util; | 946,236 |
public boolean addAll(Collection<? extends E> c) {
throw new UnsupportedOperationException();
} | boolean function(Collection<? extends E> c) { throw new UnsupportedOperationException(); } | /**
* Unsupported Operation. If you wish to add new data sources,
* do so in the underlying ReaderIteratorFactory
*/ | Unsupported Operation. If you wish to add new data sources, do so in the underlying ReaderIteratorFactory | addAll | {
"repo_name": "simplyianm/stanford-corenlp",
"path": "src/main/java/edu/stanford/nlp/objectbank/ObjectBank.java",
"license": "gpl-2.0",
"size": 14062
} | [
"java.util.Collection"
] | import java.util.Collection; | import java.util.*; | [
"java.util"
] | java.util; | 2,512,617 |
public void reportOutdating(final IFile outdatedFile) {
final IPreferencesService service = Platform.getPreferencesService();
final boolean useOnTheFlyParsing = service.getBoolean(ProductConstants.PRODUCT_ID_DESIGNER, PreferenceConstants.USEONTHEFLYPARSING,
true, null);
synchronized (this) {
syntacticallyOutdated = true;
if (uptodateFiles.containsKey(outdatedFile)) {
uptodateFiles.remove(outdatedFile);
unsupportedConstructMap.remove(outdatedFile);
}
if (highlySyntaxErroneousFiles.contains(outdatedFile)) {
highlySyntaxErroneousFiles.remove(outdatedFile);
}
sourceParser.getSemanticAnalyzer().reportOutdating(outdatedFile, useOnTheFlyParsing);
}
} | void function(final IFile outdatedFile) { final IPreferencesService service = Platform.getPreferencesService(); final boolean useOnTheFlyParsing = service.getBoolean(ProductConstants.PRODUCT_ID_DESIGNER, PreferenceConstants.USEONTHEFLYPARSING, true, null); synchronized (this) { syntacticallyOutdated = true; if (uptodateFiles.containsKey(outdatedFile)) { uptodateFiles.remove(outdatedFile); unsupportedConstructMap.remove(outdatedFile); } if (highlySyntaxErroneousFiles.contains(outdatedFile)) { highlySyntaxErroneousFiles.remove(outdatedFile); } sourceParser.getSemanticAnalyzer().reportOutdating(outdatedFile, useOnTheFlyParsing); } } | /**
* Reports that the provided file has changed and so it's stored
* information became out of date.
* <p>
* Stores that this file is out of date for later usage
* <p>
*
* @param outdatedFile
* the file which seems to have changed
* */ | Reports that the provided file has changed and so it's stored information became out of date. Stores that this file is out of date for later usage | reportOutdating | {
"repo_name": "eroslevi/titan.EclipsePlug-ins",
"path": "org.eclipse.titan.designer/src/org/eclipse/titan/designer/parsers/ProjectSourceSyntacticAnalyzer.java",
"license": "epl-1.0",
"size": 33730
} | [
"org.eclipse.core.resources.IFile",
"org.eclipse.core.runtime.Platform",
"org.eclipse.core.runtime.preferences.IPreferencesService",
"org.eclipse.titan.designer.preferences.PreferenceConstants",
"org.eclipse.titan.designer.productUtilities.ProductConstants"
] | import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.preferences.IPreferencesService; import org.eclipse.titan.designer.preferences.PreferenceConstants; import org.eclipse.titan.designer.productUtilities.ProductConstants; | import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.core.runtime.preferences.*; import org.eclipse.titan.designer.*; import org.eclipse.titan.designer.preferences.*; | [
"org.eclipse.core",
"org.eclipse.titan"
] | org.eclipse.core; org.eclipse.titan; | 752,831 |
private boolean handleManualMigration() {
// It is expected that server startup fails with migration-mode-manual
if (!MIGRATION_MODE_MANUAL.equals(System.getProperty(MIGRATION_MODE_PROPERTY))) {
return false;
}
String authServerHome = System.getProperty(AUTH_SERVER_HOME_PROPERTY);
if (authServerHome == null) {
log.warnf("Property '%s' was missing during manual mode migration test", AUTH_SERVER_HOME_PROPERTY);
return false;
}
String sqlScriptPath = authServerHome + File.separator + "keycloak-database-update.sql";
if (!new File(sqlScriptPath).exists()) {
log.warnf("File '%s' didn't exists during manual mode migration test", sqlScriptPath);
return false;
}
// Run manual migration with the ant task
log.infof("Running SQL script created by liquibase during manual migration flow", sqlScriptPath);
String prefix = "keycloak.connectionsJpa.";
String jdbcDriver = System.getProperty(prefix + "driver");
String dbUrl = StringPropertyReplacer.replaceProperties(System.getProperty(prefix + "url"));
String dbUser = System.getProperty(prefix + "user");
String dbPassword = System.getProperty(prefix + "password");
SqlUtils.runSqlScript(sqlScriptPath, jdbcDriver, dbUrl, dbUser, dbPassword);
return true;
}
private static final Pattern RECOGNIZED_ERRORS = Pattern.compile("ERROR \\[|SEVERE \\[|Exception ");
private static final Pattern IGNORED = Pattern.compile("Jetty ALPN support not found|org.keycloak.events"); | boolean function() { if (!MIGRATION_MODE_MANUAL.equals(System.getProperty(MIGRATION_MODE_PROPERTY))) { return false; } String authServerHome = System.getProperty(AUTH_SERVER_HOME_PROPERTY); if (authServerHome == null) { log.warnf(STR, AUTH_SERVER_HOME_PROPERTY); return false; } String sqlScriptPath = authServerHome + File.separator + STR; if (!new File(sqlScriptPath).exists()) { log.warnf(STR, sqlScriptPath); return false; } log.infof(STR, sqlScriptPath); String prefix = STR; String jdbcDriver = System.getProperty(prefix + STR); String dbUrl = StringPropertyReplacer.replaceProperties(System.getProperty(prefix + "url")); String dbUser = System.getProperty(prefix + "user"); String dbPassword = System.getProperty(prefix + STR); SqlUtils.runSqlScript(sqlScriptPath, jdbcDriver, dbUrl, dbUser, dbPassword); return true; } private static final Pattern RECOGNIZED_ERRORS = Pattern.compile(STR); private static final Pattern IGNORED = Pattern.compile(STR); | /**
* Returns true if we are in manual DB migration test and if the previously created SQL script was successfully executed.
* Returns false if we are not in manual DB migration test or SQL script couldn't be executed for any reason.
* @return see method description
*/ | Returns true if we are in manual DB migration test and if the previously created SQL script was successfully executed. Returns false if we are not in manual DB migration test or SQL script couldn't be executed for any reason | handleManualMigration | {
"repo_name": "mposolda/keycloak",
"path": "testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/arquillian/AuthServerTestEnricher.java",
"license": "apache-2.0",
"size": 45636
} | [
"java.io.File",
"java.util.regex.Pattern",
"org.keycloak.common.util.StringPropertyReplacer",
"org.keycloak.testsuite.util.SqlUtils"
] | import java.io.File; import java.util.regex.Pattern; import org.keycloak.common.util.StringPropertyReplacer; import org.keycloak.testsuite.util.SqlUtils; | import java.io.*; import java.util.regex.*; import org.keycloak.common.util.*; import org.keycloak.testsuite.util.*; | [
"java.io",
"java.util",
"org.keycloak.common",
"org.keycloak.testsuite"
] | java.io; java.util; org.keycloak.common; org.keycloak.testsuite; | 1,632,706 |
private String findScript(String script) {
try {
File scriptFile = new File(cl.getResource(script).toURI());
if (scriptFile.exists()) {
return scriptFile.toPath().toString();
}
}
catch (URISyntaxException ignored) {}
return null;
} | String function(String script) { try { File scriptFile = new File(cl.getResource(script).toURI()); if (scriptFile.exists()) { return scriptFile.toPath().toString(); } } catch (URISyntaxException ignored) {} return null; } | /**
* Finds the full path to a PHP script.
*/ | Finds the full path to a PHP script | findScript | {
"repo_name": "alwinmark/vertx-php",
"path": "src/main/java/io/vertx/lang/php/PhpVerticleFactory.java",
"license": "mit",
"size": 6821
} | [
"java.io.File",
"java.net.URISyntaxException"
] | import java.io.File; import java.net.URISyntaxException; | import java.io.*; import java.net.*; | [
"java.io",
"java.net"
] | java.io; java.net; | 1,088,892 |
void removeOverlayView() {
if (mToken == null) {
Log.w(TAG, "The session has been already released");
return;
}
try {
mService.removeOverlayView(mToken, mUserId);
} catch (RemoteException e) {
throw new RuntimeException(e);
}
} | void removeOverlayView() { if (mToken == null) { Log.w(TAG, STR); return; } try { mService.removeOverlayView(mToken, mUserId); } catch (RemoteException e) { throw new RuntimeException(e); } } | /**
* Removes the current overlay view.
*/ | Removes the current overlay view | removeOverlayView | {
"repo_name": "s20121035/rk3288_android5.1_repo",
"path": "frameworks/base/media/java/android/media/tv/TvInputManager.java",
"license": "gpl-3.0",
"size": 72558
} | [
"android.os.RemoteException",
"android.util.Log"
] | import android.os.RemoteException; import android.util.Log; | import android.os.*; import android.util.*; | [
"android.os",
"android.util"
] | android.os; android.util; | 1,604,198 |
protected List<SemanticException> validateStructureList( Module module,
String propName )
{
return StructureListValidator.getInstance( ).validate( module, this,
propName );
} | List<SemanticException> function( Module module, String propName ) { return StructureListValidator.getInstance( ).validate( module, this, propName ); } | /**
* Checks all structures in the specific property whose type is structure
* list property type. This method is used for element semantic check. The
* error is kept in the report design's error list.
*
* @param module
* the module
* @param propName
* the name of the structure list type
* @return the list of the errors found in validation, each of which is the
* <code>SemanticException</code> object.
*/ | Checks all structures in the specific property whose type is structure list property type. This method is used for element semantic check. The error is kept in the report design's error list | validateStructureList | {
"repo_name": "sguan-actuate/birt",
"path": "model/org.eclipse.birt.report.model/src/org/eclipse/birt/report/model/core/DesignElement.java",
"license": "epl-1.0",
"size": 113258
} | [
"java.util.List",
"org.eclipse.birt.report.model.api.activity.SemanticException",
"org.eclipse.birt.report.model.api.validators.StructureListValidator"
] | import java.util.List; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.validators.StructureListValidator; | import java.util.*; import org.eclipse.birt.report.model.api.activity.*; import org.eclipse.birt.report.model.api.validators.*; | [
"java.util",
"org.eclipse.birt"
] | java.util; org.eclipse.birt; | 132,684 |
public Iterator<Item> getItemsIterator() {
return emptyItemIterator();
} | Iterator<Item> function() { return emptyItemIterator(); } | /**
* Return all possible child items
*/ | Return all possible child items | getItemsIterator | {
"repo_name": "CleverCloud/Bianca",
"path": "bianca/src/main/java/com/clevercloud/relaxng/program/Item.java",
"license": "gpl-2.0",
"size": 6298
} | [
"java.util.Iterator"
] | import java.util.Iterator; | import java.util.*; | [
"java.util"
] | java.util; | 1,294,642 |
private void replacePath(String sourceModulePath, String targetModulePath, List<CmsResource> resources)
throws CmsException, UnsupportedEncodingException {
for (CmsResource resource : resources) {
if (resource.isFile()) {
CmsFile file = getCms().readFile(resource);
if (CmsResourceTypeXmlContent.isXmlContent(file)) {
CmsXmlContent xmlContent = CmsXmlContentFactory.unmarshal(getCms(), file);
xmlContent.setAutoCorrectionEnabled(true);
file = xmlContent.correctXmlStructure(getCms());
}
String encoding = CmsLocaleManager.getResourceEncoding(getCms(), file);
String oldContent = new String(file.getContents(), encoding);
String newContent = oldContent.replaceAll(sourceModulePath, targetModulePath);
Matcher matcher = Pattern.compile(CmsUUID.UUID_REGEX).matcher(newContent);
newContent = matcher.replaceAll("");
newContent = newContent.replaceAll("<uuid></uuid>", "");
if (!oldContent.equals(newContent)) {
file.setContents(newContent.getBytes(encoding));
if (!resource.getRootPath().startsWith(CmsWorkplace.VFS_PATH_SYSTEM)) {
if (lockResource(getCms(), resource)) {
getCms().writeFile(file);
}
} else {
getCms().writeFile(file);
}
}
}
}
}
/**
* Replaces the messages for the given resources.<p>
*
* @param descKeys the replacement mapping
* @param resources the resources to consult
*
* @throws CmsException if something goes wrong
* @throws UnsupportedEncodingException if the file content could not be read with the determined encoding | void function(String sourceModulePath, String targetModulePath, List<CmsResource> resources) throws CmsException, UnsupportedEncodingException { for (CmsResource resource : resources) { if (resource.isFile()) { CmsFile file = getCms().readFile(resource); if (CmsResourceTypeXmlContent.isXmlContent(file)) { CmsXmlContent xmlContent = CmsXmlContentFactory.unmarshal(getCms(), file); xmlContent.setAutoCorrectionEnabled(true); file = xmlContent.correctXmlStructure(getCms()); } String encoding = CmsLocaleManager.getResourceEncoding(getCms(), file); String oldContent = new String(file.getContents(), encoding); String newContent = oldContent.replaceAll(sourceModulePath, targetModulePath); Matcher matcher = Pattern.compile(CmsUUID.UUID_REGEX).matcher(newContent); newContent = matcher.replaceAll(STR<uuid></uuid>STR"); if (!oldContent.equals(newContent)) { file.setContents(newContent.getBytes(encoding)); if (!resource.getRootPath().startsWith(CmsWorkplace.VFS_PATH_SYSTEM)) { if (lockResource(getCms(), resource)) { getCms().writeFile(file); } } else { getCms().writeFile(file); } } } } } /** * Replaces the messages for the given resources.<p> * * @param descKeys the replacement mapping * @param resources the resources to consult * * @throws CmsException if something goes wrong * @throws UnsupportedEncodingException if the file content could not be read with the determined encoding | /**
* Replaces the paths within all the given resources and removes all UUIDs by an regex.<p>
*
* @param sourceModulePath the search path
* @param targetModulePath the replace path
* @param resources the resources
*
* @throws CmsException if something goes wrong
* @throws UnsupportedEncodingException if the file content could not be read with the determined encoding
*/ | Replaces the paths within all the given resources and removes all UUIDs by an regex | replacePath | {
"repo_name": "sbonoc/opencms-core",
"path": "src-modules/org/opencms/workplace/tools/modules/CmsCloneModuleThread.java",
"license": "lgpl-2.1",
"size": 44992
} | [
"java.io.UnsupportedEncodingException",
"java.util.List",
"java.util.regex.Matcher",
"java.util.regex.Pattern",
"org.opencms.file.CmsFile",
"org.opencms.file.CmsResource",
"org.opencms.file.types.CmsResourceTypeXmlContent",
"org.opencms.i18n.CmsLocaleManager",
"org.opencms.main.CmsException",
"org.opencms.util.CmsUUID",
"org.opencms.workplace.CmsWorkplace",
"org.opencms.xml.content.CmsXmlContent",
"org.opencms.xml.content.CmsXmlContentFactory"
] | import java.io.UnsupportedEncodingException; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.opencms.file.CmsFile; import org.opencms.file.CmsResource; import org.opencms.file.types.CmsResourceTypeXmlContent; import org.opencms.i18n.CmsLocaleManager; import org.opencms.main.CmsException; import org.opencms.util.CmsUUID; import org.opencms.workplace.CmsWorkplace; import org.opencms.xml.content.CmsXmlContent; import org.opencms.xml.content.CmsXmlContentFactory; | import java.io.*; import java.util.*; import java.util.regex.*; import org.opencms.file.*; import org.opencms.file.types.*; import org.opencms.i18n.*; import org.opencms.main.*; import org.opencms.util.*; import org.opencms.workplace.*; import org.opencms.xml.content.*; | [
"java.io",
"java.util",
"org.opencms.file",
"org.opencms.i18n",
"org.opencms.main",
"org.opencms.util",
"org.opencms.workplace",
"org.opencms.xml"
] | java.io; java.util; org.opencms.file; org.opencms.i18n; org.opencms.main; org.opencms.util; org.opencms.workplace; org.opencms.xml; | 915,272 |
boolean isLoanable(Book book); | boolean isLoanable(Book book); | /**
* Finds out if book has any loanable bookCopy
*
* @return if book has any loanable bookCopy
*/ | Finds out if book has any loanable bookCopy | isLoanable | {
"repo_name": "DavidLuptak/pa165-library-system",
"path": "library-system-service/src/main/java/cz/muni/fi/pa165/library/service/BookService.java",
"license": "gpl-3.0",
"size": 1971
} | [
"cz.muni.fi.pa165.library.entity.Book"
] | import cz.muni.fi.pa165.library.entity.Book; | import cz.muni.fi.pa165.library.entity.*; | [
"cz.muni.fi"
] | cz.muni.fi; | 1,710,978 |
void setStreamingStates(final List<StreamingState> states); | void setStreamingStates(final List<StreamingState> states); | /**
* set its streaming states.
*
* @param states the streaming states.
*/ | set its streaming states | setStreamingStates | {
"repo_name": "uwescience/myria",
"path": "src/edu/washington/escience/myria/operator/StreamingStateful.java",
"license": "bsd-3-clause",
"size": 485
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 1,536,655 |
@Test
public void testGetConfigClassUniqueId() {
final ConfigSource underlying = Mockito.mock(ConfigSource.class);
final ConfigSource test = new VersionLockedConfigSource(underlying, VersionCorrection.LATEST);
final DateSet result = Mockito.mock(DateSet.class);
Mockito.when(underlying.getConfig(DateSet.class, UniqueId.of("Test", "Foo"))).thenReturn(result);
assertSame(test.getConfig(DateSet.class, UniqueId.of("Test", "Foo")), result);
} | void function() { final ConfigSource underlying = Mockito.mock(ConfigSource.class); final ConfigSource test = new VersionLockedConfigSource(underlying, VersionCorrection.LATEST); final DateSet result = Mockito.mock(DateSet.class); Mockito.when(underlying.getConfig(DateSet.class, UniqueId.of("Test", "Foo"))).thenReturn(result); assertSame(test.getConfig(DateSet.class, UniqueId.of("Test", "Foo")), result); } | /**
* Tests getting an item by a class type and unique identifier.
*/ | Tests getting an item by a class type and unique identifier | testGetConfigClassUniqueId | {
"repo_name": "McLeodMoores/starling",
"path": "projects/core/src/test/java/com/opengamma/core/config/impl/VersionLockedConfigSourceTest.java",
"license": "apache-2.0",
"size": 15577
} | [
"com.opengamma.core.DateSet",
"com.opengamma.core.config.ConfigSource",
"com.opengamma.id.UniqueId",
"com.opengamma.id.VersionCorrection",
"org.mockito.Mockito",
"org.testng.Assert",
"org.testng.annotations.Test"
] | import com.opengamma.core.DateSet; import com.opengamma.core.config.ConfigSource; import com.opengamma.id.UniqueId; import com.opengamma.id.VersionCorrection; import org.mockito.Mockito; import org.testng.Assert; import org.testng.annotations.Test; | import com.opengamma.core.*; import com.opengamma.core.config.*; import com.opengamma.id.*; import org.mockito.*; import org.testng.*; import org.testng.annotations.*; | [
"com.opengamma.core",
"com.opengamma.id",
"org.mockito",
"org.testng",
"org.testng.annotations"
] | com.opengamma.core; com.opengamma.id; org.mockito; org.testng; org.testng.annotations; | 557,373 |
public void setUserService(UserService userService) {
this.userService = userService;
} | void function(UserService userService) { this.userService = userService; } | /**
* Setter of the userService
*
* @param userService
*/ | Setter of the userService | setUserService | {
"repo_name": "raulsuarezdabo/flight",
"path": "src/main/java/com/raulsuarezdabo/flight/jsf/user/AddUserBean.java",
"license": "mit",
"size": 10419
} | [
"com.raulsuarezdabo.flight.service.UserService"
] | import com.raulsuarezdabo.flight.service.UserService; | import com.raulsuarezdabo.flight.service.*; | [
"com.raulsuarezdabo.flight"
] | com.raulsuarezdabo.flight; | 1,518,060 |
private void createHeartbeatsFeed() throws NotificationFeedException {
Id.NotificationFeed streamHeartbeatsFeed = new Id.NotificationFeed.Builder()
.setNamespaceId(Id.Namespace.SYSTEM.getId())
.setCategory(Constants.Notification.Stream.STREAM_INTERNAL_FEED_CATEGORY)
.setName(Constants.Notification.Stream.STREAM_HEARTBEAT_FEED_NAME)
.setDescription("Stream heartbeats feed.")
.build();
while (true) {
try {
feedManager.getFeed(streamHeartbeatsFeed);
return;
} catch (NotificationFeedNotFoundException e) {
feedManager.createFeed(streamHeartbeatsFeed);
return;
} catch (NotificationFeedException e) {
waitBeforeRetryHeartbeatsFeedOperation();
}
}
} | void function() throws NotificationFeedException { Id.NotificationFeed streamHeartbeatsFeed = new Id.NotificationFeed.Builder() .setNamespaceId(Id.Namespace.SYSTEM.getId()) .setCategory(Constants.Notification.Stream.STREAM_INTERNAL_FEED_CATEGORY) .setName(Constants.Notification.Stream.STREAM_HEARTBEAT_FEED_NAME) .setDescription(STR) .build(); while (true) { try { feedManager.getFeed(streamHeartbeatsFeed); return; } catch (NotificationFeedNotFoundException e) { feedManager.createFeed(streamHeartbeatsFeed); return; } catch (NotificationFeedException e) { waitBeforeRetryHeartbeatsFeedOperation(); } } } | /**
* Create Notification feed for stream's heartbeats, if it does not already exist.
*/ | Create Notification feed for stream's heartbeats, if it does not already exist | createHeartbeatsFeed | {
"repo_name": "mpouttuclarke/cdap",
"path": "cdap-data-fabric/src/main/java/co/cask/cdap/data/stream/service/DistributedStreamService.java",
"license": "apache-2.0",
"size": 26137
} | [
"co.cask.cdap.common.conf.Constants",
"co.cask.cdap.notifications.feeds.NotificationFeedException",
"co.cask.cdap.notifications.feeds.NotificationFeedNotFoundException",
"co.cask.cdap.proto.Id"
] | import co.cask.cdap.common.conf.Constants; import co.cask.cdap.notifications.feeds.NotificationFeedException; import co.cask.cdap.notifications.feeds.NotificationFeedNotFoundException; import co.cask.cdap.proto.Id; | import co.cask.cdap.common.conf.*; import co.cask.cdap.notifications.feeds.*; import co.cask.cdap.proto.*; | [
"co.cask.cdap"
] | co.cask.cdap; | 1,468,974 |
public static void writeByte(ByteBuffer buf, int pos, byte v) {
buf.put(pos, v);
} | static void function(ByteBuffer buf, int pos, byte v) { buf.put(pos, v); } | /**
* Writes a single byte value (1 byte) to the output byte buffer at the given offset.
*
* @param buf output byte buffer
* @param pos offset into the byte buffer to write
* @param v byte value to write
*/ | Writes a single byte value (1 byte) to the output byte buffer at the given offset | writeByte | {
"repo_name": "wwjiang007/alluxio",
"path": "core/common/src/main/java/alluxio/util/io/ByteIOUtils.java",
"license": "apache-2.0",
"size": 8205
} | [
"java.nio.ByteBuffer"
] | import java.nio.ByteBuffer; | import java.nio.*; | [
"java.nio"
] | java.nio; | 1,642,031 |
public RecordTemplate toRecordTemplate(String role, String lang,
boolean readOnly) throws WorkflowException {
GenericRecordTemplate rt = new GenericRecordTemplate();
String label = "";
if (inputList == null)
return rt;
int count = 0;
try {
// Add all fields description in the RecordTemplate
for (int i = 0; i < inputList.size(); i++) {
// Get the item definition
Input input = (Input) inputList.get(i);
ItemImpl item = (ItemImpl) input.getItem();
if (item == null) {
item = new ItemImpl();
item.setName("label#" + count);
item.setType("text");
count++;
}
// create a new FieldTemplate and set attributes
GenericFieldTemplate ft = new GenericFieldTemplate(item.getName(), item
.getType());
if (readOnly) {
ft.setReadOnly(true);
} else {
ft.setReadOnly(input.isReadonly());
}
ft.setMandatory(input.isMandatory());
if (input.getDisplayerName() != null
&& input.getDisplayerName().length() > 0) {
ft.setDisplayerName(input.getDisplayerName());
}
if (role != null && lang != null) {
label = input.getLabel(role, lang);
if (label == null || label.length() == 0) {
ft.addLabel(item.getLabel(role, lang), lang);
} else {
ft.addLabel(label, lang);
}
}
// add parameters
Iterator<Parameter> parameters = item.iterateParameter();
Parameter param = null;
while (parameters.hasNext()) {
param = parameters.next();
if (param != null) {
ft.addParameter(param.getName(), param.getValue());
}
}
// add the new FieldTemplate in RecordTemplate
rt.addFieldTemplate(ft);
}
return rt;
} catch (FormException fe) {
throw new WorkflowException("FormImpl.toRecordTemplate()",
"workflowEngine.EX_ERR_BUILD_FIELD_TEMPLATE", fe);
}
}
// ~ Methods ////////////////////////////////////////////////////////////////
| RecordTemplate function(String role, String lang, boolean readOnly) throws WorkflowException { GenericRecordTemplate rt = new GenericRecordTemplate(); String label = STRlabel#STRtextSTRFormImpl.toRecordTemplate()STRworkflowEngine.EX_ERR_BUILD_FIELD_TEMPLATE", fe); } } | /**
* Converts this object in a RecordTemplate object
* @return the resulting RecordTemplate
*/ | Converts this object in a RecordTemplate object | toRecordTemplate | {
"repo_name": "stephaneperry/Silverpeas-Core",
"path": "ejb-core/formtemplate/src/main/java/com/silverpeas/workflow/engine/model/FormImpl.java",
"license": "agpl-3.0",
"size": 11473
} | [
"com.silverpeas.form.RecordTemplate",
"com.silverpeas.form.record.GenericRecordTemplate",
"com.silverpeas.workflow.api.WorkflowException"
] | import com.silverpeas.form.RecordTemplate; import com.silverpeas.form.record.GenericRecordTemplate; import com.silverpeas.workflow.api.WorkflowException; | import com.silverpeas.form.*; import com.silverpeas.form.record.*; import com.silverpeas.workflow.api.*; | [
"com.silverpeas.form",
"com.silverpeas.workflow"
] | com.silverpeas.form; com.silverpeas.workflow; | 1,547,249 |
public RectangleAnchor getBlockAnchor() {
return this.blockAnchor;
}
| RectangleAnchor function() { return this.blockAnchor; } | /**
* Returns the anchor point used to align a block at its (x, y) location.
* The default values is {@link RectangleAnchor#CENTER}.
*
* @return The anchor point (never <code>null</code>).
*
* @see #setBlockAnchor(RectangleAnchor)
*/ | Returns the anchor point used to align a block at its (x, y) location. The default values is <code>RectangleAnchor#CENTER</code> | getBlockAnchor | {
"repo_name": "oskopek/jfreechart-fse",
"path": "src/main/java/org/jfree/chart/renderer/xy/XYBlockRenderer.java",
"license": "lgpl-2.1",
"size": 15327
} | [
"org.jfree.chart.ui.RectangleAnchor"
] | import org.jfree.chart.ui.RectangleAnchor; | import org.jfree.chart.ui.*; | [
"org.jfree.chart"
] | org.jfree.chart; | 648,225 |
public static CheckpointStorageLocationReference encodePathAsReference(Path path) {
byte[] refBytes = path.toString().getBytes(StandardCharsets.UTF_8);
byte[] bytes = new byte[REFERENCE_MAGIC_NUMBER.length + refBytes.length];
System.arraycopy(REFERENCE_MAGIC_NUMBER, 0, bytes, 0, REFERENCE_MAGIC_NUMBER.length);
System.arraycopy(refBytes, 0, bytes, REFERENCE_MAGIC_NUMBER.length, refBytes.length);
return new CheckpointStorageLocationReference(bytes);
} | static CheckpointStorageLocationReference function(Path path) { byte[] refBytes = path.toString().getBytes(StandardCharsets.UTF_8); byte[] bytes = new byte[REFERENCE_MAGIC_NUMBER.length + refBytes.length]; System.arraycopy(REFERENCE_MAGIC_NUMBER, 0, bytes, 0, REFERENCE_MAGIC_NUMBER.length); System.arraycopy(refBytes, 0, bytes, REFERENCE_MAGIC_NUMBER.length, refBytes.length); return new CheckpointStorageLocationReference(bytes); } | /**
* Encodes the given path as a reference in bytes. The path is encoded as a UTF-8 string and
* prepended as a magic number.
*
* @param path The path to encode.
* @return The location reference.
*/ | Encodes the given path as a reference in bytes. The path is encoded as a UTF-8 string and prepended as a magic number | encodePathAsReference | {
"repo_name": "apache/flink",
"path": "flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/AbstractFsCheckpointStorageAccess.java",
"license": "apache-2.0",
"size": 15957
} | [
"java.nio.charset.StandardCharsets",
"org.apache.flink.core.fs.Path",
"org.apache.flink.runtime.state.CheckpointStorageLocationReference"
] | import java.nio.charset.StandardCharsets; import org.apache.flink.core.fs.Path; import org.apache.flink.runtime.state.CheckpointStorageLocationReference; | import java.nio.charset.*; import org.apache.flink.core.fs.*; import org.apache.flink.runtime.state.*; | [
"java.nio",
"org.apache.flink"
] | java.nio; org.apache.flink; | 185,398 |
private static void encodeDataPair(final StringBuilder buffer, final String key, final String value) throws UnsupportedEncodingException {
buffer.append('&').append(encode(key)).append('=').append(encode(value));
}
| static void function(final StringBuilder buffer, final String key, final String value) throws UnsupportedEncodingException { buffer.append('&').append(encode(key)).append('=').append(encode(value)); } | /**
* <p>Encode a key/value data pair to be used in a HTTP post request. This INCLUDES a & so the first
* key/value pair MUST be included manually, e.g:</p>
* <code>
* StringBuffer data = new StringBuffer();
* data.append(encode("guid")).append('=').append(encode(guid));
* encodeDataPair(data, "version", description.getVersion());
* </code>
*
* @param buffer the stringbuilder to append the data pair onto
* @param key the key value
* @param value the value
*/ | Encode a key/value data pair to be used in a HTTP post request. This INCLUDES a & so the first key/value pair MUST be included manually, e.g: <code> StringBuffer data = new StringBuffer(); data.append(encode("guid")).append('=').append(encode(guid)); encodeDataPair(data, "version", description.getVersion()); </code> | encodeDataPair | {
"repo_name": "syamn/Likes",
"path": "src/main/java/syam/likes/util/Metrics.java",
"license": "lgpl-3.0",
"size": 21708
} | [
"java.io.UnsupportedEncodingException"
] | import java.io.UnsupportedEncodingException; | import java.io.*; | [
"java.io"
] | java.io; | 2,743,945 |
@Test
public void testDecodeNestedObject() throws Exception{
JSONParser parser;
Object deserialized;
JSONArray array;
JSONObject object;
String input;
parser = new JSONParser();
input = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
deserialized = parser.parse(input);
array = (JSONArray)deserialized;
Assert.assertEquals("{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}", array.get(1).toString());
object = (JSONObject)array.get(1);
Assert.assertEquals("{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}", object.get("1").toString());
}
| void function() throws Exception{ JSONParser parser; Object deserialized; JSONArray array; JSONObject object; String input; parser = new JSONParser(); input = "[0,{\"1\":{\"2\":{\"3\":{\"4\STR6\STR; deserialized = parser.parse(input); array = (JSONArray)deserialized; Assert.assertEquals("{\"1\":{\"2\":{\"3\":{\"4\STR6\STR, array.get(1).toString()); object = (JSONObject)array.get(1); Assert.assertEquals("{\"2\":{\"3\":{\"4\STR6\STR, object.get("1").toString()); } | /** Ensures a nested object is decoded.
* @throws Exception if the test failed. */ | Ensures a nested object is decoded | testDecodeNestedObject | {
"repo_name": "tomwhoiscontrary/json-simple",
"path": "src/test/java/org/json/simple/parser/JSONParserTest.java",
"license": "apache-2.0",
"size": 10744
} | [
"org.json.simple.JSONArray",
"org.json.simple.JSONObject",
"org.junit.Assert"
] | import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.junit.Assert; | import org.json.simple.*; import org.junit.*; | [
"org.json.simple",
"org.junit"
] | org.json.simple; org.junit; | 2,249,879 |
private static void getAllChilds(List<Element> list,
Element parent,
Type type,
String typeValue) {
Node node;
for (int i = 0; i < parent.getChildCount(); i++) {
node = parent.getChild(i);
// using css class name as typeValue
if (Type.CLASS.equals(type)) {
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = node.cast();
if (element.getClassName()
.contains(typeValue)) {
list.add((Element) node);
}
}
} else if (Type.ID.equals(type)) {
// using the value of the id attribute as typeValue
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = node.cast();
if (element.getId()
.equals(typeValue)) {
list.add((Element) node);
}
}
} else {
// in all other cases use the tag to identify a node
if (node.getNodeType() == Node.ELEMENT_NODE) {
if (node.getNodeName()
.toUpperCase()
.equals(typeValue.toUpperCase())) {
list.add((Element) node.cast());
}
}
}
getAllChilds(list,
(Element) node.cast(),
type,
typeValue);
}
}
| static void function(List<Element> list, Element parent, Type type, String typeValue) { Node node; for (int i = 0; i < parent.getChildCount(); i++) { node = parent.getChild(i); if (Type.CLASS.equals(type)) { if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = node.cast(); if (element.getClassName() .contains(typeValue)) { list.add((Element) node); } } } else if (Type.ID.equals(type)) { if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = node.cast(); if (element.getId() .equals(typeValue)) { list.add((Element) node); } } } else { if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName() .toUpperCase() .equals(typeValue.toUpperCase())) { list.add((Element) node.cast()); } } } getAllChilds(list, (Element) node.cast(), type, typeValue); } } | /**
* <p>Returns a list of elements which match the requested
* {@link Gwt4eDOM.Type}.</p>
*
* @param list list of matching elements
* @param parent the parent element
* @param typeValue typeValue
* @param type Requested node type ({@link Gwt4eDOM.Type})
*/ | Returns a list of elements which match the requested <code>Gwt4eDOM.Type</code> | getAllChilds | {
"repo_name": "gwt4e/gwt4e",
"path": "src/main/java/org/gwt4e/core/client/Gwt4eDOM.java",
"license": "apache-2.0",
"size": 8380
} | [
"com.google.gwt.dom.client.Element",
"com.google.gwt.dom.client.Node",
"java.util.List"
] | import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Node; import java.util.List; | import com.google.gwt.dom.client.*; import java.util.*; | [
"com.google.gwt",
"java.util"
] | com.google.gwt; java.util; | 170,825 |
void validatePropertySet(String propertyName, Object value) {
if (value == null) {
Trace.log(Trace.ERROR, "Required property " + propertyName + " not set.");
throw new ExtendedIllegalStateException(
ExtendedIllegalStateException.PROPERTY_NOT_SET);
}
} | void validatePropertySet(String propertyName, Object value) { if (value == null) { Trace.log(Trace.ERROR, STR + propertyName + STR); throw new ExtendedIllegalStateException( ExtendedIllegalStateException.PROPERTY_NOT_SET); } } | /**
* Validates that the given property has been set.
*
* <p> Performs a simple null check, used to
* centralize exception handling.
*
* @param propertyName
* The property to validate.
*
* @param value
* The property value.
*
* @exception ExtendedIllegalStateException
* If the property is not set.
*
*/ | Validates that the given property has been set. Performs a simple null check, used to centralize exception handling | validatePropertySet | {
"repo_name": "piguangming/jt400",
"path": "cvsroot/src/com/ibm/as400/security/auth/RefreshAgent.java",
"license": "epl-1.0",
"size": 8191
} | [
"com.ibm.as400.access.ExtendedIllegalStateException",
"com.ibm.as400.access.Trace"
] | import com.ibm.as400.access.ExtendedIllegalStateException; import com.ibm.as400.access.Trace; | import com.ibm.as400.access.*; | [
"com.ibm.as400"
] | com.ibm.as400; | 1,213,700 |
public AddForeignConstraintAction addReference(
Column col, Column referencedCol) {
return addCustomReference(col, referencedCol);
} | AddForeignConstraintAction function( Column col, Column referencedCol) { return addCustomReference(col, referencedCol); } | /**
* Adds {@code col} as a reference to {@code referencedCol} in the
* referenced table.
*/ | Adds col as a reference to referencedCol in the referenced table | addReference | {
"repo_name": "jahlborn/sqlbuilder",
"path": "src/main/java/com/healthmarketscience/sqlbuilder/AlterTableQuery.java",
"license": "apache-2.0",
"size": 10165
} | [
"com.healthmarketscience.sqlbuilder.dbspec.Column"
] | import com.healthmarketscience.sqlbuilder.dbspec.Column; | import com.healthmarketscience.sqlbuilder.dbspec.*; | [
"com.healthmarketscience.sqlbuilder"
] | com.healthmarketscience.sqlbuilder; | 1,035,608 |
public Pair<Float, Float> verifyScaleValues(TiUIView view, boolean autoreverse)
{
ArrayList<Operation> scaleOps = new ArrayList<Operation>();
Ti2DMatrix check = this;
while (check != null) {
if (check.op != null && check.op.type == Operation.TYPE_SCALE) {
scaleOps.add(0, check.op);
}
check = check.prev;
}
Pair<Float, Float> viewCurrentScale = (view == null ?
Pair.create(Float.valueOf(1f), Float.valueOf(1f)) :
view.getAnimatedScaleValues());
if (scaleOps.size() == 0) {
return viewCurrentScale;
}
float lastToX = viewCurrentScale.first;
float lastToY = viewCurrentScale.second;
for (Operation op : scaleOps) {
if (!op.scaleFromValuesSpecified) {
// The "from" values were not specified,
// so they should be whatever the last "to" values were.
op.scaleFromX = lastToX;
op.scaleFromY = lastToY;
}
lastToX = op.scaleToX;
lastToY = op.scaleToY;
}
// If autoreversing, then the final scale values for the view will be
// whatever they are at the start. Else they are whatever the last "to" scale
// values are in the sequence.
if (autoreverse) {
return viewCurrentScale;
} else {
return Pair.create(Float.valueOf(lastToX), Float.valueOf(lastToY));
}
} | Pair<Float, Float> function(TiUIView view, boolean autoreverse) { ArrayList<Operation> scaleOps = new ArrayList<Operation>(); Ti2DMatrix check = this; while (check != null) { if (check.op != null && check.op.type == Operation.TYPE_SCALE) { scaleOps.add(0, check.op); } check = check.prev; } Pair<Float, Float> viewCurrentScale = (view == null ? Pair.create(Float.valueOf(1f), Float.valueOf(1f)) : view.getAnimatedScaleValues()); if (scaleOps.size() == 0) { return viewCurrentScale; } float lastToX = viewCurrentScale.first; float lastToY = viewCurrentScale.second; for (Operation op : scaleOps) { if (!op.scaleFromValuesSpecified) { op.scaleFromX = lastToX; op.scaleFromY = lastToY; } lastToX = op.scaleToX; lastToY = op.scaleToY; } if (autoreverse) { return viewCurrentScale; } else { return Pair.create(Float.valueOf(lastToX), Float.valueOf(lastToY)); } } | /**
* Checks all of the scale operations in the sequence and sets the appropriate
* scale "from" values for them all (in case they aren't specified), then gives
* back the final scale values that will be in effect when the animation has completed.
* @param view
* @param autoreverse
* @return Final scale values after the animation has finished.
*/ | Checks all of the scale operations in the sequence and sets the appropriate scale "from" values for them all (in case they aren't specified), then gives back the final scale values that will be in effect when the animation has completed | verifyScaleValues | {
"repo_name": "hieupham007/Titanium_Mobile",
"path": "android/titanium/src/java/org/appcelerator/titanium/view/Ti2DMatrix.java",
"license": "apache-2.0",
"size": 11161
} | [
"android.util.Pair",
"java.util.ArrayList"
] | import android.util.Pair; import java.util.ArrayList; | import android.util.*; import java.util.*; | [
"android.util",
"java.util"
] | android.util; java.util; | 108,393 |
public InputStream oneshotSearch(String query, Map args) {
args = Args.create(args);
args.put("search", query);
args.put("exec_mode", "oneshot");
// By default, don't highlight search terms in the search output.
if (!args.containsKey("segmentation")) {
args.put("segmentation", "none");
}
ResponseMessage response = post(JobCollection.REST_PATH, args);
return response.getContent();
} | InputStream function(String query, Map args) { args = Args.create(args); args.put(STR, query); args.put(STR, STR); if (!args.containsKey(STR)) { args.put(STR, "none"); } ResponseMessage response = post(JobCollection.REST_PATH, args); return response.getContent(); } | /**
* Creates a oneshot synchronous search using search arguments.
*
* @param query The search query.
* @param args The search arguments:<ul>
* <li>"output_mode": Specifies the output format of the results (XML, JSON,
* or CSV).</li>
* <li>"earliest_time": Specifies the earliest time in the time range to
* search. The time string can be a UTC time (with fractional seconds), a
* relative time specifier (to now), or a formatted time string.</li>
* <li>"latest_time": Specifies the latest time in the time range to search.
* The time string can be a UTC time (with fractional seconds), a relative
* time specifier (to now), or a formatted time string.</li>
* <li>"rf": Specifies one or more fields to add to the search.</li></ul>
* @return The search results.
*/ | Creates a oneshot synchronous search using search arguments | oneshotSearch | {
"repo_name": "etreznicek/SplunkPull",
"path": "splunk/com/splunk/Service.java",
"license": "apache-2.0",
"size": 46650
} | [
"java.io.InputStream",
"java.util.Map"
] | import java.io.InputStream; import java.util.Map; | import java.io.*; import java.util.*; | [
"java.io",
"java.util"
] | java.io; java.util; | 189,145 |
public ResultMatcher isMethodNotAllowed() {
return matcher(HttpStatus.METHOD_NOT_ALLOWED);
} | ResultMatcher function() { return matcher(HttpStatus.METHOD_NOT_ALLOWED); } | /**
* Assert the response status code is {@code HttpStatus.METHOD_NOT_ALLOWED} (405).
*/ | Assert the response status code is HttpStatus.METHOD_NOT_ALLOWED (405) | isMethodNotAllowed | {
"repo_name": "spring-projects/spring-framework",
"path": "spring-test/src/main/java/org/springframework/test/web/servlet/result/StatusResultMatchers.java",
"license": "apache-2.0",
"size": 17758
} | [
"org.springframework.http.HttpStatus",
"org.springframework.test.web.servlet.ResultMatcher"
] | import org.springframework.http.HttpStatus; import org.springframework.test.web.servlet.ResultMatcher; | import org.springframework.http.*; import org.springframework.test.web.servlet.*; | [
"org.springframework.http",
"org.springframework.test"
] | org.springframework.http; org.springframework.test; | 1,833,003 |
public int compareTo(final HttpString other) {
if(orderInt != 0 && other.orderInt != 0) {
return signum(orderInt - other.orderInt);
}
final int len = Math.min(bytes.length, other.bytes.length);
int res;
for (int i = 0; i < len; i++) {
res = signum(higher(bytes[i]) - higher(other.bytes[i]));
if (res != 0) return res;
}
// shorter strings sort higher
return signum(bytes.length - other.bytes.length);
} | int function(final HttpString other) { if(orderInt != 0 && other.orderInt != 0) { return signum(orderInt - other.orderInt); } final int len = Math.min(bytes.length, other.bytes.length); int res; for (int i = 0; i < len; i++) { res = signum(higher(bytes[i]) - higher(other.bytes[i])); if (res != 0) return res; } return signum(bytes.length - other.bytes.length); } | /**
* Compare this string to another in a case-insensitive manner.
*
* @param other the other string
* @return -1, 0, or 1
*/ | Compare this string to another in a case-insensitive manner | compareTo | {
"repo_name": "wildfly-security-incubator/undertow",
"path": "core/src/main/java/io/undertow/util/HttpString.java",
"license": "apache-2.0",
"size": 10708
} | [
"java.lang.Integer"
] | import java.lang.Integer; | import java.lang.*; | [
"java.lang"
] | java.lang; | 358,283 |
public void setReference(final String reference) {
JodaBeanUtils.notNull(reference, "reference");
this._reference = reference;
} | void function(final String reference) { JodaBeanUtils.notNull(reference, STR); this._reference = reference; } | /**
* Sets the reference.
* @param reference the new value of the property, not null
*/ | Sets the reference | setReference | {
"repo_name": "McLeodMoores/starling",
"path": "projects/financial/src/main/java/com/opengamma/financial/analytics/curve/InflationIssuerCurveTypeConfiguration.java",
"license": "apache-2.0",
"size": 8948
} | [
"org.joda.beans.JodaBeanUtils"
] | import org.joda.beans.JodaBeanUtils; | import org.joda.beans.*; | [
"org.joda.beans"
] | org.joda.beans; | 862,500 |
void resumeReadsInternal(boolean wakeup) {
boolean alreadyResumed = anyAreSet(state, STATE_READS_RESUMED);
state |= STATE_READS_RESUMED;
if(!alreadyResumed || wakeup) {
if (!anyAreSet(state, STATE_IN_LISTENER_LOOP)) {
state |= STATE_IN_LISTENER_LOOP;
getFramedChannel().runInIoThread(new Runnable() { | void resumeReadsInternal(boolean wakeup) { boolean alreadyResumed = anyAreSet(state, STATE_READS_RESUMED); state = STATE_READS_RESUMED; if(!alreadyResumed wakeup) { if (!anyAreSet(state, STATE_IN_LISTENER_LOOP)) { state = STATE_IN_LISTENER_LOOP; getFramedChannel().runInIoThread(new Runnable() { | /**
* For this class there is no difference between a resume and a wakeup
*/ | For this class there is no difference between a resume and a wakeup | resumeReadsInternal | {
"repo_name": "jasonchaffee/undertow",
"path": "core/src/main/java/io/undertow/server/protocol/framed/AbstractFramedStreamSourceChannel.java",
"license": "apache-2.0",
"size": 22330
} | [
"org.xnio.Bits"
] | import org.xnio.Bits; | import org.xnio.*; | [
"org.xnio"
] | org.xnio; | 2,085,153 |
public static BigInteger shift(BigInteger integer, int distance) {
if (integer == null) return null;
return integer.shiftLeft(distance);
} | static BigInteger function(BigInteger integer, int distance) { if (integer == null) return null; return integer.shiftLeft(distance); } | /**
* Returns a BigInteger whose value is shifted by the given distance. The shift distance when positive performs a
* left shift and when negative performs a right shift.
*
* @param integer The integer to be shifted.
* @param distance The distance to shift the integer.
* @return The given integer shifted the given distance, left if distance is positive, and right if
* distance is negative.
*/ | Returns a BigInteger whose value is shifted by the given distance. The shift distance when positive performs a left shift and when negative performs a right shift | shift | {
"repo_name": "Permafrost/Tundra.java",
"path": "src/main/java/permafrost/tundra/math/BigIntegerHelper.java",
"license": "mit",
"size": 22329
} | [
"java.math.BigInteger"
] | import java.math.BigInteger; | import java.math.*; | [
"java.math"
] | java.math; | 256,506 |
public void replaceCredentials(HomeserverConnectionConfig config) {
if (null != config && config.getCredentials() != null) {
SharedPreferences prefs = mContext.getSharedPreferences(PREFS_LOGIN, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
ArrayList<HomeserverConnectionConfig> configs = getCredentialsList();
ArrayList<JSONObject> serialized = new ArrayList<JSONObject>(configs.size());
boolean found = false;
try {
for (HomeserverConnectionConfig c : configs) {
if (c.getCredentials().userId.equals(config.getCredentials().userId)) {
serialized.add(config.toJson());
found = true;
} else {
serialized.add(c.toJson());
}
}
} catch (JSONException e) {
throw new RuntimeException("Failed to serialize connection config");
}
if (!found) return;
String ser = new JSONArray(serialized).toString();
Log.d(LOG_TAG, "Storing " + serialized.size() + " credentials");
editor.putString(PREFS_KEY_CONNECTION_CONFIGS, ser);
editor.commit();
}
} | void function(HomeserverConnectionConfig config) { if (null != config && config.getCredentials() != null) { SharedPreferences prefs = mContext.getSharedPreferences(PREFS_LOGIN, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); ArrayList<HomeserverConnectionConfig> configs = getCredentialsList(); ArrayList<JSONObject> serialized = new ArrayList<JSONObject>(configs.size()); boolean found = false; try { for (HomeserverConnectionConfig c : configs) { if (c.getCredentials().userId.equals(config.getCredentials().userId)) { serialized.add(config.toJson()); found = true; } else { serialized.add(c.toJson()); } } } catch (JSONException e) { throw new RuntimeException(STR); } if (!found) return; String ser = new JSONArray(serialized).toString(); Log.d(LOG_TAG, STR + serialized.size() + STR); editor.putString(PREFS_KEY_CONNECTION_CONFIGS, ser); editor.commit(); } } | /**
* Replace the credential from credentials list, based on credentials.userId.
* If it does not match an existing credential it does *not* insert the new credentials.
* @param config the credentials to insert
*/ | Replace the credential from credentials list, based on credentials.userId. If it does not match an existing credential it does *not* insert the new credentials | replaceCredentials | {
"repo_name": "matrix-org/matrix-android-console",
"path": "console/src/main/java/org/matrix/console/store/LoginStorage.java",
"license": "apache-2.0",
"size": 8639
} | [
"android.content.Context",
"android.content.SharedPreferences",
"android.util.Log",
"java.util.ArrayList",
"org.json.JSONArray",
"org.json.JSONException",
"org.json.JSONObject",
"org.matrix.androidsdk.HomeserverConnectionConfig"
] | import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.matrix.androidsdk.HomeserverConnectionConfig; | import android.content.*; import android.util.*; import java.util.*; import org.json.*; import org.matrix.androidsdk.*; | [
"android.content",
"android.util",
"java.util",
"org.json",
"org.matrix.androidsdk"
] | android.content; android.util; java.util; org.json; org.matrix.androidsdk; | 519,179 |
public void execute() {
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
CompletionService<Simulation> completionService = new ExecutorCompletionService<Simulation>(executor);
for (int i = 0; i < samples; ++i) {
completionService.submit(simulations[i], simulations[i]); // The return value is explicitly null.
}
final Simulation[] completedSimulations = new Simulation[samples];
try {
for (int i = 0; i < samples; i++) {
Future<Simulation> simulation = completionService.take();
completedSimulations[i] = simulation.get();
}
} catch (InterruptedException ex) {
Logger.getLogger(Simulator.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
executor.shutdownNow(); // Shutdown now - time to explode
throw new RuntimeException(ex);
}
// Get the names of the measurements.
List<String> descriptions = simulations[0].getMeasurementSuite().getDescriptions(); // Law of demeter!
List<File> fileList = Lists.newArrayList();
for (Simulation simulation : completedSimulations) {
fileList.add(simulation.getMeasurementSuite().getFile());
}
executor.shutdown();
combiner.combine(descriptions, fileList);
} | void function() { ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); CompletionService<Simulation> completionService = new ExecutorCompletionService<Simulation>(executor); for (int i = 0; i < samples; ++i) { completionService.submit(simulations[i], simulations[i]); } final Simulation[] completedSimulations = new Simulation[samples]; try { for (int i = 0; i < samples; i++) { Future<Simulation> simulation = completionService.take(); completedSimulations[i] = simulation.get(); } } catch (InterruptedException ex) { Logger.getLogger(Simulator.class.getName()).log(Level.SEVERE, null, ex); } catch (ExecutionException ex) { executor.shutdownNow(); throw new RuntimeException(ex); } List<String> descriptions = simulations[0].getMeasurementSuite().getDescriptions(); List<File> fileList = Lists.newArrayList(); for (Simulation simulation : completedSimulations) { fileList.add(simulation.getMeasurementSuite().getFile()); } executor.shutdown(); combiner.combine(descriptions, fileList); } | /**
* Executes all the experiments for this simulation. The measurement suite will
* be closed once this method completes.
*/ | Executes all the experiments for this simulation. The measurement suite will be closed once this method completes | execute | {
"repo_name": "krharrison/cilib",
"path": "simulator/src/main/java/net/sourceforge/cilib/simulator/Simulator.java",
"license": "gpl-3.0",
"size": 7182
} | [
"com.google.common.collect.Lists",
"java.io.File",
"java.util.List",
"java.util.concurrent.CompletionService",
"java.util.concurrent.ExecutionException",
"java.util.concurrent.ExecutorCompletionService",
"java.util.concurrent.ExecutorService",
"java.util.concurrent.Executors",
"java.util.concurrent.Future",
"java.util.logging.Level",
"java.util.logging.Logger"
] | import com.google.common.collect.Lists; import java.io.File; import java.util.List; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.Logger; | import com.google.common.collect.*; import java.io.*; import java.util.*; import java.util.concurrent.*; import java.util.logging.*; | [
"com.google.common",
"java.io",
"java.util"
] | com.google.common; java.io; java.util; | 2,114,510 |
public Boolean serviceName_orderable_kvmExpress_GET(String serviceName) throws IOException {
String qPath = "/dedicated/server/{serviceName}/orderable/kvmExpress";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, Boolean.class);
} | Boolean function(String serviceName) throws IOException { String qPath = STR; StringBuilder sb = path(qPath, serviceName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, Boolean.class); } | /**
* Is a KVM express orderable with your server
*
* REST: GET /dedicated/server/{serviceName}/orderable/kvmExpress
* @param serviceName [required] The internal name of your dedicated server
*/ | Is a KVM express orderable with your server | serviceName_orderable_kvmExpress_GET | {
"repo_name": "UrielCh/ovh-java-sdk",
"path": "ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java",
"license": "bsd-3-clause",
"size": 104814
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 2,046,434 |
protected Map<C, Integer> generateCompoundsToIndex() {
final CompoundSet<C> cs = getCompoundSet();
Map<C, Integer> map = new HashMap<C, Integer>();
int index = 0;
for (C currentCompound : sortedCompounds(cs)) {
C upperCasedCompound = getOptionalUpperCasedCompound(currentCompound, cs);
//if it has the uppercased compound then set this
//compounds' value to that one
if (map.containsKey(upperCasedCompound)) {
map.put(currentCompound, map.get(upperCasedCompound));
} else {
map.put(currentCompound, index++);
}
}
return map;
} | Map<C, Integer> function() { final CompoundSet<C> cs = getCompoundSet(); Map<C, Integer> map = new HashMap<C, Integer>(); int index = 0; for (C currentCompound : sortedCompounds(cs)) { C upperCasedCompound = getOptionalUpperCasedCompound(currentCompound, cs); if (map.containsKey(upperCasedCompound)) { map.put(currentCompound, map.get(upperCasedCompound)); } else { map.put(currentCompound, index++); } } return map; } | /**
* Returns a Map which encodes the contents of CompoundSet. This
* version is case-insensitive i.e. C and c both encode for the same
* position. We sort lexigraphically so if the compound set has
* not changed then neither will this.
*/ | Returns a Map which encodes the contents of CompoundSet. This version is case-insensitive i.e. C and c both encode for the same position. We sort lexigraphically so if the compound set has not changed then neither will this | generateCompoundsToIndex | {
"repo_name": "sbliven/biojava",
"path": "biojava3-core/src/main/java/org/biojava3/core/sequence/storage/FourBitSequenceReader.java",
"license": "lgpl-2.1",
"size": 6383
} | [
"java.util.HashMap",
"java.util.Map",
"org.biojava3.core.sequence.template.CompoundSet"
] | import java.util.HashMap; import java.util.Map; import org.biojava3.core.sequence.template.CompoundSet; | import java.util.*; import org.biojava3.core.sequence.template.*; | [
"java.util",
"org.biojava3.core"
] | java.util; org.biojava3.core; | 1,457,687 |
public Timestamp getCreated();
public static final String COLUMNNAME_CreatedBy = "CreatedBy"; | Timestamp function(); public static final String COLUMNNAME_CreatedBy = STR; | /** Get Created.
* Date this record was created
*/ | Get Created. Date this record was created | getCreated | {
"repo_name": "arthurmelo88/palmetalADP",
"path": "adempiere_360/base/src/org/compiere/model/I_C_Recurring.java",
"license": "gpl-2.0",
"size": 8897
} | [
"java.sql.Timestamp"
] | import java.sql.Timestamp; | import java.sql.*; | [
"java.sql"
] | java.sql; | 229,056 |
public static ValidationReport validatePreservationBinary(Binary binary, boolean failIfNoSchema) {
ValidationReport report = new ValidationReport();
InputStream inputStream = null;
try {
Optional<Schema> xmlSchema = RodaCoreFactory.getRodaSchema("premis-v2-0", null);
if (xmlSchema.isPresent()) {
inputStream = binary.getContent().createInputStream();
Source xmlFile = new StreamSource(inputStream);
Validator validator = xmlSchema.get().newValidator();
RodaErrorHandler errorHandler = new RodaErrorHandler();
validator.setErrorHandler(errorHandler);
try {
validator.validate(xmlFile);
report.setValid(errorHandler.getErrors().isEmpty());
for (SAXParseException saxParseException : errorHandler.getErrors()) {
report.addIssue(convertSAXParseException(saxParseException));
}
} catch (SAXException e) {
LOGGER.error("Error validating preservation binary " + binary.getStoragePath(), e);
report.setValid(false);
for (SAXParseException saxParseException : errorHandler.getErrors()) {
report.addIssue(convertSAXParseException(saxParseException));
}
}
} else if (failIfNoSchema) {
report.setValid(false);
report.setMessage("No schema to validate PREMIS");
}
} catch (IOException e) {
report.setValid(false);
report.setMessage(e.getMessage());
} finally {
IOUtils.closeQuietly(inputStream);
}
return report;
}
private static class RodaErrorHandler extends DefaultHandler {
List<SAXParseException> errors;
public RodaErrorHandler() {
errors = new ArrayList<>();
} | static ValidationReport function(Binary binary, boolean failIfNoSchema) { ValidationReport report = new ValidationReport(); InputStream inputStream = null; try { Optional<Schema> xmlSchema = RodaCoreFactory.getRodaSchema(STR, null); if (xmlSchema.isPresent()) { inputStream = binary.getContent().createInputStream(); Source xmlFile = new StreamSource(inputStream); Validator validator = xmlSchema.get().newValidator(); RodaErrorHandler errorHandler = new RodaErrorHandler(); validator.setErrorHandler(errorHandler); try { validator.validate(xmlFile); report.setValid(errorHandler.getErrors().isEmpty()); for (SAXParseException saxParseException : errorHandler.getErrors()) { report.addIssue(convertSAXParseException(saxParseException)); } } catch (SAXException e) { LOGGER.error(STR + binary.getStoragePath(), e); report.setValid(false); for (SAXParseException saxParseException : errorHandler.getErrors()) { report.addIssue(convertSAXParseException(saxParseException)); } } } else if (failIfNoSchema) { report.setValid(false); report.setMessage(STR); } } catch (IOException e) { report.setValid(false); report.setMessage(e.getMessage()); } finally { IOUtils.closeQuietly(inputStream); } return report; } private static class RodaErrorHandler extends DefaultHandler { List<SAXParseException> errors; public RodaErrorHandler() { errors = new ArrayList<>(); } | /**
* Validates preservation medatada (e.g. against its schema, but other
* strategies may be used)
*
* @param failIfNoSchema
*
* @param descriptiveMetadataId
*
* @param failIfNoSchema
* @throws ValidationException
*/ | Validates preservation medatada (e.g. against its schema, but other strategies may be used) | validatePreservationBinary | {
"repo_name": "rui-castro/roda",
"path": "roda-core/roda-core/src/main/java/org/roda/core/common/validation/ValidationUtils.java",
"license": "lgpl-3.0",
"size": 14950
} | [
"java.io.IOException",
"java.io.InputStream",
"java.util.ArrayList",
"java.util.List",
"java.util.Optional",
"javax.xml.transform.Source",
"javax.xml.transform.stream.StreamSource",
"javax.xml.validation.Schema",
"javax.xml.validation.Validator",
"org.apache.commons.io.IOUtils",
"org.roda.core.RodaCoreFactory",
"org.roda.core.data.v2.validation.ValidationReport",
"org.roda.core.storage.Binary",
"org.xml.sax.SAXException",
"org.xml.sax.SAXParseException",
"org.xml.sax.helpers.DefaultHandler"
] | import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.Validator; import org.apache.commons.io.IOUtils; import org.roda.core.RodaCoreFactory; import org.roda.core.data.v2.validation.ValidationReport; import org.roda.core.storage.Binary; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; | import java.io.*; import java.util.*; import javax.xml.transform.*; import javax.xml.transform.stream.*; import javax.xml.validation.*; import org.apache.commons.io.*; import org.roda.core.*; import org.roda.core.data.v2.validation.*; import org.roda.core.storage.*; import org.xml.sax.*; import org.xml.sax.helpers.*; | [
"java.io",
"java.util",
"javax.xml",
"org.apache.commons",
"org.roda.core",
"org.xml.sax"
] | java.io; java.util; javax.xml; org.apache.commons; org.roda.core; org.xml.sax; | 62,346 |
protected AbstractTransaction checkLockQueue(int partition) throws InterruptedException {
if (hstore_conf.site.queue_profiling) profilers[partition].lock_time.start();
if (trace.val)
LOG.trace(String.format("Checking lock queue for partition %d [queueSize=%d]",
partition, this.lockQueues[partition].size()));
// Poll the queue and get the next value.
AbstractTransaction nextTxn = null;
this.lockQueueBarriers[partition].lockInterruptibly();
try {
nextTxn = this.lockQueues[partition].poll();
} finally {
this.lockQueueBarriers[partition].unlock();
} // SYNCH
if (nextTxn == null) {
if (hstore_conf.site.queue_profiling) profilers[partition].lock_time.stopIfStarted();
return (nextTxn);
}
PartitionCountingCallback<AbstractTransaction> callback = nextTxn.getInitCallback();
assert(callback.isInitialized()) :
String.format("Uninitialized %s callback for %s [hashCode=%d]",
callback.getClass().getSimpleName(), nextTxn, callback.hashCode());
// HACK
if (nextTxn.isAborted()) {
if (debug.val)
LOG.warn(String.format("The next txn for partition %d is %s but it is marked as aborted.",
partition, nextTxn));
callback.decrementCounter(partition);
nextTxn = null;
}
// If this callback has already been aborted, then there is nothing we need to
// do. Somebody else will make sure that this txn is removed from the queue
else if (callback.isAborted()) {
if (debug.val)
LOG.warn(String.format("The next txn for partition %d is %s but its %s is " +
"marked as aborted. [queueSize=%d]",
partition, nextTxn, callback.getClass().getSimpleName(),
this.lockQueues[partition].size()));
callback.decrementCounter(partition);
nextTxn = null;
}
// We have something we can use
else {
if (trace.val)
LOG.trace(String.format("Good news! Partition %d is ready to execute %s! " +
"Invoking %s.run()",
partition, nextTxn, callback.getClass().getSimpleName()));
this.lockQueueLastTxns[partition] = nextTxn.getTransactionId();
}
if (nextTxn != null) {
// Send the init request for the specified partition
if (debug.val)
LOG.debug(String.format("%s - Invoking %s.run() for partition %d",
nextTxn, nextTxn.getInitCallback().getClass().getSimpleName(), partition));
try {
nextTxn.getInitCallback().run(partition);
} catch (NullPointerException ex) {
// HACK: Ignore...
if (debug.val)
LOG.warn(String.format("Unexpected error when invoking %s for %s at partition %d",
nextTxn.getInitCallback().getClass().getSimpleName(),
nextTxn, partition), ex);
} catch (Throwable ex) {
String msg = String.format("Failed to invoke %s for %s at partition %d",
nextTxn.getInitCallback().getClass().getSimpleName(),
nextTxn, partition);
throw new ServerFaultException(msg, ex, nextTxn.getTransactionId());
}
// Mark the txn being released to the given partition
nextTxn.markReleased(partition);
if (trace.val && nextTxn != null)
LOG.trace(String.format("Finished processing lock queue for partition %d [next=%s]",
partition, nextTxn));
}
if (hstore_conf.site.queue_profiling) profilers[partition].lock_time.stopIfStarted();
return (nextTxn);
}
| AbstractTransaction function(int partition) throws InterruptedException { if (hstore_conf.site.queue_profiling) profilers[partition].lock_time.start(); if (trace.val) LOG.trace(String.format(STR, partition, this.lockQueues[partition].size())); AbstractTransaction nextTxn = null; this.lockQueueBarriers[partition].lockInterruptibly(); try { nextTxn = this.lockQueues[partition].poll(); } finally { this.lockQueueBarriers[partition].unlock(); } if (nextTxn == null) { if (hstore_conf.site.queue_profiling) profilers[partition].lock_time.stopIfStarted(); return (nextTxn); } PartitionCountingCallback<AbstractTransaction> callback = nextTxn.getInitCallback(); assert(callback.isInitialized()) : String.format(STR, callback.getClass().getSimpleName(), nextTxn, callback.hashCode()); if (nextTxn.isAborted()) { if (debug.val) LOG.warn(String.format(STR, partition, nextTxn)); callback.decrementCounter(partition); nextTxn = null; } else if (callback.isAborted()) { if (debug.val) LOG.warn(String.format(STR + STR, partition, nextTxn, callback.getClass().getSimpleName(), this.lockQueues[partition].size())); callback.decrementCounter(partition); nextTxn = null; } else { if (trace.val) LOG.trace(String.format(STR + STR, partition, nextTxn, callback.getClass().getSimpleName())); this.lockQueueLastTxns[partition] = nextTxn.getTransactionId(); } if (nextTxn != null) { if (debug.val) LOG.debug(String.format(STR, nextTxn, nextTxn.getInitCallback().getClass().getSimpleName(), partition)); try { nextTxn.getInitCallback().run(partition); } catch (NullPointerException ex) { if (debug.val) LOG.warn(String.format(STR, nextTxn.getInitCallback().getClass().getSimpleName(), nextTxn, partition), ex); } catch (Throwable ex) { String msg = String.format(STR, nextTxn.getInitCallback().getClass().getSimpleName(), nextTxn, partition); throw new ServerFaultException(msg, ex, nextTxn.getTransactionId()); } nextTxn.markReleased(partition); if (trace.val && nextTxn != null) LOG.trace(String.format(STR, partition, nextTxn)); } if (hstore_conf.site.queue_profiling) profilers[partition].lock_time.stopIfStarted(); return (nextTxn); } | /**
* Check whether there are any transactions that need to be released for execution
* at the partitions controlled by this queue manager
* Returns true if we released a transaction at at least one partition
*/ | Check whether there are any transactions that need to be released for execution at the partitions controlled by this queue manager Returns true if we released a transaction at at least one partition | checkLockQueue | {
"repo_name": "malin1993ml/h-store",
"path": "src/frontend/edu/brown/hstore/TransactionQueueManager.java",
"license": "gpl-3.0",
"size": 39588
} | [
"edu.brown.hstore.callbacks.PartitionCountingCallback",
"edu.brown.hstore.txns.AbstractTransaction",
"org.voltdb.exceptions.ServerFaultException"
] | import edu.brown.hstore.callbacks.PartitionCountingCallback; import edu.brown.hstore.txns.AbstractTransaction; import org.voltdb.exceptions.ServerFaultException; | import edu.brown.hstore.callbacks.*; import edu.brown.hstore.txns.*; import org.voltdb.exceptions.*; | [
"edu.brown.hstore",
"org.voltdb.exceptions"
] | edu.brown.hstore; org.voltdb.exceptions; | 2,000,447 |
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) {
super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater);
return this;
} | Builder function( ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) { super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater); return this; } | /**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/ | Applies the given settings updater function to all of the unary API methods in this service. Note: This method does not support applying settings to streaming methods | applyToAllUnaryMethods | {
"repo_name": "googleapis/java-monitoring",
"path": "google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/v3/stub/AlertPolicyServiceStubSettings.java",
"license": "apache-2.0",
"size": 20193
} | [
"com.google.api.core.ApiFunction",
"com.google.api.gax.rpc.UnaryCallSettings"
] | import com.google.api.core.ApiFunction; import com.google.api.gax.rpc.UnaryCallSettings; | import com.google.api.core.*; import com.google.api.gax.rpc.*; | [
"com.google.api"
] | com.google.api; | 2,219,755 |
public static String getFullFileName(String fullFilename) {
File file = new File(fullFilename);
if (file.isDirectory()) {
return "";
}
String path = file.getAbsolutePath();
return path.substring(path.lastIndexOf(File.separator) + 1);
} | static String function(String fullFilename) { File file = new File(fullFilename); if (file.isDirectory()) { return ""; } String path = file.getAbsolutePath(); return path.substring(path.lastIndexOf(File.separator) + 1); } | /**
* gets the file name
*
* @param fullFilename full path ( c:/dir/file.txt)
* @return name (file.txt)
*/ | gets the file name | getFullFileName | {
"repo_name": "manso/MuGA",
"path": "src/com/utils/MyFile.java",
"license": "gpl-3.0",
"size": 4862
} | [
"java.io.File"
] | import java.io.File; | import java.io.*; | [
"java.io"
] | java.io; | 2,813,523 |
@Override
public MediaRouteSelector buildRouteSelector() {
return new MediaRouteSelector.Builder()
.addControlCategory(CastMediaControlIntent.categoryForCast(getApplicationId()))
.build();
} | MediaRouteSelector function() { return new MediaRouteSelector.Builder() .addControlCategory(CastMediaControlIntent.categoryForCast(getApplicationId())) .build(); } | /**
* Returns a new {@link MediaRouteSelector} to use for Cast device filtering for this
* particular media source or null if the application id is invalid.
*
* @return an initialized route selector or null.
*/ | Returns a new <code>MediaRouteSelector</code> to use for Cast device filtering for this particular media source or null if the application id is invalid | buildRouteSelector | {
"repo_name": "endlessm/chromium-browser",
"path": "chrome/android/features/media_router/java/src/org/chromium/chrome/browser/media/router/caf/remoting/RemotingMediaSource.java",
"license": "bsd-3-clause",
"size": 4892
} | [
"androidx.mediarouter.media.MediaRouteSelector",
"com.google.android.gms.cast.CastMediaControlIntent"
] | import androidx.mediarouter.media.MediaRouteSelector; import com.google.android.gms.cast.CastMediaControlIntent; | import androidx.mediarouter.media.*; import com.google.android.gms.cast.*; | [
"androidx.mediarouter",
"com.google.android"
] | androidx.mediarouter; com.google.android; | 879,762 |
public void writePacketData(PacketBuffer p_148840_1_) throws IOException
{
p_148840_1_.writeInt(this.field_149164_a);
p_148840_1_.writeByte(this.field_149163_b);
} | void function(PacketBuffer p_148840_1_) throws IOException { p_148840_1_.writeInt(this.field_149164_a); p_148840_1_.writeByte(this.field_149163_b); } | /**
* Writes the raw packet data to the data stream.
*/ | Writes the raw packet data to the data stream | writePacketData | {
"repo_name": "mviitanen/marsmod",
"path": "mcp/src/minecraft_server/net/minecraft/network/play/server/S19PacketEntityStatus.java",
"license": "gpl-2.0",
"size": 1473
} | [
"java.io.IOException",
"net.minecraft.network.PacketBuffer"
] | import java.io.IOException; import net.minecraft.network.PacketBuffer; | import java.io.*; import net.minecraft.network.*; | [
"java.io",
"net.minecraft.network"
] | java.io; net.minecraft.network; | 2,160,000 |
void registerDataSetObserver(DataSetObserver observer); | void registerDataSetObserver(DataSetObserver observer); | /**
* Register an observer that is called when changes happen to the data used
* by this adapter.
*
* @param observer
* the object that gets notified when the data set changes.
*/ | Register an observer that is called when changes happen to the data used by this adapter | registerDataSetObserver | {
"repo_name": "NolaDonato/GearVRf",
"path": "GVRf/Extensions/widgetLib/src/org/gearvrf/widgetlib/adapter/Adapter.java",
"license": "apache-2.0",
"size": 5497
} | [
"android.database.DataSetObserver"
] | import android.database.DataSetObserver; | import android.database.*; | [
"android.database"
] | android.database; | 600,602 |
void unregisterForT53AudioControlInfo(Handler h); | void unregisterForT53AudioControlInfo(Handler h); | /**
* Unregisters for T53 audio control information record notifications.
* Extraneous calls are tolerated silently
*
* @param h Handler to be removed from the registrant list.
*/ | Unregisters for T53 audio control information record notifications. Extraneous calls are tolerated silently | unregisterForT53AudioControlInfo | {
"repo_name": "JSDemos/android-sdk-20",
"path": "src/com/android/internal/telephony/Phone.java",
"license": "apache-2.0",
"size": 62674
} | [
"android.os.Handler"
] | import android.os.Handler; | import android.os.*; | [
"android.os"
] | android.os; | 1,071,571 |
// get schema for form
String formType = getFormType(config,xml);
String schemaFileName = getSchemaFileName(formType);
String schemaPath = getSchemaPath(schemaFileName, config);
try {
// build the schema
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
SchemaResolver resolver = new SchemaResolver();
resolver.setPrefix(config.getSchemasLocation());
factory.setResourceResolver(resolver);
InputStream is = getClass().getClassLoader().getResourceAsStream(schemaPath);
Source schemaFile = new StreamSource(is);
Schema schema = factory.newSchema(schemaFile);
javax.xml.validation.Validator validator = schema.newValidator();
// create a source from xml string
Source source = new StreamSource(new StringReader(xml));
// check input
validator.validate(source);
} catch (Exception ex) {
// exception thrown when invalid
throw new XsdValidationException(ex, formType, schemaFileName);
}
} | String formType = getFormType(config,xml); String schemaFileName = getSchemaFileName(formType); String schemaPath = getSchemaPath(schemaFileName, config); try { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); SchemaResolver resolver = new SchemaResolver(); resolver.setPrefix(config.getSchemasLocation()); factory.setResourceResolver(resolver); InputStream is = getClass().getClassLoader().getResourceAsStream(schemaPath); Source schemaFile = new StreamSource(is); Schema schema = factory.newSchema(schemaFile); javax.xml.validation.Validator validator = schema.newValidator(); Source source = new StreamSource(new StringReader(xml)); validator.validate(source); } catch (Exception ex) { throw new XsdValidationException(ex, formType, schemaFileName); } } | /**
* Validate a forms xml against its schema.
* Throws XsdValidationException if not valid.
*/ | Validate a forms xml against its schema. Throws XsdValidationException if not valid | validate | {
"repo_name": "companieshouse/forms-enablement-api",
"path": "src/main/java/com/ch/conversion/validation/XmlValidatorImpl.java",
"license": "mit",
"size": 2464
} | [
"com.ch.exception.XsdValidationException",
"java.io.InputStream",
"java.io.StringReader",
"javax.xml.XMLConstants",
"javax.xml.transform.Source",
"javax.xml.transform.stream.StreamSource",
"javax.xml.validation.Schema",
"javax.xml.validation.SchemaFactory"
] | import com.ch.exception.XsdValidationException; import java.io.InputStream; import java.io.StringReader; import javax.xml.XMLConstants; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; | import com.ch.exception.*; import java.io.*; import javax.xml.*; import javax.xml.transform.*; import javax.xml.transform.stream.*; import javax.xml.validation.*; | [
"com.ch.exception",
"java.io",
"javax.xml"
] | com.ch.exception; java.io; javax.xml; | 504,270 |
private void convertConditionRecord(List<Condition> conditions,
String conditionType, JsonNode conditionNode) {
Iterator<Map.Entry<String, JsonNode>> mapOfFields = conditionNode
.fields();
List<String> values;
Entry<String, JsonNode> field;
JsonNode fieldValue;
Iterator<JsonNode> elements;
while (mapOfFields.hasNext()) {
values = new LinkedList<String>();
field = mapOfFields.next();
fieldValue = field.getValue();
if (fieldValue.isArray()) {
elements = fieldValue.elements();
while (elements.hasNext()) {
values.add(elements.next().asText());
}
} else {
values.add(fieldValue.asText());
}
conditions.add(new Condition().withType(conditionType)
.withConditionKey(field.getKey()).withValues(values));
}
}
private static class NamedAction implements Action {
private String actionName;
public NamedAction(String actionName) {
this.actionName = actionName;
} | void function(List<Condition> conditions, String conditionType, JsonNode conditionNode) { Iterator<Map.Entry<String, JsonNode>> mapOfFields = conditionNode .fields(); List<String> values; Entry<String, JsonNode> field; JsonNode fieldValue; Iterator<JsonNode> elements; while (mapOfFields.hasNext()) { values = new LinkedList<String>(); field = mapOfFields.next(); fieldValue = field.getValue(); if (fieldValue.isArray()) { elements = fieldValue.elements(); while (elements.hasNext()) { values.add(elements.next().asText()); } } else { values.add(fieldValue.asText()); } conditions.add(new Condition().withType(conditionType) .withConditionKey(field.getKey()).withValues(values)); } } private static class NamedAction implements Action { private String actionName; public NamedAction(String actionName) { this.actionName = actionName; } | /**
* Generates a condition instance for each condition type under the
* Condition Json node.
*
* @param conditions
* the complete list of conditions
* @param conditionType
* the condition type for the condition being created.
* @param conditionNode
* each condition node to be parsed.
*/ | Generates a condition instance for each condition type under the Condition Json node | convertConditionRecord | {
"repo_name": "dagnir/aws-sdk-java",
"path": "aws-java-sdk-core/src/main/java/com/amazonaws/auth/policy/internal/JsonPolicyReader.java",
"license": "apache-2.0",
"size": 12607
} | [
"com.amazonaws.auth.policy.Action",
"com.amazonaws.auth.policy.Condition",
"com.fasterxml.jackson.databind.JsonNode",
"java.util.Iterator",
"java.util.LinkedList",
"java.util.List",
"java.util.Map"
] | import com.amazonaws.auth.policy.Action; import com.amazonaws.auth.policy.Condition; import com.fasterxml.jackson.databind.JsonNode; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; | import com.amazonaws.auth.policy.*; import com.fasterxml.jackson.databind.*; import java.util.*; | [
"com.amazonaws.auth",
"com.fasterxml.jackson",
"java.util"
] | com.amazonaws.auth; com.fasterxml.jackson; java.util; | 2,612,896 |
public Stroke getStroke(Comparable key) {
ParamChecks.nullNotPermitted(key, "key");
return (Stroke) this.store.get(key);
}
| Stroke function(Comparable key) { ParamChecks.nullNotPermitted(key, "key"); return (Stroke) this.store.get(key); } | /**
* Returns the stroke associated with the specified key, or
* <code>null</code>.
*
* @param key the key (<code>null</code> not permitted).
*
* @return The stroke, or <code>null</code>.
*
* @throws IllegalArgumentException if <code>key</code> is
* <code>null</code>.
*/ | Returns the stroke associated with the specified key, or <code>null</code> | getStroke | {
"repo_name": "Mr-Steve/LTSpice_Library_Manager",
"path": "libs/jfreechart-1.0.16/source/org/jfree/chart/StrokeMap.java",
"license": "gpl-2.0",
"size": 6853
} | [
"java.awt.Stroke",
"org.jfree.chart.util.ParamChecks"
] | import java.awt.Stroke; import org.jfree.chart.util.ParamChecks; | import java.awt.*; import org.jfree.chart.util.*; | [
"java.awt",
"org.jfree.chart"
] | java.awt; org.jfree.chart; | 2,396,385 |
@Nullable
private Map<String, Object> mapValues(Object object) {
try {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.parseMap(mapper.serialize(object));
return map;
} catch (IOException e) {
return null;
}
} | Map<String, Object> function(Object object) { try { ObjectMapper mapper = new ObjectMapper(); Map<String, Object> map = mapper.parseMap(mapper.serialize(object)); return map; } catch (IOException e) { return null; } } | /**
* Map values from model object.
*
* @param object The object to map.
* @return The mapped values or null
*/ | Map values from model object | mapValues | {
"repo_name": "mobgen/halo-android",
"path": "sdk/halo-sdk/src/main/java/com/mobgen/halo/android/sdk/core/management/models/HaloEvent.java",
"license": "apache-2.0",
"size": 9704
} | [
"com.bluelinelabs.logansquare.internal.objectmappers.ObjectMapper",
"java.io.IOException",
"java.util.Map"
] | import com.bluelinelabs.logansquare.internal.objectmappers.ObjectMapper; import java.io.IOException; import java.util.Map; | import com.bluelinelabs.logansquare.internal.objectmappers.*; import java.io.*; import java.util.*; | [
"com.bluelinelabs.logansquare",
"java.io",
"java.util"
] | com.bluelinelabs.logansquare; java.io; java.util; | 1,794,955 |
public static Map<String, Object> createUserPrefMap(List<GenericValue> recList) throws GeneralException {
Map<String, Object> userPrefMap = new LinkedHashMap<>();
if (recList != null) {
for (GenericValue value: recList) {
addPrefToMap(value, userPrefMap);
}
}
return userPrefMap;
} | static Map<String, Object> function(List<GenericValue> recList) throws GeneralException { Map<String, Object> userPrefMap = new LinkedHashMap<>(); if (recList != null) { for (GenericValue value: recList) { addPrefToMap(value, userPrefMap); } } return userPrefMap; } | /**
* Convert a List of UserPreference GenericValues to a userPrefMap.
* @param recList List of GenericValues to convert
* @throws GeneralException
* @return user preference map
*/ | Convert a List of UserPreference GenericValues to a userPrefMap | createUserPrefMap | {
"repo_name": "ilscipio/scipio-erp",
"path": "framework/common/src/org/ofbiz/common/preferences/PreferenceWorker.java",
"license": "apache-2.0",
"size": 12531
} | [
"java.util.LinkedHashMap",
"java.util.List",
"java.util.Map",
"org.ofbiz.base.util.GeneralException",
"org.ofbiz.entity.GenericValue"
] | import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.ofbiz.base.util.GeneralException; import org.ofbiz.entity.GenericValue; | import java.util.*; import org.ofbiz.base.util.*; import org.ofbiz.entity.*; | [
"java.util",
"org.ofbiz.base",
"org.ofbiz.entity"
] | java.util; org.ofbiz.base; org.ofbiz.entity; | 3,833 |
private long handleVehicleArrivingAtStop(VehicleState vehicleState,
long beginTime) {
String vehicleId = vehicleState.getVehicleId();
// If vehicle hasn't arrived at a stop then simply return the
// AVL time as the endTime.
SpatialMatch newMatch = vehicleState.getMatch();
VehicleAtStopInfo newVehicleAtStopInfo = newMatch.getAtStop();
AvlReport avlReport = vehicleState.getAvlReport();
if (newVehicleAtStopInfo == null)
return avlReport.getTime();
// Vehicle has arrived at a stop...
logger.debug("vehicleId={} arrived at stop {} with new AVL " +
"report so determining arrival time",
vehicleId, newVehicleAtStopInfo);
// Use match right at the stop. This way we are including the
// time it takes to get from the new match to the actual
// stop and not just to some distance before the stop.
SpatialMatch matchJustBeforeStop =
newMatch.getMatchAdjustedToEndOfPath();
// Determine arrival info for the new stop based on the
// old AVL report. This will give us the proper time if
// the vehicle already arrived before the current AVL
// report
SpatialMatch oldMatch = vehicleState.getPreviousMatch();
int travelTimeFromOldMatchMsec = TravelTimes.getInstance()
.expectedTravelTimeBetweenMatches(vehicleId,
avlReport.getDate(), oldMatch, matchJustBeforeStop);
// At first it appears that should use the time of the previous AVL
// report plus the travel time. But since vehicle might have just
// departed the previous stop should use that departure time instead.
// By using beginTime we are using the correct value.
long arrivalTimeBasedOnOldMatch =
beginTime + travelTimeFromOldMatchMsec;
// Need to also look at arrival time based on the new match. This
// will prevent us from using arrivalTimeBasedOnOldMatch if that
// time is in the future due to the expected travel times incorrectly
// being too long.
long arrivalTimeBasedOnNewMatch;
if (newMatch.lessThanOrEqualTo(matchJustBeforeStop)) {
// The new match is before the stop so add the travel time
// from the match to the stop to the AVL time to get the
// arrivalTimeBasedOnNewMatch.
int travelTimeFromNewMatchToStopMsec = TravelTimes.getInstance()
.expectedTravelTimeBetweenMatches(vehicleId,
avlReport.getDate(), newMatch, matchJustBeforeStop);
arrivalTimeBasedOnNewMatch =
avlReport.getTime() + travelTimeFromNewMatchToStopMsec;
} else {
// The new match is after the stop so subtract the travel time
// from the stop to the match from the AVL time to get the
// arrivalTimeBasedOnNewMatch.
SpatialMatch matchJustAfterStop =
newMatch.getMatchAdjustedToBeginningOfPath();
int travelTimeFromStoptoNewMatchMsec = TravelTimes.getInstance()
.expectedTravelTimeBetweenMatches(vehicleId,
avlReport.getDate(), matchJustAfterStop, newMatch);
arrivalTimeBasedOnNewMatch =
avlReport.getTime() - travelTimeFromStoptoNewMatchMsec;
}
// Determine which arrival time to use. If the one based on the old
// match is greater than the one based on the new match it means that
// the vehicle traveled faster than expected. This is pretty common
// since the travel times can be based on the schedule, which is often
// not very accurate. For this case need to use the arrival time
// based on the new match since we know that the vehicle has arrived
// at the stop by that time.
long arrivalTime = arrivalTimeBasedOnOldMatch;
if (arrivalTimeBasedOnNewMatch < arrivalTimeBasedOnOldMatch) {
// Use arrival time based on new match since we definitely know
// the vehicle has arrived at this time.
arrivalTime = arrivalTimeBasedOnNewMatch;
// Log what is going on
if (logger.isDebugEnabled()) {
logger.debug("For vehicleId={} using arrival time {} based " +
"on new match because it is less than the later value " +
"based on the old match of {}",
vehicleId,
Time.dateTimeStrMsec(arrivalTime),
Time.dateTimeStrMsec(arrivalTimeBasedOnOldMatch));
}
}
// Make sure the determined arrival time is greater than old AVL time.
// This check makes sure that matches and arrivals/departures are in
// the proper order for when determining historic travel times.
AvlReport previousAvlReport =
vehicleState.getPreviousAvlReportFromSuccessfulMatch();
if (arrivalTime <= previousAvlReport.getTime()) {
logger.debug("For vehicleId={} arrival time determined to be " +
"{} but that is less than or equal to the previous AVL " +
"time of {}. Therefore setting arrival time to {}.",
vehicleId,
Time.dateTimeStrMsec(arrivalTime),
Time.dateTimeStrMsec(previousAvlReport.getTime()),
Time.dateTimeStrMsec(previousAvlReport.getTime() + 1));
arrivalTime = previousAvlReport.getTime() + 1;
}
// Create the arrival time
Arrival arrival = createArrivalTime(vehicleState, arrivalTime,
newVehicleAtStopInfo.getBlock(),
newVehicleAtStopInfo.getTripIndex(),
newVehicleAtStopInfo.getStopPathIndex());
// If the arrival time is into the future then we don't want to store
// it right now because it might be so in the future that it could be
// after the next AVL report, which of course hasn't happened yet.
// This would be a problem because then the store arrivals/departures
// and matches could be out of sequence which would screw up all
// the systems that use that data. But if it is the last stop of the
// trip then should store it now because might not get another match
// for this trip and don't want to never store the arrival.
if (arrival.getTime() > avlReport.getTime()
&& newVehicleAtStopInfo.getStopPathIndex() !=
newMatch.getTrip().getNumberStopPaths() - 1) {
// Record the arrival to store into the db next time get a
// departure so that can make sure that arrival time is
// appropriately before the departure time.
vehicleState.setArrivalToStoreToDb(arrival);
} else {
// Not the complicated situation so store the arrival into db
vehicleState.setArrivalToStoreToDb(null);
storeInDbAndLog(arrival);
}
// The new endTime to be used to determine arrival/departure
// times at intermediate stops
return arrivalTime;
}
| long function(VehicleState vehicleState, long beginTime) { String vehicleId = vehicleState.getVehicleId(); SpatialMatch newMatch = vehicleState.getMatch(); VehicleAtStopInfo newVehicleAtStopInfo = newMatch.getAtStop(); AvlReport avlReport = vehicleState.getAvlReport(); if (newVehicleAtStopInfo == null) return avlReport.getTime(); logger.debug(STR + STR, vehicleId, newVehicleAtStopInfo); SpatialMatch matchJustBeforeStop = newMatch.getMatchAdjustedToEndOfPath(); SpatialMatch oldMatch = vehicleState.getPreviousMatch(); int travelTimeFromOldMatchMsec = TravelTimes.getInstance() .expectedTravelTimeBetweenMatches(vehicleId, avlReport.getDate(), oldMatch, matchJustBeforeStop); long arrivalTimeBasedOnOldMatch = beginTime + travelTimeFromOldMatchMsec; long arrivalTimeBasedOnNewMatch; if (newMatch.lessThanOrEqualTo(matchJustBeforeStop)) { int travelTimeFromNewMatchToStopMsec = TravelTimes.getInstance() .expectedTravelTimeBetweenMatches(vehicleId, avlReport.getDate(), newMatch, matchJustBeforeStop); arrivalTimeBasedOnNewMatch = avlReport.getTime() + travelTimeFromNewMatchToStopMsec; } else { SpatialMatch matchJustAfterStop = newMatch.getMatchAdjustedToBeginningOfPath(); int travelTimeFromStoptoNewMatchMsec = TravelTimes.getInstance() .expectedTravelTimeBetweenMatches(vehicleId, avlReport.getDate(), matchJustAfterStop, newMatch); arrivalTimeBasedOnNewMatch = avlReport.getTime() - travelTimeFromStoptoNewMatchMsec; } long arrivalTime = arrivalTimeBasedOnOldMatch; if (arrivalTimeBasedOnNewMatch < arrivalTimeBasedOnOldMatch) { arrivalTime = arrivalTimeBasedOnNewMatch; if (logger.isDebugEnabled()) { logger.debug(STR + STR + STR, vehicleId, Time.dateTimeStrMsec(arrivalTime), Time.dateTimeStrMsec(arrivalTimeBasedOnOldMatch)); } } AvlReport previousAvlReport = vehicleState.getPreviousAvlReportFromSuccessfulMatch(); if (arrivalTime <= previousAvlReport.getTime()) { logger.debug(STR + STR + STR, vehicleId, Time.dateTimeStrMsec(arrivalTime), Time.dateTimeStrMsec(previousAvlReport.getTime()), Time.dateTimeStrMsec(previousAvlReport.getTime() + 1)); arrivalTime = previousAvlReport.getTime() + 1; } Arrival arrival = createArrivalTime(vehicleState, arrivalTime, newVehicleAtStopInfo.getBlock(), newVehicleAtStopInfo.getTripIndex(), newVehicleAtStopInfo.getStopPathIndex()); if (arrival.getTime() > avlReport.getTime() && newVehicleAtStopInfo.getStopPathIndex() != newMatch.getTrip().getNumberStopPaths() - 1) { vehicleState.setArrivalToStoreToDb(arrival); } else { vehicleState.setArrivalToStoreToDb(null); storeInDbAndLog(arrival); } return arrivalTime; } | /**
* Handles the case where the new match indicates that vehicle has
* arrived at a stop. Determines the appropriate arrival time.
*
* @param vehicleState
* For obtaining match and AVL info
* @param beginTime
* The time of the previous AVL report or the departure time if
* vehicle previously was at a stop.
* @return The time to be used as the endTime for determining
* arrivals/departures for intermediate stops. Will be the time of
* the new AVL report if vehicle is not at a stop. If it is at a
* stop then it will be the expected arrival time at that stop.
*/ | Handles the case where the new match indicates that vehicle has arrived at a stop. Determines the appropriate arrival time | handleVehicleArrivingAtStop | {
"repo_name": "scrudden/core",
"path": "transitime/src/main/java/org/transitime/core/ArrivalDepartureGeneratorDefaultImpl.java",
"license": "gpl-3.0",
"size": 50316
} | [
"org.transitime.db.structs.Arrival",
"org.transitime.db.structs.AvlReport",
"org.transitime.utils.Time"
] | import org.transitime.db.structs.Arrival; import org.transitime.db.structs.AvlReport; import org.transitime.utils.Time; | import org.transitime.db.structs.*; import org.transitime.utils.*; | [
"org.transitime.db",
"org.transitime.utils"
] | org.transitime.db; org.transitime.utils; | 2,492,778 |
public static boolean checkSortedFile(File file, Comparator<String> comparator)
throws Exception {
String line, prevLine;
int ctLines = 0;
// open file
BufferedReader in = new BufferedReader(new FileReader(file));
prevLine = in.readLine();
// loop until file empty
while ((line = in.readLine()) != null) {
// if line fails test, return false
if (comparator.compare(prevLine, line) > 0) {
in.close();
Logger.getLogger(FileSorter.class).info(
"SORT FAILED after " + Integer.toString(ctLines) + " lines: "
+ file.getName());
return false;
}
prevLine = line;
}
// close file
in.close();
Logger.getLogger(FileSorter.class).info(
" Sort successful: " + file.getName());
// if we've made it this far, things are good
return true;
} | static boolean function(File file, Comparator<String> comparator) throws Exception { String line, prevLine; int ctLines = 0; BufferedReader in = new BufferedReader(new FileReader(file)); prevLine = in.readLine(); while ((line = in.readLine()) != null) { if (comparator.compare(prevLine, line) > 0) { in.close(); Logger.getLogger(FileSorter.class).info( STR + Integer.toString(ctLines) + STR + file.getName()); return false; } prevLine = line; } in.close(); Logger.getLogger(FileSorter.class).info( STR + file.getName()); return true; } | /**
* Check sorted file.
*
* @param file the file
* @param comparator the comp
* @return true, if successful
* @throws Exception the exception
*/ | Check sorted file | checkSortedFile | {
"repo_name": "WestCoastInformatics/SNOMED-Terminology-Server",
"path": "jpa-services/src/main/java/org/ihtsdo/otf/ts/jpa/algo/FileSorter.java",
"license": "apache-2.0",
"size": 8784
} | [
"java.io.BufferedReader",
"java.io.File",
"java.io.FileReader",
"java.util.Comparator",
"org.apache.log4j.Logger"
] | import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.Comparator; import org.apache.log4j.Logger; | import java.io.*; import java.util.*; import org.apache.log4j.*; | [
"java.io",
"java.util",
"org.apache.log4j"
] | java.io; java.util; org.apache.log4j; | 790,078 |
public boolean getUrlMapForContentlet(Contentlet contentlet, User user, boolean respectFrontendRoles) throws DotSecurityException, DotDataException;
| boolean function(Contentlet contentlet, User user, boolean respectFrontendRoles) throws DotSecurityException, DotDataException; | /**
* Return the URL Map for the specified content if the structure associated to the content has the URL Map Pattern set.
*
* @param contentlet
* @param user
* @param respectFrontendRoles
* @return
*/ | Return the URL Map for the specified content if the structure associated to the content has the URL Map Pattern set | getUrlMapForContentlet | {
"repo_name": "zhiqinghuang/core",
"path": "src/com/dotmarketing/portlets/contentlet/business/ContentletAPIPreHook.java",
"license": "gpl-3.0",
"size": 46827
} | [
"com.dotmarketing.exception.DotDataException",
"com.dotmarketing.exception.DotSecurityException",
"com.dotmarketing.portlets.contentlet.model.Contentlet",
"com.liferay.portal.model.User"
] | import com.dotmarketing.exception.DotDataException; import com.dotmarketing.exception.DotSecurityException; import com.dotmarketing.portlets.contentlet.model.Contentlet; import com.liferay.portal.model.User; | import com.dotmarketing.exception.*; import com.dotmarketing.portlets.contentlet.model.*; import com.liferay.portal.model.*; | [
"com.dotmarketing.exception",
"com.dotmarketing.portlets",
"com.liferay.portal"
] | com.dotmarketing.exception; com.dotmarketing.portlets; com.liferay.portal; | 2,319,939 |
protected void copyProxyCookie(HttpServletRequest servletRequest,
HttpServletResponse servletResponse, String headerValue) {
//build path for resulting cookie
String path = servletRequest.getContextPath(); // path starts with / or is empty string
path += servletRequest.getServletPath(); // servlet path starts with / or is empty string
if(path.isEmpty()){
path = "/";
}
for (HttpCookie cookie : HttpCookie.parse(headerValue)) {
//set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
String proxyCookieName = doPreserveCookies ? cookie.getName() : getCookieNamePrefix(cookie.getName()) + cookie.getName();
Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
servletCookie.setComment(cookie.getComment());
servletCookie.setMaxAge((int) cookie.getMaxAge());
servletCookie.setPath(path); //set to the path of the proxy servlet
// don't set cookie domain
servletCookie.setSecure(cookie.getSecure());
servletCookie.setVersion(cookie.getVersion());
servletCookie.setHttpOnly(cookie.isHttpOnly());
servletResponse.addCookie(servletCookie);
}
} | void function(HttpServletRequest servletRequest, HttpServletResponse servletResponse, String headerValue) { String path = servletRequest.getContextPath(); path += servletRequest.getServletPath(); if(path.isEmpty()){ path = "/"; } for (HttpCookie cookie : HttpCookie.parse(headerValue)) { String proxyCookieName = doPreserveCookies ? cookie.getName() : getCookieNamePrefix(cookie.getName()) + cookie.getName(); Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue()); servletCookie.setComment(cookie.getComment()); servletCookie.setMaxAge((int) cookie.getMaxAge()); servletCookie.setPath(path); servletCookie.setSecure(cookie.getSecure()); servletCookie.setVersion(cookie.getVersion()); servletCookie.setHttpOnly(cookie.isHttpOnly()); servletResponse.addCookie(servletCookie); } } | /**
* Copy cookie from the proxy to the servlet client.
* Replaces cookie path to local path and renames cookie to avoid collisions.
*/ | Copy cookie from the proxy to the servlet client. Replaces cookie path to local path and renames cookie to avoid collisions | copyProxyCookie | {
"repo_name": "cthiebaud/HTTP-Proxy-Servlet",
"path": "src/main/java/org/mitre/dsmiley/httpproxy/ProxyServlet.java",
"license": "apache-2.0",
"size": 36868
} | [
"java.net.HttpCookie",
"javax.servlet.http.Cookie",
"javax.servlet.http.HttpServletRequest",
"javax.servlet.http.HttpServletResponse"
] | import java.net.HttpCookie; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; | import java.net.*; import javax.servlet.http.*; | [
"java.net",
"javax.servlet"
] | java.net; javax.servlet; | 2,603,333 |
public static Properties parseInstructions( final String query )
throws MalformedURLException
{
final Properties instructions = new Properties();
if( query != null )
{
try
{
// just ignore for the moment and try out if we have valid properties separated by "&"
final String segments[] = query.split( "&" );
for( String segment : segments )
{
// do not parse empty strings
if( segment.trim().length() > 0 )
{
final Matcher matcher = INSTRUCTIONS_PATTERN.matcher( segment );
if( matcher.matches() )
{
instructions.setProperty(
matcher.group( 1 ),
URLDecoder.decode( matcher.group( 2 ), "UTF-8" )
);
}
else
{
throw new MalformedURLException( "Invalid syntax for instruction [" + segment
+ "]. Take a look at http://www.aqute.biz/Code/Bnd."
);
}
}
}
}
catch( UnsupportedEncodingException e )
{
// thrown by URLDecoder but it should never happen
throwAsMalformedURLException( "Could not retrieve the instructions from [" + query + "]", e );
}
}
return instructions;
} | static Properties function( final String query ) throws MalformedURLException { final Properties instructions = new Properties(); if( query != null ) { try { final String segments[] = query.split( "&" ); for( String segment : segments ) { if( segment.trim().length() > 0 ) { final Matcher matcher = INSTRUCTIONS_PATTERN.matcher( segment ); if( matcher.matches() ) { instructions.setProperty( matcher.group( 1 ), URLDecoder.decode( matcher.group( 2 ), "UTF-8" ) ); } else { throw new MalformedURLException( STR + segment + STRCould not retrieve the instructions from [STR]", e ); } } return instructions; } | /**
* Parses bnd instructions out of an url query string.
*
* @param query query part of an url.
*
* @return parsed instructions as properties
*
* @throws java.net.MalformedURLException if provided path does not comply to syntax.
*/ | Parses bnd instructions out of an url query string | parseInstructions | {
"repo_name": "apache/servicemix4-nmr",
"path": "jbi/deployer/src/main/java/org/apache/servicemix/jbi/deployer/handler/Parser.java",
"license": "apache-2.0",
"size": 8049
} | [
"java.net.MalformedURLException",
"java.net.URLDecoder",
"java.util.Properties",
"java.util.regex.Matcher"
] | import java.net.MalformedURLException; import java.net.URLDecoder; import java.util.Properties; import java.util.regex.Matcher; | import java.net.*; import java.util.*; import java.util.regex.*; | [
"java.net",
"java.util"
] | java.net; java.util; | 1,683,251 |
public void updateWatermarkGeneration() {
if(idleAfterWatermarkGenerations > 0) {
final List<Entry<String, Long>> elementsToRemove = watermarkActive
.entrySet()
.stream()
.filter(e -> (e.getValue() <= watermarkGeneration - idleAfterWatermarkGenerations))
.collect(Collectors.toList());
logger.debug("Perform invalidation of {} idle entries", elementsToRemove.size());
for(final Entry<String, Long> entry : elementsToRemove) {
final String key = entry.getKey();
affectedRegions.remove(key);
watermarkActive.remove(key);
}
}
watermarkGeneration++;
} | void function() { if(idleAfterWatermarkGenerations > 0) { final List<Entry<String, Long>> elementsToRemove = watermarkActive .entrySet() .stream() .filter(e -> (e.getValue() <= watermarkGeneration - idleAfterWatermarkGenerations)) .collect(Collectors.toList()); logger.debug(STR, elementsToRemove.size()); for(final Entry<String, Long> entry : elementsToRemove) { final String key = entry.getKey(); affectedRegions.remove(key); watermarkActive.remove(key); } } watermarkGeneration++; } | /**
* Update the watermark generation and remove
* idle entries
*/ | Update the watermark generation and remove idle entries | updateWatermarkGeneration | {
"repo_name": "jnidzwetzki/bboxdb",
"path": "bboxdb-server/src/main/java/org/bboxdb/network/client/tools/InvalidationHelper.java",
"license": "apache-2.0",
"size": 7288
} | [
"java.util.List",
"java.util.Map",
"java.util.stream.Collectors"
] | import java.util.List; import java.util.Map; import java.util.stream.Collectors; | import java.util.*; import java.util.stream.*; | [
"java.util"
] | java.util; | 496,856 |
@SuppressWarnings("unchecked")
public AB order(SortOrder order) {
if (order == null) {
throw new IllegalArgumentException("[order] must not be null");
}
this.order = order;
return (AB) this;
} | @SuppressWarnings(STR) AB function(SortOrder order) { if (order == null) { throw new IllegalArgumentException(STR); } this.order = order; return (AB) this; } | /**
* Sets the {@link SortOrder} to use to sort values produced this source
*/ | Sets the <code>SortOrder</code> to use to sort values produced this source | order | {
"repo_name": "nknize/elasticsearch",
"path": "server/src/main/java/org/elasticsearch/search/aggregations/bucket/composite/CompositeValuesSourceBuilder.java",
"license": "apache-2.0",
"size": 9353
} | [
"org.elasticsearch.search.sort.SortOrder"
] | import org.elasticsearch.search.sort.SortOrder; | import org.elasticsearch.search.sort.*; | [
"org.elasticsearch.search"
] | org.elasticsearch.search; | 2,418,206 |
public SubSlot getSlotForTask(ExecutionVertex vertex) {
synchronized (lock) {
Pair<SharedSlot, Locality> p = getSlotForTaskInternal(vertex.getJobvertexId(), vertex, vertex.getPreferredLocations(), false);
if (p != null) {
SharedSlot ss = p.getLeft();
SubSlot slot = ss.allocateSubSlot(vertex.getJobvertexId());
slot.setLocality(p.getRight());
return slot;
}
else {
return null;
}
}
}
| SubSlot function(ExecutionVertex vertex) { synchronized (lock) { Pair<SharedSlot, Locality> p = getSlotForTaskInternal(vertex.getJobvertexId(), vertex, vertex.getPreferredLocations(), false); if (p != null) { SharedSlot ss = p.getLeft(); SubSlot slot = ss.allocateSubSlot(vertex.getJobvertexId()); slot.setLocality(p.getRight()); return slot; } else { return null; } } } | /**
* Gets a slot suitable for the given task vertex. This method will prefer slots that are local
* (with respect to {@link ExecutionVertex#getPreferredLocations()}), but will return non local
* slots if no local slot is available. The method returns null, when no slot is available for the
* given JobVertexID at all.
*
* @param vertex
*
* @return A task vertex for a task with the given JobVertexID, or null, if none is available.
*/ | Gets a slot suitable for the given task vertex. This method will prefer slots that are local (with respect to <code>ExecutionVertex#getPreferredLocations()</code>), but will return non local slots if no local slot is available. The method returns null, when no slot is available for the given JobVertexID at all | getSlotForTask | {
"repo_name": "citlab/vs.msc.ws14",
"path": "flink-0-7-custom/flink-runtime/src/main/java/org/apache/flink/runtime/jobmanager/scheduler/SlotSharingGroupAssignment.java",
"license": "apache-2.0",
"size": 12847
} | [
"org.apache.commons.lang3.tuple.Pair",
"org.apache.flink.runtime.executiongraph.ExecutionVertex"
] | import org.apache.commons.lang3.tuple.Pair; import org.apache.flink.runtime.executiongraph.ExecutionVertex; | import org.apache.commons.lang3.tuple.*; import org.apache.flink.runtime.executiongraph.*; | [
"org.apache.commons",
"org.apache.flink"
] | org.apache.commons; org.apache.flink; | 698,504 |
public Builder addAllDefaultTaxRate(List<String> elements) {
if (this.defaultTaxRates == null) {
this.defaultTaxRates = new ArrayList<>();
}
this.defaultTaxRates.addAll(elements);
return this;
} | Builder function(List<String> elements) { if (this.defaultTaxRates == null) { this.defaultTaxRates = new ArrayList<>(); } this.defaultTaxRates.addAll(elements); return this; } | /**
* Add all elements to `defaultTaxRates` list. A list is initialized for the first
* `add/addAll` call, and subsequent calls adds additional elements to the original list. See
* {@link SessionCreateParams.SubscriptionData#defaultTaxRates} for the field documentation.
*/ | Add all elements to `defaultTaxRates` list. A list is initialized for the first `add/addAll` call, and subsequent calls adds additional elements to the original list. See <code>SessionCreateParams.SubscriptionData#defaultTaxRates</code> for the field documentation | addAllDefaultTaxRate | {
"repo_name": "stripe/stripe-java",
"path": "src/main/java/com/stripe/param/checkout/SessionCreateParams.java",
"license": "mit",
"size": 222478
} | [
"java.util.ArrayList",
"java.util.List"
] | import java.util.ArrayList; import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 2,385,488 |
public CiphertextMessage encrypt(byte[] paddedMessage) {
synchronized (SESSION_LOCK) {
SessionRecord sessionRecord = sessionStore.loadSession(remoteAddress);
SessionState sessionState = sessionRecord.getSessionState();
ChainKey chainKey = sessionState.getSenderChainKey();
MessageKeys messageKeys = chainKey.getMessageKeys();
ECPublicKey senderEphemeral = sessionState.getSenderRatchetKey();
int previousCounter = sessionState.getPreviousCounter();
int sessionVersion = sessionState.getSessionVersion();
byte[] ciphertextBody = getCiphertext(sessionVersion, messageKeys, paddedMessage);
CiphertextMessage ciphertextMessage = new WhisperMessage(sessionVersion, messageKeys.getMacKey(),
senderEphemeral, chainKey.getIndex(),
previousCounter, ciphertextBody,
sessionState.getLocalIdentityKey(),
sessionState.getRemoteIdentityKey());
if (sessionState.hasUnacknowledgedPreKeyMessage()) {
UnacknowledgedPreKeyMessageItems items = sessionState.getUnacknowledgedPreKeyMessageItems();
int localDeviceId = sessionState.getLocalDeviceId();
ciphertextMessage = new PreKeyWhisperMessage(sessionVersion, localDeviceId, items.getBaseKey(),
sessionState.getLocalIdentityKey(),
(WhisperMessage) ciphertextMessage);
}
sessionState.setSenderChainKey(chainKey.getNextChainKey());
sessionStore.storeSession(remoteAddress, sessionRecord);
return ciphertextMessage;
}
} | CiphertextMessage function(byte[] paddedMessage) { synchronized (SESSION_LOCK) { SessionRecord sessionRecord = sessionStore.loadSession(remoteAddress); SessionState sessionState = sessionRecord.getSessionState(); ChainKey chainKey = sessionState.getSenderChainKey(); MessageKeys messageKeys = chainKey.getMessageKeys(); ECPublicKey senderEphemeral = sessionState.getSenderRatchetKey(); int previousCounter = sessionState.getPreviousCounter(); int sessionVersion = sessionState.getSessionVersion(); byte[] ciphertextBody = getCiphertext(sessionVersion, messageKeys, paddedMessage); CiphertextMessage ciphertextMessage = new WhisperMessage(sessionVersion, messageKeys.getMacKey(), senderEphemeral, chainKey.getIndex(), previousCounter, ciphertextBody, sessionState.getLocalIdentityKey(), sessionState.getRemoteIdentityKey()); if (sessionState.hasUnacknowledgedPreKeyMessage()) { UnacknowledgedPreKeyMessageItems items = sessionState.getUnacknowledgedPreKeyMessageItems(); int localDeviceId = sessionState.getLocalDeviceId(); ciphertextMessage = new PreKeyWhisperMessage(sessionVersion, localDeviceId, items.getBaseKey(), sessionState.getLocalIdentityKey(), (WhisperMessage) ciphertextMessage); } sessionState.setSenderChainKey(chainKey.getNextChainKey()); sessionStore.storeSession(remoteAddress, sessionRecord); return ciphertextMessage; } } | /**
* Encrypt a message.
*
* @param paddedMessage The plaintext message bytes, optionally padded to a constant multiple.
* @return A ciphertext message encrypted to the recipient+device tuple.
*/ | Encrypt a message | encrypt | {
"repo_name": "thaidn/securegram",
"path": "libaxolotl/java/src/main/java/org/whispersystems/libaxolotl/SessionCipher.java",
"license": "gpl-2.0",
"size": 18877
} | [
"org.whispersystems.libaxolotl.ecc.ECPublicKey",
"org.whispersystems.libaxolotl.protocol.CiphertextMessage",
"org.whispersystems.libaxolotl.protocol.PreKeyWhisperMessage",
"org.whispersystems.libaxolotl.protocol.WhisperMessage",
"org.whispersystems.libaxolotl.ratchet.ChainKey",
"org.whispersystems.libaxolotl.ratchet.MessageKeys",
"org.whispersystems.libaxolotl.state.SessionRecord",
"org.whispersystems.libaxolotl.state.SessionState"
] | import org.whispersystems.libaxolotl.ecc.ECPublicKey; import org.whispersystems.libaxolotl.protocol.CiphertextMessage; import org.whispersystems.libaxolotl.protocol.PreKeyWhisperMessage; import org.whispersystems.libaxolotl.protocol.WhisperMessage; import org.whispersystems.libaxolotl.ratchet.ChainKey; import org.whispersystems.libaxolotl.ratchet.MessageKeys; import org.whispersystems.libaxolotl.state.SessionRecord; import org.whispersystems.libaxolotl.state.SessionState; | import org.whispersystems.libaxolotl.ecc.*; import org.whispersystems.libaxolotl.protocol.*; import org.whispersystems.libaxolotl.ratchet.*; import org.whispersystems.libaxolotl.state.*; | [
"org.whispersystems.libaxolotl"
] | org.whispersystems.libaxolotl; | 229,884 |
@SuppressWarnings("deprecation")
private void setRemoteAdapterV11(Context context, @NonNull final RemoteViews views) {
views.setRemoteAdapter(0, R.id.widget_list,
new Intent(context, DetailWidgetRemoteViewsService.class));
} | @SuppressWarnings(STR) void function(Context context, @NonNull final RemoteViews views) { views.setRemoteAdapter(0, R.id.widget_list, new Intent(context, DetailWidgetRemoteViewsService.class)); } | /**
* Sets the remote adapter used to fill in the list items
*
* @param views RemoteViews to set the RemoteAdapter
*/ | Sets the remote adapter used to fill in the list items | setRemoteAdapterV11 | {
"repo_name": "sjsingh200893/Sunshine",
"path": "app/src/main/java/com/example/android/sunshine/app/widget/DetailWidgetProvider.java",
"license": "apache-2.0",
"size": 3958
} | [
"android.content.Context",
"android.content.Intent",
"android.support.annotation.NonNull",
"android.widget.RemoteViews"
] | import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.widget.RemoteViews; | import android.content.*; import android.support.annotation.*; import android.widget.*; | [
"android.content",
"android.support",
"android.widget"
] | android.content; android.support; android.widget; | 2,302,233 |
public void addRow(GWTQueryResult gwtQueryResult) {
if (gwtQueryResult.getDocument()!=null || gwtQueryResult.getAttachment()!=null) {
addDocumentRow(gwtQueryResult, new Score(gwtQueryResult.getScore()));
} else if (gwtQueryResult.getFolder()!=null) {
addFolderRow(gwtQueryResult, new Score(gwtQueryResult.getScore()));
} else if (gwtQueryResult.getMail()!=null) {
addMailRow(gwtQueryResult, new Score(gwtQueryResult.getScore()));
}
}
| void function(GWTQueryResult gwtQueryResult) { if (gwtQueryResult.getDocument()!=null gwtQueryResult.getAttachment()!=null) { addDocumentRow(gwtQueryResult, new Score(gwtQueryResult.getScore())); } else if (gwtQueryResult.getFolder()!=null) { addFolderRow(gwtQueryResult, new Score(gwtQueryResult.getScore())); } else if (gwtQueryResult.getMail()!=null) { addMailRow(gwtQueryResult, new Score(gwtQueryResult.getScore())); } } | /**
* Adds a document to the panel
*
* @param doc The doc to add
*/ | Adds a document to the panel | addRow | {
"repo_name": "papamas/DMS-KANGREG-XI-MANADO",
"path": "src/main/java/com/openkm/frontend/client/widget/dashboard/keymap/KeyMapTable.java",
"license": "gpl-3.0",
"size": 28777
} | [
"com.openkm.frontend.client.bean.GWTQueryResult",
"com.openkm.frontend.client.widget.dashboard.Score"
] | import com.openkm.frontend.client.bean.GWTQueryResult; import com.openkm.frontend.client.widget.dashboard.Score; | import com.openkm.frontend.client.bean.*; import com.openkm.frontend.client.widget.dashboard.*; | [
"com.openkm.frontend"
] | com.openkm.frontend; | 2,817,868 |
public Map<String, String> getAllowlistedActionEnv() {
return filterClientEnv(visibleActionEnv);
} | Map<String, String> function() { return filterClientEnv(visibleActionEnv); } | /**
* Return an ordered version of the client environment restricted to those variables allowlisted
* by the command-line options to be inheritable by actions.
*/ | Return an ordered version of the client environment restricted to those variables allowlisted by the command-line options to be inheritable by actions | getAllowlistedActionEnv | {
"repo_name": "safarmer/bazel",
"path": "src/main/java/com/google/devtools/build/lib/runtime/CommandEnvironment.java",
"license": "apache-2.0",
"size": 29720
} | [
"java.util.Map"
] | import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 554,337 |
public static Property getTargetSemanticEnd(View view) {
EObjectValueStyle semanticStyle = (EObjectValueStyle) view.getNamedStyle(NotationPackage.eINSTANCE.getEObjectValueStyle(), SEMANTIC_TARGET_END);
return semanticStyle == null ? null : (Property) semanticStyle.getEObjectValue();
} | static Property function(View view) { EObjectValueStyle semanticStyle = (EObjectValueStyle) view.getNamedStyle(NotationPackage.eINSTANCE.getEObjectValueStyle(), SEMANTIC_TARGET_END); return semanticStyle == null ? null : (Property) semanticStyle.getEObjectValue(); } | /**
* Get the semantic end from the target of an edge representing an Association.
*
* @param view
* the Association view.
* @return the Property corresponding to the target of the graphical end.
*/ | Get the semantic end from the target of an edge representing an Association | getTargetSemanticEnd | {
"repo_name": "bmaggi/Papyrus-SysML11",
"path": "plugins/diagram/org.eclipse.papyrus.sysml.diagram.common/src-common-uml/org/eclipse/papyrus/uml/diagram/common/utils/AssociationViewUtils.java",
"license": "epl-1.0",
"size": 3189
} | [
"org.eclipse.gmf.runtime.notation.EObjectValueStyle",
"org.eclipse.gmf.runtime.notation.NotationPackage",
"org.eclipse.gmf.runtime.notation.View",
"org.eclipse.uml2.uml.Property"
] | import org.eclipse.gmf.runtime.notation.EObjectValueStyle; import org.eclipse.gmf.runtime.notation.NotationPackage; import org.eclipse.gmf.runtime.notation.View; import org.eclipse.uml2.uml.Property; | import org.eclipse.gmf.runtime.notation.*; import org.eclipse.uml2.uml.*; | [
"org.eclipse.gmf",
"org.eclipse.uml2"
] | org.eclipse.gmf; org.eclipse.uml2; | 1,923,309 |
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writeStroke(this.angleGridlineStroke, stream);
SerialUtilities.writePaint(this.angleGridlinePaint, stream);
SerialUtilities.writeStroke(this.radiusGridlineStroke, stream);
SerialUtilities.writePaint(this.radiusGridlinePaint, stream);
SerialUtilities.writePaint(this.angleLabelPaint, stream);
} | void function(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeStroke(this.angleGridlineStroke, stream); SerialUtilities.writePaint(this.angleGridlinePaint, stream); SerialUtilities.writeStroke(this.radiusGridlineStroke, stream); SerialUtilities.writePaint(this.radiusGridlinePaint, stream); SerialUtilities.writePaint(this.angleLabelPaint, stream); } | /**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/ | Provides serialization support | writeObject | {
"repo_name": "JSansalone/JFreeChart",
"path": "source/org/jfree/chart/plot/PolarPlot.java",
"license": "lgpl-2.1",
"size": 68880
} | [
"java.io.IOException",
"java.io.ObjectOutputStream",
"org.jfree.io.SerialUtilities"
] | import java.io.IOException; import java.io.ObjectOutputStream; import org.jfree.io.SerialUtilities; | import java.io.*; import org.jfree.io.*; | [
"java.io",
"org.jfree.io"
] | java.io; org.jfree.io; | 2,870,709 |
public static Range prefix(CharSequence row, CharSequence cf, CharSequence cqPrefix) {
return Range.prefix(new Text(row.toString()), new Text(cf.toString()), new Text(cqPrefix.toString()));
} | static Range function(CharSequence row, CharSequence cf, CharSequence cqPrefix) { return Range.prefix(new Text(row.toString()), new Text(cf.toString()), new Text(cqPrefix.toString())); } | /**
* Returns a Range that covers all column qualifiers beginning with a prefix within a given row and column family
*
* @see Range#prefix(Text, Text, Text)
*/ | Returns a Range that covers all column qualifiers beginning with a prefix within a given row and column family | prefix | {
"repo_name": "wjsl/jaredcumulo",
"path": "core/src/main/java/org/apache/accumulo/core/data/Range.java",
"license": "apache-2.0",
"size": 27200
} | [
"org.apache.hadoop.io.Text"
] | import org.apache.hadoop.io.Text; | import org.apache.hadoop.io.*; | [
"org.apache.hadoop"
] | org.apache.hadoop; | 762,462 |
protected String getAddress(Object object) {
return StringUtils.replaceOnce(toString(object), "*", "T-");
} | String function(Object object) { return StringUtils.replaceOnce(toString(object), "*", "T-"); } | /**
* Returns the address of a device, replacing group address identifier.
*/ | Returns the address of a device, replacing group address identifier | getAddress | {
"repo_name": "Jamstah/openhab2-addons",
"path": "addons/binding/org.openhab.binding.homematic/src/main/java/org/openhab/binding/homematic/internal/communicator/parser/CommonRpcParser.java",
"license": "epl-1.0",
"size": 7273
} | [
"org.apache.commons.lang.StringUtils"
] | import org.apache.commons.lang.StringUtils; | import org.apache.commons.lang.*; | [
"org.apache.commons"
] | org.apache.commons; | 203,087 |
@Test
public void testParseBoreholeSchema() throws Exception {
// load geosciml schema
SchemaIndex schemaIndex;
try {
schemaIndex = loadSchema(schemaBase + "commonSchemas/XMML/1/borehole.xsd");
} catch (Exception e) {
java.util.logging.Logger.getGlobal().log(java.util.logging.Level.INFO, "", e);
throw e;
}
AppSchemaFeatureTypeRegistry typeRegistry = new AppSchemaFeatureTypeRegistry();
try {
typeRegistry.addSchemas(schemaIndex);
Name typeName = Types.typeName(XMMLNS, "BoreholeType");
ComplexFeatureTypeImpl borehole =
(ComplexFeatureTypeImpl) typeRegistry.getAttributeType(typeName);
assertNotNull(borehole);
assertTrue(borehole instanceof FeatureType);
AttributeType superType = borehole.getSuper();
assertNotNull(superType);
Name superTypeName = Types.typeName(SANS, "ProfileType");
assertEquals(superTypeName, superType.getName());
assertTrue(superType instanceof FeatureType);
// ensure all needed types were parsed and aren't just empty proxies
Collection properties = borehole.getTypeDescriptors();
assertEquals(16, properties.size());
Map<Name, Name> expectedNamesAndTypes = new HashMap<>();
// from gml:AbstractFeatureType
expectedNamesAndTypes.put(
name(GMLNS, "metaDataProperty"), typeName(GMLNS, "MetaDataPropertyType"));
expectedNamesAndTypes.put(
name(GMLNS, "description"), typeName(GMLNS, "StringOrRefType"));
expectedNamesAndTypes.put(name(GMLNS, "name"), typeName(GMLNS, "CodeType"));
expectedNamesAndTypes.put(
name(GMLNS, "boundedBy"), typeName(GMLNS, "BoundingShapeType"));
expectedNamesAndTypes.put(
name(GMLNS, "location"), typeName(GMLNS, "LocationPropertyType"));
// from sa:ProfileType
expectedNamesAndTypes.put(name(SANS, "begin"), typeName(GMLNS, "PointPropertyType"));
expectedNamesAndTypes.put(name(SANS, "end"), typeName(GMLNS, "PointPropertyType"));
expectedNamesAndTypes.put(name(SANS, "length"), typeName(SWENS, "RelativeMeasureType"));
expectedNamesAndTypes.put(name(SANS, "shape"), typeName(GEONS, "Shape1DPropertyType"));
// sa:SamplingFeatureType
expectedNamesAndTypes.put(
name(SANS, "member"), typeName(SANS, "SamplingFeaturePropertyType"));
expectedNamesAndTypes.put(
name(SANS, "surveyDetails"), typeName(SANS, "SurveyProcedurePropertyType"));
expectedNamesAndTypes.put(
name(SANS, "associatedSpecimen"), typeName(SANS, "SpecimenPropertyType"));
expectedNamesAndTypes.put(
name(SANS, "relatedObservation"),
typeName(OMNS, "AbstractObservationPropertyType"));
// from xmml:BoreholeType
expectedNamesAndTypes.put(name(XMMLNS, "drillMethod"), typeName(XMMLNS, "drillCode"));
expectedNamesAndTypes.put(
name(XMMLNS, "collarDiameter"), typeName(GMLNS, "MeasureType"));
expectedNamesAndTypes.put(name(XMMLNS, "log"), typeName(XMMLNS, "LogPropertyType"));
for (Entry<Name, Name> nameNameEntry : expectedNamesAndTypes.entrySet()) {
Entry entry = (Entry) nameNameEntry;
Name dName = (Name) entry.getKey();
Name tName = (Name) entry.getValue();
AttributeDescriptor d = (AttributeDescriptor) Types.descriptor(borehole, dName);
assertNotNull("Descriptor not found: " + dName, d);
AttributeType type;
try {
type = d.getType();
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "type not parsed for " + d.getName(), e);
throw e;
}
assertNotNull(type);
assertNotNull(type.getName());
assertNotNull(type.getBinding());
if (tName != null) {
assertEquals(tName, type.getName());
}
}
Name tcl = Types.typeName(SWENS, "TypedCategoryListType");
AttributeType typedCategoryListType = typeRegistry.getAttributeType(tcl);
assertNotNull(typedCategoryListType);
assertTrue(typedCategoryListType instanceof ComplexType);
} finally {
typeRegistry.disposeSchemaIndexes();
}
} | void function() throws Exception { SchemaIndex schemaIndex; try { schemaIndex = loadSchema(schemaBase + STR); } catch (Exception e) { java.util.logging.Logger.getGlobal().log(java.util.logging.Level.INFO, STRBoreholeTypeSTRProfileTypeSTRmetaDataPropertySTRMetaDataPropertyTypeSTRdescriptionSTRStringOrRefTypeSTRnameSTRCodeTypeSTRboundedBySTRBoundingShapeTypeSTRlocationSTRLocationPropertyTypeSTRbeginSTRPointPropertyTypeSTRendSTRPointPropertyTypeSTRlengthSTRRelativeMeasureTypeSTRshapeSTRShape1DPropertyTypeSTRmemberSTRSamplingFeaturePropertyTypeSTRsurveyDetailsSTRSurveyProcedurePropertyTypeSTRassociatedSpecimenSTRSpecimenPropertyTypeSTRrelatedObservationSTRAbstractObservationPropertyTypeSTRdrillMethodSTRdrillCodeSTRcollarDiameterSTRMeasureTypeSTRlogSTRLogPropertyTypeSTRDescriptor not found: STRtype not parsed for STRTypedCategoryListType"); AttributeType typedCategoryListType = typeRegistry.getAttributeType(tcl); assertNotNull(typedCategoryListType); assertTrue(typedCategoryListType instanceof ComplexType); } finally { typeRegistry.disposeSchemaIndexes(); } } | /**
* Tests if the schema-to-FM parsing code developed for complex datastore configuration loading
* can parse the GeoSciML types
*/ | Tests if the schema-to-FM parsing code developed for complex datastore configuration loading can parse the GeoSciML types | testParseBoreholeSchema | {
"repo_name": "geotools/geotools",
"path": "modules/extension/app-schema/app-schema/src/test/java/org/geotools/data/complex/BoreholeTest.java",
"license": "lgpl-2.1",
"size": 15970
} | [
"java.util.logging.Level",
"java.util.logging.Logger",
"org.geotools.xsd.SchemaIndex",
"org.junit.Assert",
"org.opengis.feature.type.AttributeType",
"org.opengis.feature.type.ComplexType"
] | import java.util.logging.Level; import java.util.logging.Logger; import org.geotools.xsd.SchemaIndex; import org.junit.Assert; import org.opengis.feature.type.AttributeType; import org.opengis.feature.type.ComplexType; | import java.util.logging.*; import org.geotools.xsd.*; import org.junit.*; import org.opengis.feature.type.*; | [
"java.util",
"org.geotools.xsd",
"org.junit",
"org.opengis.feature"
] | java.util; org.geotools.xsd; org.junit; org.opengis.feature; | 1,454,190 |
@WebMethod
@WebResult(name = "rval", targetNamespace = "https://www.google.com/apis/ads/publisher/v202108")
@RequestWrapper(localName = "runReportJob", targetNamespace = "https://www.google.com/apis/ads/publisher/v202108", className = "com.google.api.ads.admanager.jaxws.v202108.ReportServiceInterfacerunReportJob")
@ResponseWrapper(localName = "runReportJobResponse", targetNamespace = "https://www.google.com/apis/ads/publisher/v202108", className = "com.google.api.ads.admanager.jaxws.v202108.ReportServiceInterfacerunReportJobResponse")
public ReportJob runReportJob(
@WebParam(name = "reportJob", targetNamespace = "https://www.google.com/apis/ads/publisher/v202108")
ReportJob reportJob)
throws ApiException_Exception
; | @WebResult(name = "rval", targetNamespace = STRrunReportJobSTRhttps: @ResponseWrapper(localName = "runReportJobResponseSTRhttps: ReportJob function( @WebParam(name = "reportJobSTRhttps: ReportJob reportJob) throws ApiException_Exception ; | /**
*
* Initiates the execution of a {@link ReportQuery} on the server.
*
* <p>The following fields are required:
* <ul>
* <li>{@link ReportJob#reportQuery}</li>
* </ul>
*
* @param reportJob the report job to run
* @return the report job with its ID filled in
*
*
* @param reportJob
* @return
* returns com.google.api.ads.admanager.jaxws.v202108.ReportJob
* @throws ApiException_Exception
*/ | Initiates the execution of a <code>ReportQuery</code> on the server. The following fields are required: <code>ReportJob#reportQuery</code> | runReportJob | {
"repo_name": "googleads/googleads-java-lib",
"path": "modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202108/ReportServiceInterface.java",
"license": "apache-2.0",
"size": 10520
} | [
"javax.jws.WebParam",
"javax.jws.WebResult",
"javax.xml.ws.ResponseWrapper"
] | import javax.jws.WebParam; import javax.jws.WebResult; import javax.xml.ws.ResponseWrapper; | import javax.jws.*; import javax.xml.ws.*; | [
"javax.jws",
"javax.xml"
] | javax.jws; javax.xml; | 1,790,271 |
@Provides
@Config("sshTimeout")
public static Duration provideSshTimeout() {
return Duration.standardSeconds(30);
} | @Config(STR) static Duration function() { return Duration.standardSeconds(30); } | /**
* Returns SSH client connection and read timeout.
*
* @see google.registry.rde.RdeUploadAction
*/ | Returns SSH client connection and read timeout | provideSshTimeout | {
"repo_name": "google/nomulus",
"path": "core/src/main/java/google/registry/config/RegistryConfig.java",
"license": "apache-2.0",
"size": 57133
} | [
"org.joda.time.Duration"
] | import org.joda.time.Duration; | import org.joda.time.*; | [
"org.joda.time"
] | org.joda.time; | 1,720,353 |
void startForegroundCompat(int id, Notification notification) {
// If we have the new startForeground API, then use it.
if (mStartForeground != null) {
mStartForegroundArgs[0] = Integer.valueOf(id);
mStartForegroundArgs[1] = notification;
try {
mStartForeground.invoke(this, mStartForegroundArgs);
} catch (InvocationTargetException e) {
// Should not happen.
Log.w(LOG_TAG, "Unable to invoke startForeground", e);
} catch (IllegalAccessException e) {
// Should not happen.
Log.w(LOG_TAG, "Unable to invoke startForeground", e);
}
return;
}
// Fall back on the old API.
setForeground(true);
mNM.notify(id, notification);
} | void startForegroundCompat(int id, Notification notification) { if (mStartForeground != null) { mStartForegroundArgs[0] = Integer.valueOf(id); mStartForegroundArgs[1] = notification; try { mStartForeground.invoke(this, mStartForegroundArgs); } catch (InvocationTargetException e) { Log.w(LOG_TAG, STR, e); } catch (IllegalAccessException e) { Log.w(LOG_TAG, STR, e); } return; } setForeground(true); mNM.notify(id, notification); } | /**
* This is a wrapper around the startForeground method, using the older
* APIs if it is not available.
*/ | This is a wrapper around the startForeground method, using the older APIs if it is not available | startForegroundCompat | {
"repo_name": "renndieG/androguard",
"path": "examples/android/gtalksms/src/com/googlecode/gtalksms/XmppService.java",
"license": "apache-2.0",
"size": 17718
} | [
"android.app.Notification",
"android.util.Log",
"java.lang.reflect.InvocationTargetException"
] | import android.app.Notification; import android.util.Log; import java.lang.reflect.InvocationTargetException; | import android.app.*; import android.util.*; import java.lang.reflect.*; | [
"android.app",
"android.util",
"java.lang"
] | android.app; android.util; java.lang; | 522,388 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.