_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q16300 | EmailSettingsApi.getInboundSettingsWithHttpInfo | train | public ApiResponse<GetInboundResponse> getInboundSettingsWithHttpInfo() throws ApiException {
com.squareup.okhttp.Call call = getInboundSettingsValidateBeforeCall(null, null);
Type localVarReturnType = new TypeToken<GetInboundResponse>(){}.getType();
return apiClient.execute(call, localVarReturnType);
} | java | {
"resource": ""
} |
q16301 | EmailSettingsApi.getOutboundSettingsWithHttpInfo | train | public ApiResponse<GetOutboundResponse> getOutboundSettingsWithHttpInfo() throws ApiException {
com.squareup.okhttp.Call call = getOutboundSettingsValidateBeforeCall(null, null);
Type localVarReturnType = new TypeToken<GetOutboundResponse>(){}.getType();
return apiClient.execute(call, localVarReturnType);
} | java | {
"resource": ""
} |
q16302 | CodecCodeGenerator.lookupId | train | private static Element lookupId(List<Element> fields) {
Element objectIdField = null;
Element uuidField = null;
Element _idField = null;
Element idField = null;
for (Element field : fields) {
if (field.getAnnotation(Id.class) != null) {
return field;
}
if (isObjectId(field)) {
objectIdField = field;
}
else if (isUUID(field)) {
uuidField = field;
}
else if (field.getSimpleName().contentEquals(ID_FIELD_NAME)) {
_idField = field;
}
else if (field.getSimpleName().contentEquals("id")) {
idField = field;
}
}
if (objectIdField != null) {
return objectIdField;
}
if (uuidField != null) {
return uuidField;
}
if (_idField != null) {
return _idField;
}
if (idField != null) {
return idField;
}
return null;
} | java | {
"resource": ""
} |
q16303 | Path.getUser | train | public User getUser(String fieldName, String fieldValue){
Select q = new Select().from(User.class);
String nameColumn = ModelReflector.instance(User.class).getColumnDescriptor(fieldName).getName();
q.where(new Expression(q.getPool(),nameColumn,Operator.EQ,new BindVariable(q.getPool(),fieldValue)));
List<? extends User> users = q.execute(User.class);
if (users.size() == 1){
return users.get(0);
}
return null;
} | java | {
"resource": ""
} |
q16304 | TraceInterceptor.intercept | train | @Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
request = request.newBuilder()
.addHeader(TRACEID_HEADER, makeUniqueId())
.addHeader(SPANID_HEADER, makeUniqueId()).build();
return chain.proceed(request);
} | java | {
"resource": ""
} |
q16305 | AuditApi.getAuditWithHttpInfo | train | public ApiResponse<GetAuditResponse> getAuditWithHttpInfo() throws ApiException {
com.squareup.okhttp.Call call = getAuditValidateBeforeCall(null, null);
Type localVarReturnType = new TypeToken<GetAuditResponse>(){}.getType();
return apiClient.execute(call, localVarReturnType);
} | java | {
"resource": ""
} |
q16306 | OptionsApi.getOptions | train | public Options getOptions(String personDBID, String agentGroupDBID) throws ProvisioningApiException {
try {
OptionsGetResponseSuccess resp = optionsApi.optionsGet(
personDBID,
agentGroupDBID
);
if (!resp.getStatus().getCode().equals(0)) {
throw new ProvisioningApiException("Error getting options. Code: " + resp.getStatus().getCode());
}
Options out = new Options();
out.setOptions((Map<String, Object>) resp.getData().getOptions());
out.setCmeAppName(resp.getData().getCmeAppName());
out.setCmeAppDBID(resp.getData().getCmeAppDBID());
return out;
} catch (ApiException e) {
throw new ProvisioningApiException("Error getting options", e);
}
} | java | {
"resource": ""
} |
q16307 | OptionsApi.modifyOptions | train | public void modifyOptions(Map<String, Object> options) throws ProvisioningApiException {
try {
OptionsPostResponseStatusSuccess resp = optionsApi.optionsPost(new OptionsPost().data(new OptionsPostData().options(options)));
if (!resp.getStatus().getCode().equals(0)) {
throw new ProvisioningApiException("Error modifying options. Code: " + resp.getStatus().getCode());
}
} catch (ApiException e) {
throw new ProvisioningApiException("Error modifying options", e);
}
} | java | {
"resource": ""
} |
q16308 | OptionsApi.updateOptions | train | public void updateOptions(Map<String, Object> newOptions, Map<String, Object> changedOptions, Map<String, Object> deletedOptions) throws ProvisioningApiException {
try {
OptionsPutResponseStatusSuccess resp = optionsApi.optionsPut(
new OptionsPut()
.data(
new OptionsPutData()
.newOptions(newOptions)
.changedOptions(changedOptions)
.deletedOptions(deletedOptions)
)
);
if (!resp.getStatus().getCode().equals(0)) {
throw new ProvisioningApiException("Error updating options. Code: " + resp.getStatus().getCode());
}
} catch (ApiException e) {
throw new ProvisioningApiException("Error updating options", e);
}
} | java | {
"resource": ""
} |
q16309 | AmbEval.doDefine | train | private final EvalResult doDefine(List<SExpression> subexpressions, Environment environment,
ParametricBfgBuilder builder, EvalContext context) {
int nameToBind = subexpressions.get(1).getConstantIndex();
if (subexpressions.size() == 3) {
// (define name value-expression)
// Binds a name to the value of value-expression
Object valueToBind = eval(subexpressions.get(2), environment, builder, context).getValue();
environment.bindName(nameToBind, valueToBind);
} else if (subexpressions.size() >= 4) {
// (define procedure-name (arg1 ...) procedure-body)
// syntactic sugar equivalent to (define procedure-name (lambda (arg1 ...) procedure-body
AmbLambdaValue lambdaValue = makeLambda(subexpressions.get(2),
subexpressions.subList(3, subexpressions.size()), environment);
environment.bindName(nameToBind, lambdaValue);
}
return new EvalResult(ConstantValue.UNDEFINED);
} | java | {
"resource": ""
} |
q16310 | Generate.password | train | public static String password(int length) {
StringBuilder result = new StringBuilder();
byte[] values = byteArray(length);
// We use a modulus of an increasing index rather than of the byte values
// to avoid certain characters coming up more often.
int index = 0;
for (int i = 0; i < length; i++) {
index += (values[i] & 0xff);
index = index % passwordCharacters.length();
result.append(passwordCharacters.charAt(index));
}
return result.toString();
} | java | {
"resource": ""
} |
q16311 | CcgParse.getSyntacticParse | train | public CcgSyntaxTree getSyntacticParse() {
HeadedSyntacticCategory originalSyntax = null;
if (unaryRule != null) {
originalSyntax = unaryRule.getUnaryRule().getInputSyntacticCategory().getCanonicalForm();
} else {
originalSyntax = syntax;
}
if (isTerminal()) {
return CcgSyntaxTree.createTerminal(syntax.getSyntax(), originalSyntax.getSyntax(),
spanStart, spanEnd, words, posTags, originalSyntax);
} else {
CcgSyntaxTree leftTree = left.getSyntacticParse();
CcgSyntaxTree rightTree = right.getSyntacticParse();
return CcgSyntaxTree.createNonterminal(syntax.getSyntax(), originalSyntax.getSyntax(),
leftTree, rightTree);
}
} | java | {
"resource": ""
} |
q16312 | CcgParse.getLogicalForm | train | public Expression2 getLogicalForm() {
Expression2 preUnaryLogicalForm = getPreUnaryLogicalForm();
if (unaryRule == null) {
return preUnaryLogicalForm;
} else if (preUnaryLogicalForm == null || unaryRule.getUnaryRule().getLogicalForm() == null) {
return null;
} else {
return Expression2.nested(unaryRule.getUnaryRule().getLogicalForm(), preUnaryLogicalForm);
}
} | java | {
"resource": ""
} |
q16313 | CcgParse.getLogicalFormForSpan | train | public SpannedExpression getLogicalFormForSpan(int spanStart, int spanEnd) {
CcgParse spanningParse = getParseForSpan(spanStart, spanEnd);
Expression2 lf = spanningParse.getPreUnaryLogicalForm();
if (lf != null) {
return new SpannedExpression(spanningParse.getHeadedSyntacticCategory(),
spanningParse.getLogicalForm(), spanningParse.getSpanStart(), spanningParse.getSpanEnd());
} else {
return null;
}
} | java | {
"resource": ""
} |
q16314 | CcgParse.getSpannedLogicalForms | train | public List<SpannedExpression> getSpannedLogicalForms() {
List<SpannedExpression> spannedExpressions = Lists.newArrayList();
getSpannedLogicalFormsHelper(spannedExpressions);
return spannedExpressions;
} | java | {
"resource": ""
} |
q16315 | CcgParse.getSpannedWords | train | public List<String> getSpannedWords() {
if (isTerminal()) {
return words;
} else {
List<String> words = Lists.newArrayList();
words.addAll(left.getSpannedWords());
words.addAll(right.getSpannedWords());
return words;
}
} | java | {
"resource": ""
} |
q16316 | CcgParse.getSpannedPosTags | train | public List<String> getSpannedPosTags() {
if (isTerminal()) {
return posTags;
} else {
List<String> tags = Lists.newArrayList();
tags.addAll(left.getSpannedPosTags());
tags.addAll(right.getSpannedPosTags());
return tags;
}
} | java | {
"resource": ""
} |
q16317 | CcgParse.getSpannedLexiconEntries | train | public List<LexiconEntryInfo> getSpannedLexiconEntries() {
if (isTerminal()) {
return Arrays.asList(lexiconEntry);
} else {
List<LexiconEntryInfo> lexiconEntries = Lists.newArrayList();
lexiconEntries.addAll(left.getSpannedLexiconEntries());
lexiconEntries.addAll(right.getSpannedLexiconEntries());
return lexiconEntries;
}
} | java | {
"resource": ""
} |
q16318 | CcgParse.getAllDependencies | train | public List<DependencyStructure> getAllDependencies() {
List<DependencyStructure> deps = Lists.newArrayList();
if (!isTerminal()) {
deps.addAll(left.getAllDependencies());
deps.addAll(right.getAllDependencies());
}
deps.addAll(dependencies);
return deps;
} | java | {
"resource": ""
} |
q16319 | CcgParse.getAllDependenciesIndexedByHeadWordIndex | train | public Multimap<Integer, DependencyStructure> getAllDependenciesIndexedByHeadWordIndex() {
Multimap<Integer, DependencyStructure> map = HashMultimap.create();
for (DependencyStructure dep : getAllDependencies()) {
map.put(dep.getHeadWordIndex(), dep);
}
return map;
} | java | {
"resource": ""
} |
q16320 | SqlFileFixture.load | train | @Override
public void load(UnitDaoFactory unitDaoFactory) {
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
BufferedReaderIterator iterator = new BufferedReaderIterator(reader);
StringBuilder currentQuery = new StringBuilder();
while (iterator.hasNext()) {
String line = iterator.next().trim();
if (!isCommentOrEmptyLine(line)) {
currentQuery.append(line).append(" ");
}
if (isEndOfQuery(line)) {
unitDaoFactory.getUnitDao().execute(currentQuery.toString());
currentQuery = new StringBuilder();
}
}
} | java | {
"resource": ""
} |
q16321 | VotingLexiconInduction.createParser | train | private static ParserInfo createParser(LexiconInductionCcgParserFactory factory,
SufficientStatistics currentParameters, Collection<LexiconEntry> currentLexicon) {
ParametricCcgParser family = factory.getParametricCcgParser(currentLexicon);
SufficientStatistics newParameters = family.getNewSufficientStatistics();
if (currentParameters != null) {
newParameters.transferParameters(currentParameters);
}
return new ParserInfo(currentLexicon, family, newParameters, family.getModelFromParameters(newParameters));
} | java | {
"resource": ""
} |
q16322 | VotingLexiconInduction.getPartitionFunction | train | private double getPartitionFunction(List<CcgParse> parses) {
double partitionFunction = 0.0;
for (CcgParse parse : parses) {
partitionFunction += parse.getSubtreeProbability();
}
return partitionFunction;
} | java | {
"resource": ""
} |
q16323 | SequenceModelUtils.buildSequenceModel | train | public static ParametricFactorGraph buildSequenceModel(Iterable<String> emissionFeatureLines,
String featureDelimiter) {
// Read in the possible values of each variable.
List<String> words = StringUtils.readColumnFromDelimitedLines(emissionFeatureLines, 0, featureDelimiter);
List<String> labels = StringUtils.readColumnFromDelimitedLines(emissionFeatureLines, 1, featureDelimiter);
List<String> emissionFeatures = StringUtils.readColumnFromDelimitedLines(emissionFeatureLines, 2, featureDelimiter);
// Create dictionaries for each variable's values.
DiscreteVariable wordType = new DiscreteVariable("word", words);
DiscreteVariable labelType = new DiscreteVariable("label", labels);
DiscreteVariable emissionFeatureType = new DiscreteVariable("emissionFeature", emissionFeatures);
// Create a dynamic factor graph with a single plate replicating
// the input/output variables.
ParametricFactorGraphBuilder builder = new ParametricFactorGraphBuilder();
builder.addPlate(PLATE_NAME, new VariableNumMap(Ints.asList(1, 2),
Arrays.asList(INPUT_NAME, OUTPUT_NAME), Arrays.asList(wordType, labelType)), 10000);
String inputPattern = PLATE_NAME + "/?(0)/" + INPUT_NAME;
String outputPattern = PLATE_NAME + "/?(0)/" + OUTPUT_NAME;
String nextOutputPattern = PLATE_NAME + "/?(1)/" + OUTPUT_NAME;
VariableNumMap plateVars = new VariableNumMap(Ints.asList(1, 2),
Arrays.asList(inputPattern, outputPattern), Arrays.asList(wordType, labelType));
// Read in the emission features (for the word/label weights).
VariableNumMap x = plateVars.getVariablesByName(inputPattern);
VariableNumMap y = plateVars.getVariablesByName(outputPattern);
VariableNumMap emissionFeatureVar = VariableNumMap.singleton(0, "emissionFeature", emissionFeatureType);
TableFactor emissionFeatureFactor = TableFactor.fromDelimitedFile(
Arrays.asList(x, y, emissionFeatureVar), emissionFeatureLines,
featureDelimiter, false, SparseTensorBuilder.getFactory())
.cacheWeightPermutations();
System.out.println(emissionFeatureFactor.getVars());
// Add a parametric factor for the word/label weights
DiscreteLogLinearFactor emissionFactor = new DiscreteLogLinearFactor(x.union(y), emissionFeatureVar,
emissionFeatureFactor);
builder.addFactor(WORD_LABEL_FACTOR, emissionFactor,
VariableNamePattern.fromTemplateVariables(plateVars, VariableNumMap.EMPTY));
// Create a factor connecting adjacent labels
VariableNumMap adjacentVars = new VariableNumMap(Ints.asList(0, 1),
Arrays.asList(outputPattern, nextOutputPattern), Arrays.asList(labelType, labelType));
builder.addFactor(TRANSITION_FACTOR, DiscreteLogLinearFactor.createIndicatorFactor(adjacentVars),
VariableNamePattern.fromTemplateVariables(adjacentVars, VariableNumMap.EMPTY));
return builder.build();
} | java | {
"resource": ""
} |
q16324 | AbstractFactorGraphBuilder.addConstantFactor | train | public void addConstantFactor(String factorName, PlateFactor factor) {
constantFactors.add(factor);
constantFactorNames.add(factorName);
} | java | {
"resource": ""
} |
q16325 | AbstractFactorGraphBuilder.addFactor | train | public void addFactor(String factorName, T factor, VariablePattern factorPattern) {
parametricFactors.add(factor);
factorPatterns.add(factorPattern);
parametricFactorNames.add(factorName);
} | java | {
"resource": ""
} |
q16326 | SqlFixture.load | train | @Override
public void load(UnitDaoFactory unitDaoFactory) {
for (String query : queries) {
unitDaoFactory.getUnitDao().execute(query);
}
} | java | {
"resource": ""
} |
q16327 | CcgExactChart.longMultisetsEqual | train | private static final boolean longMultisetsEqual(long[] firstDeps, long[] secondDeps) {
if (firstDeps.length != secondDeps.length) {
return false;
}
Arrays.sort(firstDeps);
Arrays.sort(secondDeps);
for (int i = 0; i < firstDeps.length; i++) {
if (firstDeps[i] != secondDeps[i]) {
return false;
}
}
return true;
} | java | {
"resource": ""
} |
q16328 | IndexedList.add | train | public int add(T item) {
if (itemIndex.containsKey(item)) {
// Items can only be added once
return itemIndex.get(item);
}
int index = items.size();
itemIndex.put(item, index);
items.add(item);
return index;
} | java | {
"resource": ""
} |
q16329 | IndexedList.getIndex | train | public int getIndex(Object item) {
if (!itemIndex.containsKey(item)) {
throw new NoSuchElementException("No such item: " + item);
}
return itemIndex.get(item);
} | java | {
"resource": ""
} |
q16330 | IndexedList.get | train | public T get(int index) {
if (index >= items.size() || index < 0) {
throw new IndexOutOfBoundsException("size: " + items.size() + " index: " + index);
}
return items.get(index);
} | java | {
"resource": ""
} |
q16331 | Expression2.getParentExpressionIndex | train | public int getParentExpressionIndex(int index) {
if (index == 0) {
return -1;
} else {
int[] parts = findSubexpression(index);
int parentIndex = subexpressions.get(parts[0]).getParentExpressionIndex(parts[1]);
if (parentIndex == -1) {
// index refers to a child of this expression.
return 0;
} else {
// Return the index into this expression of the chosen child,
// plus the index into that expression.
return parentIndex + parts[2];
}
}
} | java | {
"resource": ""
} |
q16332 | ContinuationIncEval.nextState | train | public void nextState(IncEvalState prev, IncEvalState next, Object continuation,
Environment env, Object denotation, Object diagram, Object otherArgs, LogFunction log) {
next.set(continuation, env, denotation, diagram, prev.getProb(), null);
} | java | {
"resource": ""
} |
q16333 | DataTypeGeneric.convert | train | public static Object convert(String dataType, Object record){
if(record == null){return null;}
if(dataType.equals(UUID)){
return java.util.UUID.fromString(record.toString());
}
//TODO: add a lot of else if here for the other data types
else{
return record;
}
} | java | {
"resource": ""
} |
q16334 | ModelCurator.correct | train | public ModelDef[] correct(){
for(ModelDef m : modelList){
this.model = m;
correct1to1Detail();
}
for(ModelDef m : modelList){
this.model = m;
removeUnnecessaryHasOneToSelf();
}
for(ModelDef m : modelList){
this.model = m;
removeUnnecessaryHasManyToSelf();
}
for(ModelDef m : modelList){
this.model = m;
crossOutLinkerTables();
}
for(ModelDef m : modelList){
this.model = m;
removeHasOneToBothPrimaryAndForeignKey();
}
return modelList;
} | java | {
"resource": ""
} |
q16335 | ModelCurator.removeHasOneToBothPrimaryAndForeignKey | train | private void removeHasOneToBothPrimaryAndForeignKey() {
String[] primaryKeys = model.getPrimaryAttributes();
String[] hasOne = model.getHasOne();
String[] hasOneLocal = model.getHasOneLocalColumn();
String[] hasOneReferenced = model.getHasOneReferencedColumn();
for(String pk : primaryKeys){
int pkIndex = CStringUtils.indexOf(hasOneLocal, pk);
if(pkIndex >= 0){
System.out.println("\n"+pk+" is a primary key of ["+model.getTableName()+"] ("+hasOneLocal[pkIndex]+")"
+ "and foreign key to ["+hasOne[pkIndex]+"]("+hasOneReferenced[pkIndex]+")");
System.out.println("removing ["+hasOne[pkIndex]+"] from ["+model.getTableName()+"]");
model = removeFromHasOne(model, hasOne[pkIndex]);
}
}
} | java | {
"resource": ""
} |
q16336 | ModelCurator.correct1to1Detail | train | private void correct1to1Detail(){
String[] hasManyTables = model.getHasMany();
for(String hasMany : hasManyTables){
if(shouldBeMoved(model, hasMany)){
model = moveFromHasManyToHasOne(model, hasMany);
}
}
} | java | {
"resource": ""
} |
q16337 | ModelCurator.crossOutLinkerTables | train | private void crossOutLinkerTables(){
String[] primaryKeys = model.getPrimaryAttributes();
if(primaryKeys != null && primaryKeys.length == 2){//there are only 2 primary keys
//if both primary keys look up to different table which is also a primary key
String[] hasOne = model.getHasOne();
String[] hasOneLocalColum = model.getHasOneLocalColumn();
String[] hasOneReferencedColumn = model.getHasOneReferencedColumn();
int indexP1 = CStringUtils.indexOf(hasOneLocalColum, primaryKeys[0]);
int indexP2 = CStringUtils.indexOf(hasOneLocalColum, primaryKeys[1]);
if(indexP1 >= 0 && indexP2 >= 0){
String t1 = hasOne[indexP1];
String t2 = hasOne[indexP2];
String ref1 = hasOneReferencedColumn[indexP1];
String ref2 = hasOneReferencedColumn[indexP2];
ModelDef m1 = getModel(t1);
boolean isRef1Primary = CStringUtils.inArray(m1.getPrimaryAttributes(), ref1);
ModelDef m2 = getModel(t2);
boolean isRef2Primary = CStringUtils.inArray(m2.getPrimaryAttributes(), ref2);
if(model != m1 && model != m2
&& isRef1Primary
&& isRef2Primary
){
removeFromHasMany(m1, model.getTableName());//remove the hasMany of this table
removeFromHasMany(m2, model.getTableName());//remove the hasMany of this table
addToHasMany(m1, m2.getTableName(), ref2, null);
addToHasMany(m2, m1.getTableName(), ref1, null);
}
}
}
} | java | {
"resource": ""
} |
q16338 | DictionaryFeatureVectorGenerator.getActiveFeatures | train | public Map<U, Double> getActiveFeatures(Tensor featureVector) {
Preconditions.checkArgument(featureVector.getDimensionSizes().length == 1
&& featureVector.getDimensionSizes()[0] == getNumberOfFeatures());
Map<U, Double> features = Maps.newHashMap();
Iterator<KeyValue> keyValueIter = featureVector.keyValueIterator();
while (keyValueIter.hasNext()) {
KeyValue featureKeyValue = keyValueIter.next();
features.put(featureIndexes.get(featureKeyValue.getKey()[0]), featureKeyValue.getValue());
}
return features;
} | java | {
"resource": ""
} |
q16339 | LocalTrustGraph.sendAdvertisement | train | public void sendAdvertisement(final BasicTrustGraphAdvertisement message,
final TrustGraphNodeId sender,
final TrustGraphNodeId toNeighbor,
final int ttl) {
final BasicTrustGraphAdvertisement outboundMessage = message.copyWith(sender, ttl);
final TrustGraphNode toNode = nodes.get(toNeighbor);
toNode.handleAdvertisement(outboundMessage);
} | java | {
"resource": ""
} |
q16340 | LocalTrustGraph.addNode | train | public LocalTrustGraphNode addNode(final TrustGraphNodeId nodeId) {
final LocalTrustGraphNode node = createNode(nodeId);
addNode(node);
return node;
} | java | {
"resource": ""
} |
q16341 | LocalTrustGraph.addDirectedRoute | train | public void addDirectedRoute(final LocalTrustGraphNode from, final LocalTrustGraphNode to) {
from.getRoutingTable().addNeighbor(to.getId());
} | java | {
"resource": ""
} |
q16342 | LocalTrustGraph.addDirectedRoute | train | public void addDirectedRoute(final TrustGraphNodeId from, final TrustGraphNodeId to) {
final TrustGraphNode fromNode = nodes.get(from);
fromNode.getRoutingTable().addNeighbor(to);
} | java | {
"resource": ""
} |
q16343 | LocalTrustGraph.addRoute | train | public void addRoute(final TrustGraphNodeId a, final TrustGraphNodeId b) {
addDirectedRoute(a,b);
addDirectedRoute(b,a);
} | java | {
"resource": ""
} |
q16344 | LocalTrustGraph.addRoute | train | public void addRoute(final LocalTrustGraphNode a, final LocalTrustGraphNode b) {
addDirectedRoute(a,b);
addDirectedRoute(b,a);
} | java | {
"resource": ""
} |
q16345 | Status.valueOf | train | public static Status valueOf(int code) {
Status result = null;
switch (code) {
case 100:
result = INFO_CONTINUE;
break;
case 101:
result = INFO_SWITCHING_PROTOCOL;
break;
case 102:
result = INFO_PROCESSING;
break;
case 200:
result = SUCCESS_OK;
break;
case 201:
result = SUCCESS_CREATED;
break;
case 202:
result = SUCCESS_ACCEPTED;
break;
case 203:
result = SUCCESS_NON_AUTHORITATIVE;
break;
case 204:
result = SUCCESS_NO_CONTENT;
break;
case 205:
result = SUCCESS_RESET_CONTENT;
break;
case 206:
result = SUCCESS_PARTIAL_CONTENT;
break;
case 207:
result = SUCCESS_MULTI_STATUS;
break;
case 300:
result = REDIRECTION_MULTIPLE_CHOICES;
break;
case 301:
result = REDIRECTION_PERMANENT;
break;
case 302:
result = REDIRECTION_FOUND;
break;
case 303:
result = REDIRECTION_SEE_OTHER;
break;
case 304:
result = REDIRECTION_NOT_MODIFIED;
break;
case 305:
result = REDIRECTION_USE_PROXY;
break;
case 307:
result = REDIRECTION_TEMPORARY;
break;
case 400:
result = CLIENT_ERROR_BAD_REQUEST;
break;
case 401:
result = CLIENT_ERROR_UNAUTHORIZED;
break;
case 402:
result = CLIENT_ERROR_PAYMENT_REQUIRED;
break;
case 403:
result = CLIENT_ERROR_FORBIDDEN;
break;
case 404:
result = CLIENT_ERROR_NOT_FOUND;
break;
case 405:
result = CLIENT_ERROR_METHOD_NOT_ALLOWED;
break;
case 406:
result = CLIENT_ERROR_NOT_ACCEPTABLE;
break;
case 407:
result = CLIENT_ERROR_PROXY_AUTHENTIFICATION_REQUIRED;
break;
case 408:
result = CLIENT_ERROR_REQUEST_TIMEOUT;
break;
case 409:
result = CLIENT_ERROR_CONFLICT;
break;
case 410:
result = CLIENT_ERROR_GONE;
break;
case 411:
result = CLIENT_ERROR_LENGTH_REQUIRED;
break;
case 412:
result = CLIENT_ERROR_PRECONDITION_FAILED;
break;
case 413:
result = CLIENT_ERROR_REQUEST_ENTITY_TOO_LARGE;
break;
case 414:
result = CLIENT_ERROR_REQUEST_URI_TOO_LONG;
break;
case 415:
result = CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE;
break;
case 416:
result = CLIENT_ERROR_REQUESTED_RANGE_NOT_SATISFIABLE;
break;
case 417:
result = CLIENT_ERROR_EXPECTATION_FAILED;
break;
case 422:
result = CLIENT_ERROR_UNPROCESSABLE_ENTITY;
break;
case 423:
result = CLIENT_ERROR_LOCKED;
break;
case 424:
result = CLIENT_ERROR_FAILED_DEPENDENCY;
break;
case 500:
result = SERVER_ERROR_INTERNAL;
break;
case 501:
result = SERVER_ERROR_NOT_IMPLEMENTED;
break;
case 502:
result = SERVER_ERROR_BAD_GATEWAY;
break;
case 503:
result = SERVER_ERROR_SERVICE_UNAVAILABLE;
break;
case 504:
result = SERVER_ERROR_GATEWAY_TIMEOUT;
break;
case 505:
result = SERVER_ERROR_VERSION_NOT_SUPPORTED;
break;
case 507:
result = SERVER_ERROR_INSUFFICIENT_STORAGE;
break;
case 1000:
result = CONNECTOR_ERROR_CONNECTION;
break;
case 1001:
result = CONNECTOR_ERROR_COMMUNICATION;
break;
case 1002:
result = CONNECTOR_ERROR_INTERNAL;
break;
}
return result;
} | java | {
"resource": ""
} |
q16346 | BasicPopulateFactory.populateEntity | train | private <T> T populateEntity(final T t,
final Map<Field, Long> enumeratesMap,
final Set<Field> nullableFields,
final int currentEmbeddedDepth) {
final Map<Field, GenContainer> genContainers = this.populateScanner.scan(t.getClass());
for (final Map.Entry<Field, GenContainer> annotatedField : genContainers.entrySet()) {
final Field field = annotatedField.getKey();
// If field had errors or null gen in prev populate iteration, just skip that field
if (nullableFields.contains(field))
continue;
try {
field.setAccessible(true);
final Object objValue = generateObject(field,
annotatedField.getValue(),
enumeratesMap,
nullableFields,
currentEmbeddedDepth);
field.set(t, objValue);
} catch (ClassCastException e) {
logger.warning(e.getMessage() + " | field TYPE and GENERATE TYPE are not compatible");
nullableFields.add(field); // skip field due to error as if it null
throw e;
} catch (IllegalAccessException e) {
logger.warning(e.getMessage() + " | have NO ACCESS to field: " + field.getName());
nullableFields.add(field); // skip field due to error as if it null
} catch (Exception e) {
logger.warning(e.getMessage());
nullableFields.add(field); // skip field due to error as if it null
} finally {
annotatedField.getKey().setAccessible(false);
}
}
return t;
} | java | {
"resource": ""
} |
q16347 | BasicPopulateFactory.generateObject | train | private Object generateObject(final Field field,
final GenContainer container,
final Map<Field, Long> enumerateMap,
final Set<Field> nullableFields,
final int currentEmbeddedDepth) {
final IGenerator generator = genStorage.getGenInstance(container.getGeneratorClass());
final Annotation annotation = container.getMarker();
Object generated;
if (EmbeddedGenerator.class.equals(container.getGeneratorClass())) {
generated = generateEmbeddedObject(annotation, field, nullableFields, currentEmbeddedDepth);
} else if (enumerateMap.containsKey(field)) {
generated = generateEnumerateObject(field, enumerateMap);
} else if (container.isComplex()) {
// If complexGen can generate embedded objects
// And not handling it like BasicComplexGenerator, you are StackOverFlowed
generated = ((IComplexGenerator) generator).generate(annotation, field, genStorage, currentEmbeddedDepth);
} else {
generated = generator.generate();
}
final Object casted = castObject(generated, field.getType());
if (casted == null)
nullableFields.add(field);
return casted;
} | java | {
"resource": ""
} |
q16348 | BasicPopulateFactory.generateEmbeddedObject | train | private Object generateEmbeddedObject(final Annotation annotation,
final Field field,
final Set<Field> nullableFields,
final int currentEmbeddedDepth) {
final int fieldDepth = getDepth(annotation);
if (fieldDepth < currentEmbeddedDepth)
return null;
final Object embedded = instantiate(field.getType());
if (embedded == null) {
nullableFields.add(field);
return null;
}
return populateEntity(embedded,
buildEnumerateMap(field.getType()),
buildNullableSet(),
currentEmbeddedDepth + 1);
} | java | {
"resource": ""
} |
q16349 | BasicPopulateFactory.generateEnumerateObject | train | private Object generateEnumerateObject(final Field field,
final Map<Field, Long> enumerateMap) {
final Long currentEnumerateValue = enumerateMap.get(field);
Object objValue = BasicCastUtils.castToNumber(currentEnumerateValue, field.getType());
// Increment numerate number for generated field
enumerateMap.computeIfPresent(field, (k, v) -> v + 1);
return objValue;
} | java | {
"resource": ""
} |
q16350 | BasicPopulateFactory.buildEnumerateMap | train | private Map<Field, Long> buildEnumerateMap(final Class t) {
return this.enumerateScanner.scan(t).entrySet().stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> ((GenEnumerate) e.getValue().get(0)).from())
);
} | java | {
"resource": ""
} |
q16351 | CfgAlignmentModel.getRootFactor | train | public Factor getRootFactor(ExpressionTree tree, VariableNumMap expressionVar) {
List<Assignment> roots = Lists.newArrayList();
if (tree.getSubstitutions().size() == 0) {
roots.add(expressionVar.outcomeArrayToAssignment(tree.getExpressionNode()));
} else {
for (ExpressionTree substitution : tree.getSubstitutions()) {
roots.add(expressionVar.outcomeArrayToAssignment(substitution.getExpressionNode()));
}
}
return TableFactor.pointDistribution(expressionVar, roots.toArray(new Assignment[0]));
} | java | {
"resource": ""
} |
q16352 | Cron4jNow.clearDisappearedJob | train | public synchronized void clearDisappearedJob() {
getCron4jJobList().stream().filter(job -> job.isDisappeared()).forEach(job -> {
final LaJobKey jobKey = job.getJobKey();
jobKeyJobMap.remove(jobKey);
jobOrderedList.remove(job);
job.getJobUnique().ifPresent(jobUnique -> jobUniqueJobMap.remove(jobUnique));
cron4jTaskJobMap.remove(job.getCron4jTask());
});
} | java | {
"resource": ""
} |
q16353 | DynamicFactorGraphBuilder.addUnreplicatedFactor | train | public void addUnreplicatedFactor(String factorName, Factor factor, VariableNumMap vars) {
plateFactors.add(new ReplicatedFactor(factor, new WrapperVariablePattern(vars)));
plateFactorNames.add(factorName);
} | java | {
"resource": ""
} |
q16354 | PopulateScanner.isComplex | train | private boolean isComplex(final Field field) {
final Class<?> declaringClass = field.getType();
return (declaringClass.equals(List.class)
|| declaringClass.equals(Set.class)
|| declaringClass.equals(Map.class))
|| declaringClass.getTypeName().endsWith("[][]")
|| declaringClass.getTypeName().endsWith("[]");
} | java | {
"resource": ""
} |
q16355 | PopulateScanner.findGenAnnotation | train | private GenContainer findGenAnnotation(final Field field) {
for (Annotation annotation : field.getDeclaredAnnotations()) {
for (Annotation inline : annotation.annotationType().getDeclaredAnnotations()) {
if (isGen.test(inline)) {
return GenContainer.asGen(inline, annotation);
}
}
}
return null;
} | java | {
"resource": ""
} |
q16356 | DavidsonianCcgParseAugmenter.markEntityVars | train | private static void markEntityVars(HeadedSyntacticCategory cat, int[] uniqueVars,
boolean[] isEntityVar) {
if (cat.isAtomic()) {
for (int var : cat.getUniqueVariables()) {
int index = Ints.indexOf(uniqueVars, var);
isEntityVar[index] = true;
}
} else {
markEntityVars(cat.getArgumentType(), uniqueVars, isEntityVar);
markEntityVars(cat.getReturnType(), uniqueVars, isEntityVar);
}
} | java | {
"resource": ""
} |
q16357 | CleanableFixtureProxy.getClassesToDeleteIterator | train | @Override
public Iterator<Class> getClassesToDeleteIterator() {
if (fixture instanceof CleanableFixture) {
return cleanableFixture().getClassesToDeleteIterator();
}
return Collections.<Class>emptyList().iterator();
} | java | {
"resource": ""
} |
q16358 | CsvExporter.buildCsvValue | train | private String buildCsvValue(final Field field,
final String fieldValue) {
return (areTextValuesWrapped && field.getType().equals(String.class)
|| isValueWrappable.test(fieldValue))
? wrapWithQuotes(fieldValue)
: fieldValue;
} | java | {
"resource": ""
} |
q16359 | CsvExporter.generateCsvHeader | train | private String generateCsvHeader(final IClassContainer container) {
final String separatorAsStr = String.valueOf(separator);
return container.getFormatSupported(Format.CSV).entrySet().stream()
.map(e -> e.getValue().getExportName())
.collect(Collectors.joining(separatorAsStr));
} | java | {
"resource": ""
} |
q16360 | SyntacticCategory.assignFeatures | train | public SyntacticCategory assignFeatures(Map<Integer, String> assignedFeatures,
Map<Integer, Integer> relabeledFeatures) {
String newFeatureValue = featureValue;
int newFeatureVariable = featureVariable;
if (assignedFeatures.containsKey(featureVariable)) {
newFeatureValue = assignedFeatures.get(featureVariable);
newFeatureVariable = -1;
} else if (relabeledFeatures.containsKey(featureVariable)) {
newFeatureVariable = relabeledFeatures.get(newFeatureVariable);
}
if (isAtomic()) {
return SyntacticCategory.createAtomic(value, newFeatureValue, newFeatureVariable);
} else {
SyntacticCategory assignedReturn = returnType.assignFeatures(assignedFeatures, relabeledFeatures);
SyntacticCategory assignedArgument = argumentType.assignFeatures(assignedFeatures, relabeledFeatures);
return SyntacticCategory.createFunctional(direction, assignedReturn, assignedArgument, newFeatureValue, newFeatureVariable);
}
} | java | {
"resource": ""
} |
q16361 | SyntacticCategory.assignAllFeatures | train | public SyntacticCategory assignAllFeatures(String value) {
Set<Integer> featureVars = Sets.newHashSet();
getAllFeatureVariables(featureVars);
Map<Integer, String> valueMap = Maps.newHashMap();
for (Integer var : featureVars) {
valueMap.put(var, value);
}
return assignFeatures(valueMap, Collections.<Integer, Integer>emptyMap());
} | java | {
"resource": ""
} |
q16362 | SyntacticCategory.getWithoutFeatures | train | public SyntacticCategory getWithoutFeatures() {
if (isAtomic()) {
return createAtomic(value, DEFAULT_FEATURE_VALUE, -1);
} else {
return createFunctional(getDirection(), returnType.getWithoutFeatures(),
argumentType.getWithoutFeatures());
}
} | java | {
"resource": ""
} |
q16363 | SyntacticCategory.getArgumentList | train | public List<SyntacticCategory> getArgumentList() {
if (isAtomic()) {
return Lists.newArrayList();
} else {
List<SyntacticCategory> args = getReturn().getArgumentList();
args.add(getArgument());
return args;
}
} | java | {
"resource": ""
} |
q16364 | JunctionTree.cliqueTreeToMaxMarginalSet | train | private static MaxMarginalSet cliqueTreeToMaxMarginalSet(CliqueTree cliqueTree,
FactorGraph originalFactorGraph) {
for (int i = 0; i < cliqueTree.numFactors(); i++) {
computeMarginal(cliqueTree, i, false);
}
return new FactorMaxMarginalSet(cliqueTree, originalFactorGraph.getConditionedValues());
} | java | {
"resource": ""
} |
q16365 | DigitalSignature.sign | train | public String sign(String content, PrivateKey privateKey) {
if (content == null) {
return null;
}
byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
InputStream input = new ByteArrayInputStream(bytes);
return sign(input, privateKey);
// ByteArrayInputStream does not need to be closed.
} | java | {
"resource": ""
} |
q16366 | DigitalSignature.verify | train | public boolean verify(String content, PublicKey publicKey, String signature) {
byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
InputStream input = new ByteArrayInputStream(bytes);
return verify(input, publicKey, signature);
// ByteArrayInputStream does not need to be closed.
} | java | {
"resource": ""
} |
q16367 | Assignment.union | train | public final Assignment union(Assignment other) {
Preconditions.checkNotNull(other);
if (other.size() == 0) {
return this;
} if (vars.length == 0) {
return other;
}
// Merge varnums / values
int[] otherNums = other.getVariableNumsArray();
int[] myNums = getVariableNumsArray();
Object[] otherVals = other.getValuesArray();
Object[] myVals = getValuesArray();
int[] mergedNums = new int[otherNums.length + myNums.length];
Object[] mergedVals = new Object[otherNums.length + myNums.length];
int i = 0;
int j = 0;
int numFilled = 0;
while (i < otherNums.length && j < myNums.length) {
if (otherNums[i] < myNums[j]) {
mergedNums[numFilled] = otherNums[i];
mergedVals[numFilled] = otherVals[i];
i++;
numFilled++;
} else if (otherNums[i] > myNums[j]) {
mergedNums[numFilled] = myNums[j];
mergedVals[numFilled] = myVals[j];
j++;
numFilled++;
} else {
Preconditions.checkState(false, "Cannot combine non-disjoint assignments: %s with %s", this, other);
}
}
// One list might still have elements in it.
while (i < otherNums.length) {
mergedNums[numFilled] = otherNums[i];
mergedVals[numFilled] = otherVals[i];
i++;
numFilled++;
}
while (j < myNums.length) {
mergedNums[numFilled] = myNums[j];
mergedVals[numFilled] = myVals[j];
j++;
numFilled++;
}
Preconditions.checkState(numFilled == mergedNums.length);
return Assignment.fromSortedArrays(mergedNums, mergedVals);
} | java | {
"resource": ""
} |
q16368 | Assignment.removeAll | train | @Deprecated
public final Assignment removeAll(Collection<Integer> varNumsToRemove) {
return removeAll(Ints.toArray(varNumsToRemove));
} | java | {
"resource": ""
} |
q16369 | Assignment.mapVariables | train | public Assignment mapVariables(Map<Integer, Integer> varMap) {
int[] newVarNums = new int[vars.length];
Object[] newValues = new Object[vars.length];
int numFilled = 0;
for (int i = 0; i < vars.length; i++) {
if (varMap.containsKey(vars[i])) {
newVarNums[numFilled] = varMap.get(vars[i]);
newValues[numFilled] = values[i];
numFilled++;
}
}
if (numFilled < newVarNums.length) {
newVarNums = Arrays.copyOf(newVarNums, numFilled);
newValues = Arrays.copyOf(newValues, numFilled);
}
return Assignment.fromUnsortedArrays(newVarNums, newValues);
} | java | {
"resource": ""
} |
q16370 | DB_Rdbms.curateIgnoredColumns | train | private String[] curateIgnoredColumns(String[] ignoredColumns) {
if(ignoredColumns == null){
return null;
}else{
String[] curated = new String[ignoredColumns.length];
for(int i = 0; i < ignoredColumns.length; i++){
if(ignoredColumns[i] != null){
String[] splinters = ignoredColumns[i].split("\\.");
if(splinters != null && splinters.length > 0){
String last = splinters[splinters.length - 1];
curated[i] = last;
}
}
}
return curated;
}
} | java | {
"resource": ""
} |
q16371 | XmlStorage.hasFileChangedUnexpectedly | train | private boolean hasFileChangedUnexpectedly() {
synchronized (this) {
if (mDiskWritesInFlight > 0) {
// If we know we caused it, it's not unexpected.
if (DEBUG) System.out.println( "disk write in flight, not unexpected.");
return false;
}
}
if (!mFile.canRead()) {
return true;
}
synchronized (this) {
return mStatTimestamp != mFile.lastModified() || mStatSize != mFile.length();
}
} | java | {
"resource": ""
} |
q16372 | XmlStorage.enqueueDiskWrite | train | private void enqueueDiskWrite(final MemoryCommitResult mcr,
final Runnable postWriteRunnable) {
final Runnable writeToDiskRunnable = new Runnable() {
public void run() {
synchronized (mWritingToDiskLock) {
writeToFile(mcr);
}
synchronized (XmlStorage.this) {
mDiskWritesInFlight--;
}
if (postWriteRunnable != null) {
postWriteRunnable.run();
}
}
};
final boolean isFromSyncCommit = (postWriteRunnable == null);
// Typical #commit() path with fewer allocations, doing a write on
// the current thread.
if (isFromSyncCommit) {
boolean wasEmpty = false;
synchronized (XmlStorage.this) {
wasEmpty = mDiskWritesInFlight == 1;
}
if (wasEmpty) {
writeToDiskRunnable.run();
return;
}
}
QueuedWork.singleThreadExecutor().execute(writeToDiskRunnable);
} | java | {
"resource": ""
} |
q16373 | IoUtils.readLines | train | public static List<String> readLines(String filename) {
List<String> lines = Lists.newArrayList();
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
String line;
while ((line = in.readLine()) != null) {
// Ignore blank lines.
if (line.trim().length() > 0) {
lines.add(line);
}
}
in.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return lines;
} | java | {
"resource": ""
} |
q16374 | TaggerUtils.reformatTrainingData | train | public static <I, O> List<Example<DynamicAssignment, DynamicAssignment>> reformatTrainingData(
List<? extends TaggedSequence<I, O>> sequences, FeatureVectorGenerator<LocalContext<I>> featureGen,
Function<? super LocalContext<I>, ? extends Object> inputGen, DynamicVariableSet modelVariables,
I startInput, O startLabel) {
Preconditions.checkArgument(!(startInput == null ^ startLabel == null));
DynamicVariableSet plate = modelVariables.getPlate(PLATE_NAME);
VariableNumMap x = plate.getFixedVariables().getVariablesByName(INPUT_FEATURES_NAME);
VariableNumMap xInput = plate.getFixedVariables().getVariablesByName(INPUT_NAME);
VariableNumMap y = plate.getFixedVariables().getVariablesByName(OUTPUT_NAME);
List<Example<DynamicAssignment, DynamicAssignment>> examples = Lists.newArrayList();
for (TaggedSequence<I, O> sequence : sequences) {
List<Assignment> inputs = Lists.newArrayList();
if (startInput != null) {
List<I> newItems = Lists.newArrayList();
newItems.add(startInput);
newItems.addAll(sequence.getItems());
LocalContext<I> startContext = new ListLocalContext<I>(newItems, 0);
Assignment inputFeatureVector = x.outcomeArrayToAssignment(featureGen.apply(startContext));
Assignment inputElement = xInput.outcomeArrayToAssignment(inputGen.apply(startContext));
Assignment firstLabel = y.outcomeArrayToAssignment(startLabel);
inputs.add(Assignment.unionAll(inputFeatureVector, inputElement, firstLabel));
}
List<LocalContext<I>> contexts = sequence.getLocalContexts();
for (int i = 0; i < contexts.size(); i++) {
Assignment inputFeatureVector = x.outcomeArrayToAssignment(featureGen.apply(contexts.get(i)));
Assignment inputElement = xInput.outcomeArrayToAssignment(inputGen.apply(contexts.get(i)));
inputs.add(inputFeatureVector.union(inputElement));
}
DynamicAssignment input = DynamicAssignment.createPlateAssignment(PLATE_NAME, inputs);
DynamicAssignment output = DynamicAssignment.EMPTY;
if (sequence.getLabels() != null) {
List<Assignment> outputs = Lists.newArrayList();
if (startInput != null) {
// First label is given (and equal to the special start label).
outputs.add(Assignment.EMPTY);
}
List<O> labels = sequence.getLabels();
for (int i = 0; i < contexts.size(); i++) {
outputs.add(y.outcomeArrayToAssignment(labels.get(i)));
}
output = DynamicAssignment.createPlateAssignment(PLATE_NAME, outputs);
}
examples.add(Example.create(input, output));
}
return examples;
} | java | {
"resource": ""
} |
q16375 | TaggerUtils.reformatTrainingDataPerItem | train | public static <I, O> List<Example<DynamicAssignment, DynamicAssignment>> reformatTrainingDataPerItem(
List<? extends TaggedSequence<I, O>> sequences, FeatureVectorGenerator<LocalContext<I>> featureGen,
Function<? super LocalContext<I>, ? extends Object> inputGen, DynamicVariableSet modelVariables,
I startInput, O startLabel) {
DynamicVariableSet plate = modelVariables.getPlate(PLATE_NAME);
VariableNumMap x = plate.getFixedVariables().getVariablesByName(INPUT_FEATURES_NAME);
VariableNumMap xInput = plate.getFixedVariables().getVariablesByName(INPUT_NAME);
VariableNumMap y = plate.getFixedVariables().getVariablesByName(OUTPUT_NAME);
ReformatPerItemMapper<I, O> mapper = new ReformatPerItemMapper<I, O>(featureGen, inputGen, x, xInput, y,
startInput, startLabel);
List<List<Example<DynamicAssignment, DynamicAssignment>>> exampleLists = MapReduceConfiguration
.getMapReduceExecutor().map(sequences, mapper);
List<Example<DynamicAssignment, DynamicAssignment>> examples = Lists.newArrayList();
for (List<Example<DynamicAssignment, DynamicAssignment>> exampleList : exampleLists) {
examples.addAll(exampleList);
}
return examples;
} | java | {
"resource": ""
} |
q16376 | TaggerUtils.trainSequenceModel | train | public static <I, O> FactorGraphSequenceTagger<I, O> trainSequenceModel(
ParametricFactorGraph sequenceModelFamily, List<Example<DynamicAssignment, DynamicAssignment>> examples,
Class<O> outputClass, FeatureVectorGenerator<LocalContext<I>> featureGen,
Function<? super LocalContext<I>, ? extends Object> inputGen, I startInput, O startLabel,
GradientOptimizer optimizer, boolean useMaxMargin) {
// Generate the training data and estimate parameters.
SufficientStatistics parameters = estimateParameters(sequenceModelFamily, examples,
optimizer, useMaxMargin);
DynamicFactorGraph factorGraph = sequenceModelFamily.getModelFromParameters(parameters);
return new FactorGraphSequenceTagger<I, O>(sequenceModelFamily, parameters,
factorGraph, featureGen, inputGen, outputClass, new JunctionTree(), new JunctionTree(true),
startInput, startLabel);
} | java | {
"resource": ""
} |
q16377 | GCMRegistrar.onDestroy | train | public static synchronized void onDestroy(Context context) {
if (sRetryReceiver != null) {
Log.v(TAG, "Unregistering receiver");
context.unregisterReceiver(sRetryReceiver);
sRetryReceiver = null;
}
} | java | {
"resource": ""
} |
q16378 | GCMRegistrar.setRegistrationId | train | static String setRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
String oldRegistrationId = prefs.getString(PROPERTY_REG_ID, "");
int appVersion = getAppVersion(context);
Log.v(TAG, "Saving regId on app version " + appVersion);
Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
return oldRegistrationId;
} | java | {
"resource": ""
} |
q16379 | GCMRegistrar.setRegisteredOnServer | train | public static void setRegisteredOnServer(Context context, boolean flag) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
editor.putBoolean(PROPERTY_ON_SERVER, flag);
// set the flag's expiration date
long lifespan = getRegisterOnServerLifespan(context);
long expirationTime = System.currentTimeMillis() + lifespan;
Log.v(TAG, "Setting registeredOnServer status as " + flag + " until " +
new Timestamp(expirationTime));
editor.putLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, expirationTime);
editor.commit();
} | java | {
"resource": ""
} |
q16380 | GCMRegistrar.getAppVersion | train | private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Coult not get package name: " + e);
}
} | java | {
"resource": ""
} |
q16381 | GCMRegistrar.getBackoff | train | static int getBackoff(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
return prefs.getInt(BACKOFF_MS, DEFAULT_BACKOFF_MS);
} | java | {
"resource": ""
} |
q16382 | DenseTensor.denseTensorInnerProduct | train | private double denseTensorInnerProduct(DenseTensor other) {
double[] otherValues = other.values;
int length = values.length;
Preconditions.checkArgument(otherValues.length == length);
double innerProduct = 0.0;
for (int i = 0; i < length; i++) {
innerProduct += values[i] * otherValues[i];
}
return innerProduct;
} | java | {
"resource": ""
} |
q16383 | BasicScanner.buildDeclaredAnnotationList | train | private List<Annotation> buildDeclaredAnnotationList(final Annotation annotation) {
final List<Annotation> list = Arrays.stream(annotation.annotationType().getDeclaredAnnotations())
.collect(Collectors.toList());
list.add(annotation);
return list;
} | java | {
"resource": ""
} |
q16384 | CrossValidationEvaluation.kFold | train | public static <I, O> CrossValidationEvaluation<I, O> kFold(
Collection<Example<I, O>> data, int k) {
Preconditions.checkNotNull(data);
Preconditions.checkArgument(k > 1);
int numTrainingPoints = data.size();
List<Collection<Example<I, O>>> folds = Lists.newArrayList();
for (List<Example<I, O>> fold : Iterables.partition(data, (int) Math.ceil(numTrainingPoints / k))) {
folds.add(fold);
}
return new CrossValidationEvaluation<I, O>(folds);
} | java | {
"resource": ""
} |
q16385 | ModelDef.getLocalColumns | train | public String[] getLocalColumns(String modelName) {
List<String> columnList = new ArrayList<String>();
for(int i = 0; i < this.hasOne.length; i++){
if(modelName.equalsIgnoreCase(this.hasOne[i])){
columnList.add(hasOneLocalColumn[i]);
}
}
for(int j = 0; j < this.hasMany.length; j++){
if(modelName.equalsIgnoreCase(hasMany[j])){
columnList.add(hasManyLocalColumn[j]);
}
}
if(columnList.size() == 0){
return null;
}
return columnList.toArray(new String[columnList.size()]);
} | java | {
"resource": ""
} |
q16386 | ModelDef.getPlainProperties | train | public String[] getPlainProperties(){
String[] commonColumns = {"created", "createdby", "updated","updatedby", "isactive"};
String[] referencedProperties = getReferencedColumns();
List<String> plainProperties = new ArrayList<String>();
for(String att : attributes){
if(CStringUtils.indexOf(referencedProperties, att) >= 0 ){
//do not include referenced columns
}
else if(att.endsWith("_id")){
;//do not include implied columns
}
else if(CStringUtils.indexOf(commonColumns, att) >= 0){
;//do not include common columns
}
else{
plainProperties.add(att);
}
}
return plainProperties.toArray(new String[plainProperties.size()]);
} | java | {
"resource": ""
} |
q16387 | ExtractionResult.add | train | public void add(Object entity, String name) {
Result result = new Result(entity, name);
results.add(result);
} | java | {
"resource": ""
} |
q16388 | ExtractionResult.getEntities | train | public List<Object> getEntities(String name) {
List<Object> entitiesList = new LinkedList<Object>();
for (Result result : results) {
if (result.getResultName().equals(name)) {
entitiesList.add(result.getObject());
}
}
return entitiesList;
} | java | {
"resource": ""
} |
q16389 | ExtractionResult.getEntities | train | public List<Object> getEntities() {
List<Object> entitiesList = new LinkedList<Object>();
for (Result result : results) {
entitiesList.add(result.getObject());
}
return entitiesList;
} | java | {
"resource": ""
} |
q16390 | DenseTensorBuilder.simpleIncrement | train | private void simpleIncrement(TensorBase other, double multiplier) {
Preconditions.checkArgument(Arrays.equals(other.getDimensionNumbers(), getDimensionNumbers()));
if (other instanceof DenseTensorBase) {
double[] otherTensorValues = ((DenseTensorBase) other).values;
Preconditions.checkArgument(otherTensorValues.length == values.length);
int length = values.length;
for (int i = 0; i < length; i++) {
values[i] += otherTensorValues[i] * multiplier;
}
} else {
int otherSize = other.size();
for (int i = 0; i < otherSize; i++) {
long keyNum = other.indexToKeyNum(i);
double value = other.getByIndex(i);
values[keyNumToIndex(keyNum)] += value * multiplier;
}
}
} | java | {
"resource": ""
} |
q16391 | DAOGenerator.getOverrideModel | train | private ModelDef getOverrideModel(ModelDef model,
ModelMetaData explicitMeta2) {
if(explicitMeta2 == null){
return model;
}
List<ModelDef> explicitList = explicitMeta2.getModelDefinitionList();
for(ModelDef explicitModel : explicitList){
if(explicitModel.getModelName().equals(model.getModelName())){
return explicitModel;
}
}
return model;
} | java | {
"resource": ""
} |
q16392 | DAOGenerator.chooseFirstOccurence | train | private String chooseFirstOccurence(String[] among_owners, String[] within_listgroup,
String prior_tableName) {
int index = CStringUtils.indexOf(within_listgroup, prior_tableName);
for(int i = index-1; i >= 0; i-- ){
String closest = within_listgroup[i];
if(CStringUtils.indexOf(among_owners, closest) >= 0){
return closest;
}
}
return null;
} | java | {
"resource": ""
} |
q16393 | DAOGenerator.transformGroup | train | private Map<String, Set<String[]>> transformGroup(List<String[]> tableGroups) {
Map<String, Set<String[]>> model_tableGroup = new LinkedHashMap<String, Set<String[]>>();
for(String[] list : tableGroups){
for(String table : list){
if(model_tableGroup.containsKey(table)){
Set<String[]> tableGroupSet = model_tableGroup.get(table);
tableGroupSet.add(list);
}
else{
Set<String[]> tableGroupSet = new HashSet<String[]>();
tableGroupSet.add(list);
model_tableGroup.put(table, tableGroupSet);
}
}
}
return model_tableGroup;
} | java | {
"resource": ""
} |
q16394 | BasicRandomRoutingTable.getNextHop | train | @Override
public TrustGraphNodeId getNextHop(final TrustGraphAdvertisement message) {
final TrustGraphNodeId prev = message.getSender();
return getNextHop(prev);
} | java | {
"resource": ""
} |
q16395 | BasicRandomRoutingTable.getNextHop | train | @Override
public TrustGraphNodeId getNextHop(final TrustGraphNodeId priorNeighbor) {
if (priorNeighbor != null) {
return routingTable.get(priorNeighbor);
}
else {
return null;
}
} | java | {
"resource": ""
} |
q16396 | BasicRandomRoutingTable.addNeighbor | train | @Override
public void addNeighbor(final TrustGraphNodeId neighbor) {
if (neighbor == null) {
return;
}
// all modification operations are serialized
synchronized(this) {
// do not add this neighbor if it is already present
if (contains(neighbor)) {
return;
}
/* If there is nothing in the table, route the neighbor to itself.
* this condition is fixed during the next single addition since
* the route is always selected to be split. The bulk add
* operation also takes special care to perform a single addition
* if this state exists before adding additional routes.
*/
if (routingTable.isEmpty()) {
routingTable.put(neighbor, neighbor);
}
/* otherwise, pick a random existing route X->Y and
* split it into two routes, X->neighbor and neighbor->Y
*/
else {
Map.Entry<TrustGraphNodeId,TrustGraphNodeId> split =
randomRoute();
TrustGraphNodeId splitKey = split.getKey();
TrustGraphNodeId splitVal = split.getValue();
/*
* The new route neighbor->Y is inserted first. This
* preserves the existing routing behavior for readers
* until the entire operation is complete.
*/
routingTable.put(neighbor, splitVal);
routingTable.replace(splitKey, neighbor);
}
// add the neighbor to the ordering
addNeighborToOrdering(neighbor);
}
} | java | {
"resource": ""
} |
q16397 | BasicRandomRoutingTable.randomRoute | train | protected Map.Entry<TrustGraphNodeId,TrustGraphNodeId> randomRoute() {
final int routeNumber = rng.nextInt(routingTable.size());
final Iterator<Map.Entry<TrustGraphNodeId,TrustGraphNodeId>> routes =
routingTable.entrySet().iterator();
for (int i = 0; i < routeNumber; i++) { routes.next(); }
return routes.next();
} | java | {
"resource": ""
} |
q16398 | BasicRandomRoutingTable.addNeighbors | train | @Override
public void addNeighbors(final Collection<TrustGraphNodeId> neighborsIn) {
if (neighborsIn.isEmpty()) {
return;
}
// all modification operations are serialized
synchronized (this) {
/* filter out any neighbors that are already in the routing table
* and the new ones to the newNeighbors list
*/
final LinkedList<TrustGraphNodeId> newNeighbors =
new LinkedList<TrustGraphNodeId>();
for (TrustGraphNodeId n : neighborsIn) {
if (!contains(n)) {
newNeighbors.add(n);
}
}
// if there is nothing new, we're done.
if (newNeighbors.size() == 0) {
return;
}
// handle list of length 1 the same way as a single insertion
else if (newNeighbors.size() == 1) {
addNeighbor(newNeighbors.get(0));
return;
}
// otherwise there is more than one new neighbor to add.
/* if there are existing routes, a random route in the
* table will be split. It is picked prior to adding
* any of the new routes.
*/
Map.Entry<TrustGraphNodeId,TrustGraphNodeId> split = null;
if (!routingTable.isEmpty()) {
// Pick a random existing route X->Y to split
split = randomRoute();
}
/* Create a random permutation of the list.
* Add in new neighbors from this permutation, routing
* i->i+1. These routes do not disturb any existing
* routes and create no self references.
*/
Collections.shuffle(newNeighbors, rng);
final Iterator<TrustGraphNodeId> i = newNeighbors.iterator();
TrustGraphNodeId key = i.next();
while (i.hasNext()) {
final TrustGraphNodeId val = i.next();
routingTable.put(key,val);
key = val;
}
/* if there was nothing in the routing table yet, the first
* item in the permutation is routed to the last.
*/
if (split == null) {
// loop around, bind the last to the first
routingTable.put(newNeighbors.getLast(), newNeighbors.getFirst());
}
/* Otherwise, split the route chosen beforehand. Map the
* key to the first node in the chain, and map the
* last node in the chain to the value. ie X->Y becomes
* X->first->....->last->Y. Similarly to the single
* neighbor add method above, this preserves the structure
* of the routing table forming some circular chain of
* nodes of length equal to the size of the table.
*/
else {
TrustGraphNodeId splitKey = split.getKey();
TrustGraphNodeId splitVal = split.getValue();
/*
* Add routes X-> first and last->Y. The new route last->Y is
* inserted first. This preserves the existing routing behavior
* for readers until the entire operation is complete.
*/
routingTable.put(newNeighbors.getLast(), splitVal);
routingTable.replace(splitKey, newNeighbors.getFirst());
}
/* add the new neighbors into the ordering */
addNeighborsToOrdering(newNeighbors);
}
} | java | {
"resource": ""
} |
q16399 | BasicRandomRoutingTable.removeNeighbor | train | @Override
public void removeNeighbor(final TrustGraphNodeId neighbor) {
// all modification operations are serialized
synchronized(this) {
// do nothing if there is no entry for the neighbor specified
if (!contains(neighbor)) {
return;
}
/* first remove the neighbor from the ordering. This will
* prevent it from being advertised to.
*/
removeNeighborFromOrdering(neighbor);
removeNeighborFromRoutingTable(neighbor);
}
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.