id int32 0 165k | repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1 value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 |
|---|---|---|---|---|---|---|---|---|---|---|---|
22,800 | raphw/byte-buddy | byte-buddy-benchmark/src/main/java/net/bytebuddy/benchmark/ClassByExtensionBenchmark.java | ClassByExtensionBenchmark.benchmarkByteBuddyWithAccessorAndReusedDelegatorWithTypePool | @Benchmark
public ExampleClass benchmarkByteBuddyWithAccessorAndReusedDelegatorWithTypePool() throws Exception {
return (ExampleClass) new ByteBuddy()
.with(TypeValidation.DISABLED)
.ignore(none())
.subclass(baseClassDescription)
.method(isDeclaredBy(baseClassDescription)).intercept(accessInterceptorDescription)
.make()
.load(newClassLoader(), ClassLoadingStrategy.Default.INJECTION)
.getLoaded()
.getDeclaredConstructor()
.newInstance();
} | java | @Benchmark
public ExampleClass benchmarkByteBuddyWithAccessorAndReusedDelegatorWithTypePool() throws Exception {
return (ExampleClass) new ByteBuddy()
.with(TypeValidation.DISABLED)
.ignore(none())
.subclass(baseClassDescription)
.method(isDeclaredBy(baseClassDescription)).intercept(accessInterceptorDescription)
.make()
.load(newClassLoader(), ClassLoadingStrategy.Default.INJECTION)
.getLoaded()
.getDeclaredConstructor()
.newInstance();
} | [
"@",
"Benchmark",
"public",
"ExampleClass",
"benchmarkByteBuddyWithAccessorAndReusedDelegatorWithTypePool",
"(",
")",
"throws",
"Exception",
"{",
"return",
"(",
"ExampleClass",
")",
"new",
"ByteBuddy",
"(",
")",
".",
"with",
"(",
"TypeValidation",
".",
"DISABLED",
")",
".",
"ignore",
"(",
"none",
"(",
")",
")",
".",
"subclass",
"(",
"baseClassDescription",
")",
".",
"method",
"(",
"isDeclaredBy",
"(",
"baseClassDescription",
")",
")",
".",
"intercept",
"(",
"accessInterceptorDescription",
")",
".",
"make",
"(",
")",
".",
"load",
"(",
"newClassLoader",
"(",
")",
",",
"ClassLoadingStrategy",
".",
"Default",
".",
"INJECTION",
")",
".",
"getLoaded",
"(",
")",
".",
"getDeclaredConstructor",
"(",
")",
".",
"newInstance",
"(",
")",
";",
"}"
] | Performs a benchmark of a class extension using Byte Buddy. This benchmark also uses the annotation-based approach
but creates delegation methods which do not require the creation of additional classes. This benchmark reuses a
precomputed delegator. This benchmark uses a type pool to compare against usage of the reflection API.
@return The created instance, in order to avoid JIT removal.
@throws Exception If the invocation causes an exception. | [
"Performs",
"a",
"benchmark",
"of",
"a",
"class",
"extension",
"using",
"Byte",
"Buddy",
".",
"This",
"benchmark",
"also",
"uses",
"the",
"annotation",
"-",
"based",
"approach",
"but",
"creates",
"delegation",
"methods",
"which",
"do",
"not",
"require",
"the",
"creation",
"of",
"additional",
"classes",
".",
"This",
"benchmark",
"reuses",
"a",
"precomputed",
"delegator",
".",
"This",
"benchmark",
"uses",
"a",
"type",
"pool",
"to",
"compare",
"against",
"usage",
"of",
"the",
"reflection",
"API",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-benchmark/src/main/java/net/bytebuddy/benchmark/ClassByExtensionBenchmark.java#L323-L335 |
22,801 | raphw/byte-buddy | byte-buddy-benchmark/src/main/java/net/bytebuddy/benchmark/ClassByExtensionBenchmark.java | ClassByExtensionBenchmark.benchmarkCglib | @Benchmark
public ExampleClass benchmarkCglib() {
Enhancer enhancer = new Enhancer();
enhancer.setUseCache(false);
enhancer.setUseFactory(false);
enhancer.setInterceptDuringConstruction(true);
enhancer.setClassLoader(newClassLoader());
enhancer.setSuperclass(baseClass);
CallbackHelper callbackHelper = new CallbackHelper(baseClass, new Class[0]) {
protected Object getCallback(Method method) {
if (method.getDeclaringClass() == baseClass) {
return new MethodInterceptor() {
public Object intercept(Object object,
Method method,
Object[] arguments,
MethodProxy methodProxy) throws Throwable {
return methodProxy.invokeSuper(object, arguments);
}
};
} else {
return NoOp.INSTANCE;
}
}
};
enhancer.setCallbackFilter(callbackHelper);
enhancer.setCallbacks(callbackHelper.getCallbacks());
return (ExampleClass) enhancer.create();
} | java | @Benchmark
public ExampleClass benchmarkCglib() {
Enhancer enhancer = new Enhancer();
enhancer.setUseCache(false);
enhancer.setUseFactory(false);
enhancer.setInterceptDuringConstruction(true);
enhancer.setClassLoader(newClassLoader());
enhancer.setSuperclass(baseClass);
CallbackHelper callbackHelper = new CallbackHelper(baseClass, new Class[0]) {
protected Object getCallback(Method method) {
if (method.getDeclaringClass() == baseClass) {
return new MethodInterceptor() {
public Object intercept(Object object,
Method method,
Object[] arguments,
MethodProxy methodProxy) throws Throwable {
return methodProxy.invokeSuper(object, arguments);
}
};
} else {
return NoOp.INSTANCE;
}
}
};
enhancer.setCallbackFilter(callbackHelper);
enhancer.setCallbacks(callbackHelper.getCallbacks());
return (ExampleClass) enhancer.create();
} | [
"@",
"Benchmark",
"public",
"ExampleClass",
"benchmarkCglib",
"(",
")",
"{",
"Enhancer",
"enhancer",
"=",
"new",
"Enhancer",
"(",
")",
";",
"enhancer",
".",
"setUseCache",
"(",
"false",
")",
";",
"enhancer",
".",
"setUseFactory",
"(",
"false",
")",
";",
"enhancer",
".",
"setInterceptDuringConstruction",
"(",
"true",
")",
";",
"enhancer",
".",
"setClassLoader",
"(",
"newClassLoader",
"(",
")",
")",
";",
"enhancer",
".",
"setSuperclass",
"(",
"baseClass",
")",
";",
"CallbackHelper",
"callbackHelper",
"=",
"new",
"CallbackHelper",
"(",
"baseClass",
",",
"new",
"Class",
"[",
"0",
"]",
")",
"{",
"protected",
"Object",
"getCallback",
"(",
"Method",
"method",
")",
"{",
"if",
"(",
"method",
".",
"getDeclaringClass",
"(",
")",
"==",
"baseClass",
")",
"{",
"return",
"new",
"MethodInterceptor",
"(",
")",
"{",
"public",
"Object",
"intercept",
"(",
"Object",
"object",
",",
"Method",
"method",
",",
"Object",
"[",
"]",
"arguments",
",",
"MethodProxy",
"methodProxy",
")",
"throws",
"Throwable",
"{",
"return",
"methodProxy",
".",
"invokeSuper",
"(",
"object",
",",
"arguments",
")",
";",
"}",
"}",
";",
"}",
"else",
"{",
"return",
"NoOp",
".",
"INSTANCE",
";",
"}",
"}",
"}",
";",
"enhancer",
".",
"setCallbackFilter",
"(",
"callbackHelper",
")",
";",
"enhancer",
".",
"setCallbacks",
"(",
"callbackHelper",
".",
"getCallbacks",
"(",
")",
")",
";",
"return",
"(",
"ExampleClass",
")",
"enhancer",
".",
"create",
"(",
")",
";",
"}"
] | Performs a benchmark of a class extension using cglib.
@return The created instance, in order to avoid JIT removal. | [
"Performs",
"a",
"benchmark",
"of",
"a",
"class",
"extension",
"using",
"cglib",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-benchmark/src/main/java/net/bytebuddy/benchmark/ClassByExtensionBenchmark.java#L448-L475 |
22,802 | raphw/byte-buddy | byte-buddy-benchmark/src/main/java/net/bytebuddy/benchmark/ClassByExtensionBenchmark.java | ClassByExtensionBenchmark.benchmarkJavassist | @Benchmark
public ExampleClass benchmarkJavassist() throws Exception {
ProxyFactory proxyFactory = new ProxyFactory() {
protected ClassLoader getClassLoader() {
return newClassLoader();
}
};
proxyFactory.setUseCache(false);
proxyFactory.setUseWriteReplace(false);
proxyFactory.setSuperclass(baseClass);
proxyFactory.setFilter(new MethodFilter() {
public boolean isHandled(Method method) {
return method.getDeclaringClass() == baseClass;
}
});
@SuppressWarnings("unchecked")
Object instance = proxyFactory.createClass().getDeclaredConstructor().newInstance();
((javassist.util.proxy.Proxy) instance).setHandler(new MethodHandler() {
public Object invoke(Object self,
Method thisMethod,
Method proceed,
Object[] args) throws Throwable {
return proceed.invoke(self, args);
}
});
return (ExampleClass) instance;
} | java | @Benchmark
public ExampleClass benchmarkJavassist() throws Exception {
ProxyFactory proxyFactory = new ProxyFactory() {
protected ClassLoader getClassLoader() {
return newClassLoader();
}
};
proxyFactory.setUseCache(false);
proxyFactory.setUseWriteReplace(false);
proxyFactory.setSuperclass(baseClass);
proxyFactory.setFilter(new MethodFilter() {
public boolean isHandled(Method method) {
return method.getDeclaringClass() == baseClass;
}
});
@SuppressWarnings("unchecked")
Object instance = proxyFactory.createClass().getDeclaredConstructor().newInstance();
((javassist.util.proxy.Proxy) instance).setHandler(new MethodHandler() {
public Object invoke(Object self,
Method thisMethod,
Method proceed,
Object[] args) throws Throwable {
return proceed.invoke(self, args);
}
});
return (ExampleClass) instance;
} | [
"@",
"Benchmark",
"public",
"ExampleClass",
"benchmarkJavassist",
"(",
")",
"throws",
"Exception",
"{",
"ProxyFactory",
"proxyFactory",
"=",
"new",
"ProxyFactory",
"(",
")",
"{",
"protected",
"ClassLoader",
"getClassLoader",
"(",
")",
"{",
"return",
"newClassLoader",
"(",
")",
";",
"}",
"}",
";",
"proxyFactory",
".",
"setUseCache",
"(",
"false",
")",
";",
"proxyFactory",
".",
"setUseWriteReplace",
"(",
"false",
")",
";",
"proxyFactory",
".",
"setSuperclass",
"(",
"baseClass",
")",
";",
"proxyFactory",
".",
"setFilter",
"(",
"new",
"MethodFilter",
"(",
")",
"{",
"public",
"boolean",
"isHandled",
"(",
"Method",
"method",
")",
"{",
"return",
"method",
".",
"getDeclaringClass",
"(",
")",
"==",
"baseClass",
";",
"}",
"}",
")",
";",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Object",
"instance",
"=",
"proxyFactory",
".",
"createClass",
"(",
")",
".",
"getDeclaredConstructor",
"(",
")",
".",
"newInstance",
"(",
")",
";",
"(",
"(",
"javassist",
".",
"util",
".",
"proxy",
".",
"Proxy",
")",
"instance",
")",
".",
"setHandler",
"(",
"new",
"MethodHandler",
"(",
")",
"{",
"public",
"Object",
"invoke",
"(",
"Object",
"self",
",",
"Method",
"thisMethod",
",",
"Method",
"proceed",
",",
"Object",
"[",
"]",
"args",
")",
"throws",
"Throwable",
"{",
"return",
"proceed",
".",
"invoke",
"(",
"self",
",",
"args",
")",
";",
"}",
"}",
")",
";",
"return",
"(",
"ExampleClass",
")",
"instance",
";",
"}"
] | Performs a benchmark of a class extension using javassist proxies.
@return The created instance, in order to avoid JIT removal.
@throws java.lang.Exception If the invocation causes an exception. | [
"Performs",
"a",
"benchmark",
"of",
"a",
"class",
"extension",
"using",
"javassist",
"proxies",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-benchmark/src/main/java/net/bytebuddy/benchmark/ClassByExtensionBenchmark.java#L483-L509 |
22,803 | raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/ByteBuddy.java | ByteBuddy.rebase | public <T> DynamicType.Builder<T> rebase(TypeDescription type, ClassFileLocator classFileLocator, MethodNameTransformer methodNameTransformer) {
if (type.isArray() || type.isPrimitive()) {
throw new IllegalArgumentException("Cannot rebase array or primitive type: " + type);
}
return new RebaseDynamicTypeBuilder<T>(instrumentedTypeFactory.represent(type),
classFileVersion,
auxiliaryTypeNamingStrategy,
annotationValueFilterFactory,
annotationRetention,
implementationContextFactory,
methodGraphCompiler,
typeValidation,
visibilityBridgeStrategy,
classWriterStrategy,
ignoredMethods,
type,
classFileLocator,
methodNameTransformer);
} | java | public <T> DynamicType.Builder<T> rebase(TypeDescription type, ClassFileLocator classFileLocator, MethodNameTransformer methodNameTransformer) {
if (type.isArray() || type.isPrimitive()) {
throw new IllegalArgumentException("Cannot rebase array or primitive type: " + type);
}
return new RebaseDynamicTypeBuilder<T>(instrumentedTypeFactory.represent(type),
classFileVersion,
auxiliaryTypeNamingStrategy,
annotationValueFilterFactory,
annotationRetention,
implementationContextFactory,
methodGraphCompiler,
typeValidation,
visibilityBridgeStrategy,
classWriterStrategy,
ignoredMethods,
type,
classFileLocator,
methodNameTransformer);
} | [
"public",
"<",
"T",
">",
"DynamicType",
".",
"Builder",
"<",
"T",
">",
"rebase",
"(",
"TypeDescription",
"type",
",",
"ClassFileLocator",
"classFileLocator",
",",
"MethodNameTransformer",
"methodNameTransformer",
")",
"{",
"if",
"(",
"type",
".",
"isArray",
"(",
")",
"||",
"type",
".",
"isPrimitive",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Cannot rebase array or primitive type: \"",
"+",
"type",
")",
";",
"}",
"return",
"new",
"RebaseDynamicTypeBuilder",
"<",
"T",
">",
"(",
"instrumentedTypeFactory",
".",
"represent",
"(",
"type",
")",
",",
"classFileVersion",
",",
"auxiliaryTypeNamingStrategy",
",",
"annotationValueFilterFactory",
",",
"annotationRetention",
",",
"implementationContextFactory",
",",
"methodGraphCompiler",
",",
"typeValidation",
",",
"visibilityBridgeStrategy",
",",
"classWriterStrategy",
",",
"ignoredMethods",
",",
"type",
",",
"classFileLocator",
",",
"methodNameTransformer",
")",
";",
"}"
] | Rebases the given type where any intercepted method that is declared by the redefined type is preserved within the
rebased type's class such that the class's original can be invoked from the new method implementations. Rebasing a
type can be seen similarly to creating a subclass where the subclass is later merged with the original class file.
@param type The type that is being rebased.
@param classFileLocator The class file locator that is queried for the rebased type's class file.
@param methodNameTransformer The method name transformer for renaming a method that is rebased.
@param <T> The loaded type of the rebased type.
@return A type builder for rebasing the provided type. | [
"Rebases",
"the",
"given",
"type",
"where",
"any",
"intercepted",
"method",
"that",
"is",
"declared",
"by",
"the",
"redefined",
"type",
"is",
"preserved",
"within",
"the",
"rebased",
"type",
"s",
"class",
"such",
"that",
"the",
"class",
"s",
"original",
"can",
"be",
"invoked",
"from",
"the",
"new",
"method",
"implementations",
".",
"Rebasing",
"a",
"type",
"can",
"be",
"seen",
"similarly",
"to",
"creating",
"a",
"subclass",
"where",
"the",
"subclass",
"is",
"later",
"merged",
"with",
"the",
"original",
"class",
"file",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/ByteBuddy.java#L847-L865 |
22,804 | raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/scaffold/inline/RebaseImplementationTarget.java | RebaseImplementationTarget.of | protected static Implementation.Target of(TypeDescription instrumentedType,
MethodGraph.Linked methodGraph,
ClassFileVersion classFileVersion,
MethodRebaseResolver methodRebaseResolver) {
return new RebaseImplementationTarget(instrumentedType, methodGraph, DefaultMethodInvocation.of(classFileVersion), methodRebaseResolver.asTokenMap());
} | java | protected static Implementation.Target of(TypeDescription instrumentedType,
MethodGraph.Linked methodGraph,
ClassFileVersion classFileVersion,
MethodRebaseResolver methodRebaseResolver) {
return new RebaseImplementationTarget(instrumentedType, methodGraph, DefaultMethodInvocation.of(classFileVersion), methodRebaseResolver.asTokenMap());
} | [
"protected",
"static",
"Implementation",
".",
"Target",
"of",
"(",
"TypeDescription",
"instrumentedType",
",",
"MethodGraph",
".",
"Linked",
"methodGraph",
",",
"ClassFileVersion",
"classFileVersion",
",",
"MethodRebaseResolver",
"methodRebaseResolver",
")",
"{",
"return",
"new",
"RebaseImplementationTarget",
"(",
"instrumentedType",
",",
"methodGraph",
",",
"DefaultMethodInvocation",
".",
"of",
"(",
"classFileVersion",
")",
",",
"methodRebaseResolver",
".",
"asTokenMap",
"(",
")",
")",
";",
"}"
] | Creates a new rebase implementation target.
@param instrumentedType The instrumented type.
@param methodGraph A method graph of the instrumented type.
@param classFileVersion The type's class file version.
@param methodRebaseResolver A method rebase resolver to be used when calling a rebased method.
@return An implementation target for the given input. | [
"Creates",
"a",
"new",
"rebase",
"implementation",
"target",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/scaffold/inline/RebaseImplementationTarget.java#L73-L78 |
22,805 | raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/scaffold/inline/RebaseImplementationTarget.java | RebaseImplementationTarget.invokeSuper | private Implementation.SpecialMethodInvocation invokeSuper(MethodGraph.Node node) {
return node.getSort().isResolved()
? Implementation.SpecialMethodInvocation.Simple.of(node.getRepresentative(), instrumentedType.getSuperClass().asErasure())
: Implementation.SpecialMethodInvocation.Illegal.INSTANCE;
} | java | private Implementation.SpecialMethodInvocation invokeSuper(MethodGraph.Node node) {
return node.getSort().isResolved()
? Implementation.SpecialMethodInvocation.Simple.of(node.getRepresentative(), instrumentedType.getSuperClass().asErasure())
: Implementation.SpecialMethodInvocation.Illegal.INSTANCE;
} | [
"private",
"Implementation",
".",
"SpecialMethodInvocation",
"invokeSuper",
"(",
"MethodGraph",
".",
"Node",
"node",
")",
"{",
"return",
"node",
".",
"getSort",
"(",
")",
".",
"isResolved",
"(",
")",
"?",
"Implementation",
".",
"SpecialMethodInvocation",
".",
"Simple",
".",
"of",
"(",
"node",
".",
"getRepresentative",
"(",
")",
",",
"instrumentedType",
".",
"getSuperClass",
"(",
")",
".",
"asErasure",
"(",
")",
")",
":",
"Implementation",
".",
"SpecialMethodInvocation",
".",
"Illegal",
".",
"INSTANCE",
";",
"}"
] | Creates a special method invocation for the given node.
@param node The node for which a special method invocation is to be created.
@return A special method invocation for the provided node. | [
"Creates",
"a",
"special",
"method",
"invocation",
"for",
"the",
"given",
"node",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/scaffold/inline/RebaseImplementationTarget.java#L96-L100 |
22,806 | raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/scaffold/inline/RebaseImplementationTarget.java | RebaseImplementationTarget.invokeSuper | private Implementation.SpecialMethodInvocation invokeSuper(MethodRebaseResolver.Resolution resolution) {
return resolution.isRebased()
? RebasedMethodInvocation.of(resolution.getResolvedMethod(), instrumentedType, resolution.getAdditionalArguments())
: Implementation.SpecialMethodInvocation.Simple.of(resolution.getResolvedMethod(), instrumentedType);
} | java | private Implementation.SpecialMethodInvocation invokeSuper(MethodRebaseResolver.Resolution resolution) {
return resolution.isRebased()
? RebasedMethodInvocation.of(resolution.getResolvedMethod(), instrumentedType, resolution.getAdditionalArguments())
: Implementation.SpecialMethodInvocation.Simple.of(resolution.getResolvedMethod(), instrumentedType);
} | [
"private",
"Implementation",
".",
"SpecialMethodInvocation",
"invokeSuper",
"(",
"MethodRebaseResolver",
".",
"Resolution",
"resolution",
")",
"{",
"return",
"resolution",
".",
"isRebased",
"(",
")",
"?",
"RebasedMethodInvocation",
".",
"of",
"(",
"resolution",
".",
"getResolvedMethod",
"(",
")",
",",
"instrumentedType",
",",
"resolution",
".",
"getAdditionalArguments",
"(",
")",
")",
":",
"Implementation",
".",
"SpecialMethodInvocation",
".",
"Simple",
".",
"of",
"(",
"resolution",
".",
"getResolvedMethod",
"(",
")",
",",
"instrumentedType",
")",
";",
"}"
] | Creates a special method invocation for the given rebase resolution.
@param resolution The resolution for which a special method invocation is to be created.
@return A special method invocation for the provided resolution. | [
"Creates",
"a",
"special",
"method",
"invocation",
"for",
"the",
"given",
"rebase",
"resolution",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/scaffold/inline/RebaseImplementationTarget.java#L108-L112 |
22,807 | raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/agent/builder/LambdaFactory.java | LambdaFactory.register | @SuppressWarnings("all")
public static boolean register(ClassFileTransformer classFileTransformer, Object classFileFactory) {
try {
TypeDescription typeDescription = TypeDescription.ForLoadedType.of(LambdaFactory.class);
Class<?> lambdaFactory = ClassInjector.UsingReflection.ofSystemClassLoader()
.inject(Collections.singletonMap(typeDescription, ClassFileLocator.ForClassLoader.read(LambdaFactory.class)))
.get(typeDescription);
@SuppressWarnings("unchecked")
Map<ClassFileTransformer, Object> classFileTransformers = (Map<ClassFileTransformer, Object>) lambdaFactory
.getField(FIELD_NAME)
.get(null);
synchronized (classFileTransformers) {
try {
return classFileTransformers.isEmpty();
} finally {
classFileTransformers.put(classFileTransformer, lambdaFactory
.getConstructor(Object.class, Method.class)
.newInstance(classFileFactory, classFileFactory.getClass().getMethod("make",
Object.class,
String.class,
Object.class,
Object.class,
Object.class,
Object.class,
boolean.class,
List.class,
List.class,
Collection.class)));
}
}
} catch (RuntimeException exception) {
throw exception;
} catch (Exception exception) {
throw new IllegalStateException("Could not register class file transformer", exception);
}
} | java | @SuppressWarnings("all")
public static boolean register(ClassFileTransformer classFileTransformer, Object classFileFactory) {
try {
TypeDescription typeDescription = TypeDescription.ForLoadedType.of(LambdaFactory.class);
Class<?> lambdaFactory = ClassInjector.UsingReflection.ofSystemClassLoader()
.inject(Collections.singletonMap(typeDescription, ClassFileLocator.ForClassLoader.read(LambdaFactory.class)))
.get(typeDescription);
@SuppressWarnings("unchecked")
Map<ClassFileTransformer, Object> classFileTransformers = (Map<ClassFileTransformer, Object>) lambdaFactory
.getField(FIELD_NAME)
.get(null);
synchronized (classFileTransformers) {
try {
return classFileTransformers.isEmpty();
} finally {
classFileTransformers.put(classFileTransformer, lambdaFactory
.getConstructor(Object.class, Method.class)
.newInstance(classFileFactory, classFileFactory.getClass().getMethod("make",
Object.class,
String.class,
Object.class,
Object.class,
Object.class,
Object.class,
boolean.class,
List.class,
List.class,
Collection.class)));
}
}
} catch (RuntimeException exception) {
throw exception;
} catch (Exception exception) {
throw new IllegalStateException("Could not register class file transformer", exception);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"all\"",
")",
"public",
"static",
"boolean",
"register",
"(",
"ClassFileTransformer",
"classFileTransformer",
",",
"Object",
"classFileFactory",
")",
"{",
"try",
"{",
"TypeDescription",
"typeDescription",
"=",
"TypeDescription",
".",
"ForLoadedType",
".",
"of",
"(",
"LambdaFactory",
".",
"class",
")",
";",
"Class",
"<",
"?",
">",
"lambdaFactory",
"=",
"ClassInjector",
".",
"UsingReflection",
".",
"ofSystemClassLoader",
"(",
")",
".",
"inject",
"(",
"Collections",
".",
"singletonMap",
"(",
"typeDescription",
",",
"ClassFileLocator",
".",
"ForClassLoader",
".",
"read",
"(",
"LambdaFactory",
".",
"class",
")",
")",
")",
".",
"get",
"(",
"typeDescription",
")",
";",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Map",
"<",
"ClassFileTransformer",
",",
"Object",
">",
"classFileTransformers",
"=",
"(",
"Map",
"<",
"ClassFileTransformer",
",",
"Object",
">",
")",
"lambdaFactory",
".",
"getField",
"(",
"FIELD_NAME",
")",
".",
"get",
"(",
"null",
")",
";",
"synchronized",
"(",
"classFileTransformers",
")",
"{",
"try",
"{",
"return",
"classFileTransformers",
".",
"isEmpty",
"(",
")",
";",
"}",
"finally",
"{",
"classFileTransformers",
".",
"put",
"(",
"classFileTransformer",
",",
"lambdaFactory",
".",
"getConstructor",
"(",
"Object",
".",
"class",
",",
"Method",
".",
"class",
")",
".",
"newInstance",
"(",
"classFileFactory",
",",
"classFileFactory",
".",
"getClass",
"(",
")",
".",
"getMethod",
"(",
"\"make\"",
",",
"Object",
".",
"class",
",",
"String",
".",
"class",
",",
"Object",
".",
"class",
",",
"Object",
".",
"class",
",",
"Object",
".",
"class",
",",
"Object",
".",
"class",
",",
"boolean",
".",
"class",
",",
"List",
".",
"class",
",",
"List",
".",
"class",
",",
"Collection",
".",
"class",
")",
")",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"RuntimeException",
"exception",
")",
"{",
"throw",
"exception",
";",
"}",
"catch",
"(",
"Exception",
"exception",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Could not register class file transformer\"",
",",
"exception",
")",
";",
"}",
"}"
] | Registers a class file transformer together with a factory for creating a lambda expression. It is possible to call this method independently
of the class loader's context as the supplied injector makes sure that the manipulated collection is the one that is held by the system class
loader.
@param classFileTransformer The class file transformer to register.
@param classFileFactory The lambda class file factory to use. This factory must define a visible instance method with the signature
{@code byte[] make(Object, String, Object, Object, Object, Object, boolean, List, List, Collection}. The arguments provided
are the invokedynamic call site's lookup object, the lambda method's name, the factory method's type, the lambda method's
type, the target method's handle, the specialized method type of the lambda expression, a boolean to indicate
serializability, a list of marker interfaces, a list of additional bridges and a collection of class file transformers to
apply.
@return {@code true} if this is the first registered transformer. This indicates that the {@code LambdaMetafactory} must be instrumented to delegate
to this alternative factory. | [
"Registers",
"a",
"class",
"file",
"transformer",
"together",
"with",
"a",
"factory",
"for",
"creating",
"a",
"lambda",
"expression",
".",
"It",
"is",
"possible",
"to",
"call",
"this",
"method",
"independently",
"of",
"the",
"class",
"loader",
"s",
"context",
"as",
"the",
"supplied",
"injector",
"makes",
"sure",
"that",
"the",
"manipulated",
"collection",
"is",
"the",
"one",
"that",
"is",
"held",
"by",
"the",
"system",
"class",
"loader",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/agent/builder/LambdaFactory.java#L89-L124 |
22,808 | raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/agent/builder/LambdaFactory.java | LambdaFactory.release | @SuppressWarnings("all")
public static boolean release(ClassFileTransformer classFileTransformer) {
try {
@SuppressWarnings("unchecked")
Map<ClassFileTransformer, ?> classFileTransformers = (Map<ClassFileTransformer, ?>) ClassLoader.getSystemClassLoader()
.loadClass(LambdaFactory.class.getName())
.getField(FIELD_NAME)
.get(null);
synchronized (classFileTransformers) {
return classFileTransformers.remove(classFileTransformer) != null && classFileTransformers.isEmpty();
}
} catch (RuntimeException exception) {
throw exception;
} catch (Exception exception) {
throw new IllegalStateException("Could not release class file transformer", exception);
}
} | java | @SuppressWarnings("all")
public static boolean release(ClassFileTransformer classFileTransformer) {
try {
@SuppressWarnings("unchecked")
Map<ClassFileTransformer, ?> classFileTransformers = (Map<ClassFileTransformer, ?>) ClassLoader.getSystemClassLoader()
.loadClass(LambdaFactory.class.getName())
.getField(FIELD_NAME)
.get(null);
synchronized (classFileTransformers) {
return classFileTransformers.remove(classFileTransformer) != null && classFileTransformers.isEmpty();
}
} catch (RuntimeException exception) {
throw exception;
} catch (Exception exception) {
throw new IllegalStateException("Could not release class file transformer", exception);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"all\"",
")",
"public",
"static",
"boolean",
"release",
"(",
"ClassFileTransformer",
"classFileTransformer",
")",
"{",
"try",
"{",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Map",
"<",
"ClassFileTransformer",
",",
"?",
">",
"classFileTransformers",
"=",
"(",
"Map",
"<",
"ClassFileTransformer",
",",
"?",
">",
")",
"ClassLoader",
".",
"getSystemClassLoader",
"(",
")",
".",
"loadClass",
"(",
"LambdaFactory",
".",
"class",
".",
"getName",
"(",
")",
")",
".",
"getField",
"(",
"FIELD_NAME",
")",
".",
"get",
"(",
"null",
")",
";",
"synchronized",
"(",
"classFileTransformers",
")",
"{",
"return",
"classFileTransformers",
".",
"remove",
"(",
"classFileTransformer",
")",
"!=",
"null",
"&&",
"classFileTransformers",
".",
"isEmpty",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"RuntimeException",
"exception",
")",
"{",
"throw",
"exception",
";",
"}",
"catch",
"(",
"Exception",
"exception",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Could not release class file transformer\"",
",",
"exception",
")",
";",
"}",
"}"
] | Releases a class file transformer.
@param classFileTransformer The class file transformer to release.
@return {@code true} if the removed transformer was the last class file transformer registered. This indicates that the {@code LambdaMetafactory} must
be instrumented to no longer delegate to this alternative factory. | [
"Releases",
"a",
"class",
"file",
"transformer",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/agent/builder/LambdaFactory.java#L133-L149 |
22,809 | raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/agent/builder/LambdaFactory.java | LambdaFactory.invoke | private byte[] invoke(Object caller,
String invokedName,
Object invokedType,
Object samMethodType,
Object implMethod,
Object instantiatedMethodType,
boolean serializable,
List<Class<?>> markerInterfaces,
List<?> additionalBridges,
Collection<ClassFileTransformer> classFileTransformers) {
try {
return (byte[]) dispatcher.invoke(target,
caller,
invokedName,
invokedType,
samMethodType,
implMethod,
instantiatedMethodType,
serializable,
markerInterfaces,
additionalBridges,
classFileTransformers);
} catch (RuntimeException exception) {
throw exception;
} catch (Exception exception) {
throw new IllegalStateException("Cannot create class for lambda expression", exception);
}
} | java | private byte[] invoke(Object caller,
String invokedName,
Object invokedType,
Object samMethodType,
Object implMethod,
Object instantiatedMethodType,
boolean serializable,
List<Class<?>> markerInterfaces,
List<?> additionalBridges,
Collection<ClassFileTransformer> classFileTransformers) {
try {
return (byte[]) dispatcher.invoke(target,
caller,
invokedName,
invokedType,
samMethodType,
implMethod,
instantiatedMethodType,
serializable,
markerInterfaces,
additionalBridges,
classFileTransformers);
} catch (RuntimeException exception) {
throw exception;
} catch (Exception exception) {
throw new IllegalStateException("Cannot create class for lambda expression", exception);
}
} | [
"private",
"byte",
"[",
"]",
"invoke",
"(",
"Object",
"caller",
",",
"String",
"invokedName",
",",
"Object",
"invokedType",
",",
"Object",
"samMethodType",
",",
"Object",
"implMethod",
",",
"Object",
"instantiatedMethodType",
",",
"boolean",
"serializable",
",",
"List",
"<",
"Class",
"<",
"?",
">",
">",
"markerInterfaces",
",",
"List",
"<",
"?",
">",
"additionalBridges",
",",
"Collection",
"<",
"ClassFileTransformer",
">",
"classFileTransformers",
")",
"{",
"try",
"{",
"return",
"(",
"byte",
"[",
"]",
")",
"dispatcher",
".",
"invoke",
"(",
"target",
",",
"caller",
",",
"invokedName",
",",
"invokedType",
",",
"samMethodType",
",",
"implMethod",
",",
"instantiatedMethodType",
",",
"serializable",
",",
"markerInterfaces",
",",
"additionalBridges",
",",
"classFileTransformers",
")",
";",
"}",
"catch",
"(",
"RuntimeException",
"exception",
")",
"{",
"throw",
"exception",
";",
"}",
"catch",
"(",
"Exception",
"exception",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot create class for lambda expression\"",
",",
"exception",
")",
";",
"}",
"}"
] | Applies this lambda meta factory.
@param caller A lookup context representing the creating class of this lambda expression.
@param invokedName The name of the lambda expression's represented method.
@param invokedType The type of the lambda expression's factory method.
@param samMethodType The type of the lambda expression's represented method.
@param implMethod A handle representing the target of the lambda expression's method.
@param instantiatedMethodType A specialization of the type of the lambda expression's represented method.
@param serializable {@code true} if the lambda expression should be serializable.
@param markerInterfaces A list of interfaces for the lambda expression to represent.
@param additionalBridges A list of additional bridge methods to be implemented by the lambda expression.
@param classFileTransformers A collection of class file transformers to apply when creating the class.
@return A binary representation of the transformed class file. | [
"Applies",
"this",
"lambda",
"meta",
"factory",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/agent/builder/LambdaFactory.java#L166-L194 |
22,810 | raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/agent/builder/LambdaFactory.java | LambdaFactory.make | public static byte[] make(Object caller,
String invokedName,
Object invokedType,
Object samMethodType,
Object implMethod,
Object instantiatedMethodType,
boolean serializable,
List<Class<?>> markerInterfaces,
List<?> additionalBridges) {
return CLASS_FILE_TRANSFORMERS.values().iterator().next().invoke(caller,
invokedName,
invokedType,
samMethodType,
implMethod,
instantiatedMethodType,
serializable,
markerInterfaces,
additionalBridges,
CLASS_FILE_TRANSFORMERS.keySet());
} | java | public static byte[] make(Object caller,
String invokedName,
Object invokedType,
Object samMethodType,
Object implMethod,
Object instantiatedMethodType,
boolean serializable,
List<Class<?>> markerInterfaces,
List<?> additionalBridges) {
return CLASS_FILE_TRANSFORMERS.values().iterator().next().invoke(caller,
invokedName,
invokedType,
samMethodType,
implMethod,
instantiatedMethodType,
serializable,
markerInterfaces,
additionalBridges,
CLASS_FILE_TRANSFORMERS.keySet());
} | [
"public",
"static",
"byte",
"[",
"]",
"make",
"(",
"Object",
"caller",
",",
"String",
"invokedName",
",",
"Object",
"invokedType",
",",
"Object",
"samMethodType",
",",
"Object",
"implMethod",
",",
"Object",
"instantiatedMethodType",
",",
"boolean",
"serializable",
",",
"List",
"<",
"Class",
"<",
"?",
">",
">",
"markerInterfaces",
",",
"List",
"<",
"?",
">",
"additionalBridges",
")",
"{",
"return",
"CLASS_FILE_TRANSFORMERS",
".",
"values",
"(",
")",
".",
"iterator",
"(",
")",
".",
"next",
"(",
")",
".",
"invoke",
"(",
"caller",
",",
"invokedName",
",",
"invokedType",
",",
"samMethodType",
",",
"implMethod",
",",
"instantiatedMethodType",
",",
"serializable",
",",
"markerInterfaces",
",",
"additionalBridges",
",",
"CLASS_FILE_TRANSFORMERS",
".",
"keySet",
"(",
")",
")",
";",
"}"
] | Dispatches the creation of a new class representing a class file.
@param caller A lookup context representing the creating class of this lambda expression.
@param invokedName The name of the lambda expression's represented method.
@param invokedType The type of the lambda expression's factory method.
@param samMethodType The type of the lambda expression's represented method.
@param implMethod A handle representing the target of the lambda expression's method.
@param instantiatedMethodType A specialization of the type of the lambda expression's represented method.
@param serializable {@code true} if the lambda expression should be serializable.
@param markerInterfaces A list of interfaces for the lambda expression to represent.
@param additionalBridges A list of additional bridge methods to be implemented by the lambda expression.
@return A binary representation of the transformed class file. | [
"Dispatches",
"the",
"creation",
"of",
"a",
"new",
"class",
"representing",
"a",
"class",
"file",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/agent/builder/LambdaFactory.java#L210-L229 |
22,811 | raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/asm/ModifierAdjustment.java | ModifierAdjustment.withMethodModifiers | public ModifierAdjustment withMethodModifiers(ElementMatcher<? super MethodDescription> matcher,
List<? extends ModifierContributor.ForMethod> modifierContributors) {
return withInvokableModifiers(isMethod().and(matcher), modifierContributors);
} | java | public ModifierAdjustment withMethodModifiers(ElementMatcher<? super MethodDescription> matcher,
List<? extends ModifierContributor.ForMethod> modifierContributors) {
return withInvokableModifiers(isMethod().and(matcher), modifierContributors);
} | [
"public",
"ModifierAdjustment",
"withMethodModifiers",
"(",
"ElementMatcher",
"<",
"?",
"super",
"MethodDescription",
">",
"matcher",
",",
"List",
"<",
"?",
"extends",
"ModifierContributor",
".",
"ForMethod",
">",
"modifierContributors",
")",
"{",
"return",
"withInvokableModifiers",
"(",
"isMethod",
"(",
")",
".",
"and",
"(",
"matcher",
")",
",",
"modifierContributors",
")",
";",
"}"
] | Adjusts a method's modifiers if it fulfills the supplied matcher.
@param matcher The matcher that determines if a method's modifiers should be adjusted.
@param modifierContributors The modifier contributors to enforce.
@return A new modifier adjustment that enforces the given modifier contributors and any previous adjustments. | [
"Adjusts",
"a",
"method",
"s",
"modifiers",
"if",
"it",
"fulfills",
"the",
"supplied",
"matcher",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/asm/ModifierAdjustment.java#L221-L224 |
22,812 | raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/asm/ModifierAdjustment.java | ModifierAdjustment.withInvokableModifiers | public ModifierAdjustment withInvokableModifiers(ElementMatcher<? super MethodDescription> matcher,
List<? extends ModifierContributor.ForMethod> modifierContributors) {
return new ModifierAdjustment(typeAdjustments, fieldAdjustments, CompoundList.of(new Adjustment<MethodDescription>(matcher,
ModifierContributor.Resolver.of(modifierContributors)), methodAdjustments));
} | java | public ModifierAdjustment withInvokableModifiers(ElementMatcher<? super MethodDescription> matcher,
List<? extends ModifierContributor.ForMethod> modifierContributors) {
return new ModifierAdjustment(typeAdjustments, fieldAdjustments, CompoundList.of(new Adjustment<MethodDescription>(matcher,
ModifierContributor.Resolver.of(modifierContributors)), methodAdjustments));
} | [
"public",
"ModifierAdjustment",
"withInvokableModifiers",
"(",
"ElementMatcher",
"<",
"?",
"super",
"MethodDescription",
">",
"matcher",
",",
"List",
"<",
"?",
"extends",
"ModifierContributor",
".",
"ForMethod",
">",
"modifierContributors",
")",
"{",
"return",
"new",
"ModifierAdjustment",
"(",
"typeAdjustments",
",",
"fieldAdjustments",
",",
"CompoundList",
".",
"of",
"(",
"new",
"Adjustment",
"<",
"MethodDescription",
">",
"(",
"matcher",
",",
"ModifierContributor",
".",
"Resolver",
".",
"of",
"(",
"modifierContributors",
")",
")",
",",
"methodAdjustments",
")",
")",
";",
"}"
] | Adjusts a method's or constructor's modifiers if it fulfills the supplied matcher.
@param matcher The matcher that determines if a method's or constructor's modifiers should be adjusted.
@param modifierContributors The modifier contributors to enforce.
@return A new modifier adjustment that enforces the given modifier contributors and any previous adjustments. | [
"Adjusts",
"a",
"method",
"s",
"or",
"constructor",
"s",
"modifiers",
"if",
"it",
"fulfills",
"the",
"supplied",
"matcher",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/asm/ModifierAdjustment.java#L309-L313 |
22,813 | raphw/byte-buddy | byte-buddy-maven-plugin/src/main/java/net/bytebuddy/build/maven/ClassLoaderResolver.java | ClassLoaderResolver.resolve | public ClassLoader resolve(MavenCoordinate mavenCoordinate) throws MojoFailureException, MojoExecutionException {
ClassLoader classLoader = classLoaders.get(mavenCoordinate);
if (classLoader == null) {
classLoader = doResolve(mavenCoordinate);
classLoaders.put(mavenCoordinate, classLoader);
}
return classLoader;
} | java | public ClassLoader resolve(MavenCoordinate mavenCoordinate) throws MojoFailureException, MojoExecutionException {
ClassLoader classLoader = classLoaders.get(mavenCoordinate);
if (classLoader == null) {
classLoader = doResolve(mavenCoordinate);
classLoaders.put(mavenCoordinate, classLoader);
}
return classLoader;
} | [
"public",
"ClassLoader",
"resolve",
"(",
"MavenCoordinate",
"mavenCoordinate",
")",
"throws",
"MojoFailureException",
",",
"MojoExecutionException",
"{",
"ClassLoader",
"classLoader",
"=",
"classLoaders",
".",
"get",
"(",
"mavenCoordinate",
")",
";",
"if",
"(",
"classLoader",
"==",
"null",
")",
"{",
"classLoader",
"=",
"doResolve",
"(",
"mavenCoordinate",
")",
";",
"classLoaders",
".",
"put",
"(",
"mavenCoordinate",
",",
"classLoader",
")",
";",
"}",
"return",
"classLoader",
";",
"}"
] | Resolves a Maven coordinate to a class loader that can load all of the coordinates classes. If a Maven coordinate was resolved previously,
the previously created class loader is returned.
@param mavenCoordinate The Maven coordinate to resolve.
@return A class loader that references all of the class loader's dependencies and which is a child of this class's class loader.
@throws MojoExecutionException If the user configuration results in an error.
@throws MojoFailureException If the plugin application raises an error. | [
"Resolves",
"a",
"Maven",
"coordinate",
"to",
"a",
"class",
"loader",
"that",
"can",
"load",
"all",
"of",
"the",
"coordinates",
"classes",
".",
"If",
"a",
"Maven",
"coordinate",
"was",
"resolved",
"previously",
"the",
"previously",
"created",
"class",
"loader",
"is",
"returned",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-maven-plugin/src/main/java/net/bytebuddy/build/maven/ClassLoaderResolver.java#L100-L107 |
22,814 | raphw/byte-buddy | byte-buddy-maven-plugin/src/main/java/net/bytebuddy/build/maven/ClassLoaderResolver.java | ClassLoaderResolver.doResolve | private ClassLoader doResolve(MavenCoordinate mavenCoordinate) throws MojoExecutionException, MojoFailureException {
List<URL> urls = new ArrayList<URL>();
log.info("Resolving transformer dependency: " + mavenCoordinate);
try {
DependencyNode root = repositorySystem.collectDependencies(repositorySystemSession, new CollectRequest(new Dependency(mavenCoordinate.asArtifact(), "runtime"), remoteRepositories)).getRoot();
repositorySystem.resolveDependencies(repositorySystemSession, new DependencyRequest().setRoot(root));
PreorderNodeListGenerator preorderNodeListGenerator = new PreorderNodeListGenerator();
root.accept(preorderNodeListGenerator);
for (Artifact artifact : preorderNodeListGenerator.getArtifacts(false)) {
urls.add(artifact.getFile().toURI().toURL());
}
} catch (DependencyCollectionException exception) {
throw new MojoExecutionException("Could not collect dependencies for " + mavenCoordinate, exception);
} catch (DependencyResolutionException exception) {
throw new MojoExecutionException("Could not resolve dependencies for " + mavenCoordinate, exception);
} catch (MalformedURLException exception) {
throw new MojoFailureException("Could not resolve file as URL for " + mavenCoordinate, exception);
}
return new URLClassLoader(urls.toArray(new URL[0]), ByteBuddy.class.getClassLoader());
} | java | private ClassLoader doResolve(MavenCoordinate mavenCoordinate) throws MojoExecutionException, MojoFailureException {
List<URL> urls = new ArrayList<URL>();
log.info("Resolving transformer dependency: " + mavenCoordinate);
try {
DependencyNode root = repositorySystem.collectDependencies(repositorySystemSession, new CollectRequest(new Dependency(mavenCoordinate.asArtifact(), "runtime"), remoteRepositories)).getRoot();
repositorySystem.resolveDependencies(repositorySystemSession, new DependencyRequest().setRoot(root));
PreorderNodeListGenerator preorderNodeListGenerator = new PreorderNodeListGenerator();
root.accept(preorderNodeListGenerator);
for (Artifact artifact : preorderNodeListGenerator.getArtifacts(false)) {
urls.add(artifact.getFile().toURI().toURL());
}
} catch (DependencyCollectionException exception) {
throw new MojoExecutionException("Could not collect dependencies for " + mavenCoordinate, exception);
} catch (DependencyResolutionException exception) {
throw new MojoExecutionException("Could not resolve dependencies for " + mavenCoordinate, exception);
} catch (MalformedURLException exception) {
throw new MojoFailureException("Could not resolve file as URL for " + mavenCoordinate, exception);
}
return new URLClassLoader(urls.toArray(new URL[0]), ByteBuddy.class.getClassLoader());
} | [
"private",
"ClassLoader",
"doResolve",
"(",
"MavenCoordinate",
"mavenCoordinate",
")",
"throws",
"MojoExecutionException",
",",
"MojoFailureException",
"{",
"List",
"<",
"URL",
">",
"urls",
"=",
"new",
"ArrayList",
"<",
"URL",
">",
"(",
")",
";",
"log",
".",
"info",
"(",
"\"Resolving transformer dependency: \"",
"+",
"mavenCoordinate",
")",
";",
"try",
"{",
"DependencyNode",
"root",
"=",
"repositorySystem",
".",
"collectDependencies",
"(",
"repositorySystemSession",
",",
"new",
"CollectRequest",
"(",
"new",
"Dependency",
"(",
"mavenCoordinate",
".",
"asArtifact",
"(",
")",
",",
"\"runtime\"",
")",
",",
"remoteRepositories",
")",
")",
".",
"getRoot",
"(",
")",
";",
"repositorySystem",
".",
"resolveDependencies",
"(",
"repositorySystemSession",
",",
"new",
"DependencyRequest",
"(",
")",
".",
"setRoot",
"(",
"root",
")",
")",
";",
"PreorderNodeListGenerator",
"preorderNodeListGenerator",
"=",
"new",
"PreorderNodeListGenerator",
"(",
")",
";",
"root",
".",
"accept",
"(",
"preorderNodeListGenerator",
")",
";",
"for",
"(",
"Artifact",
"artifact",
":",
"preorderNodeListGenerator",
".",
"getArtifacts",
"(",
"false",
")",
")",
"{",
"urls",
".",
"add",
"(",
"artifact",
".",
"getFile",
"(",
")",
".",
"toURI",
"(",
")",
".",
"toURL",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"DependencyCollectionException",
"exception",
")",
"{",
"throw",
"new",
"MojoExecutionException",
"(",
"\"Could not collect dependencies for \"",
"+",
"mavenCoordinate",
",",
"exception",
")",
";",
"}",
"catch",
"(",
"DependencyResolutionException",
"exception",
")",
"{",
"throw",
"new",
"MojoExecutionException",
"(",
"\"Could not resolve dependencies for \"",
"+",
"mavenCoordinate",
",",
"exception",
")",
";",
"}",
"catch",
"(",
"MalformedURLException",
"exception",
")",
"{",
"throw",
"new",
"MojoFailureException",
"(",
"\"Could not resolve file as URL for \"",
"+",
"mavenCoordinate",
",",
"exception",
")",
";",
"}",
"return",
"new",
"URLClassLoader",
"(",
"urls",
".",
"toArray",
"(",
"new",
"URL",
"[",
"0",
"]",
")",
",",
"ByteBuddy",
".",
"class",
".",
"getClassLoader",
"(",
")",
")",
";",
"}"
] | Resolves a Maven coordinate to a class loader that can load all of the coordinates classes.
@param mavenCoordinate The Maven coordinate to resolve.
@return A class loader that references all of the class loader's dependencies and which is a child of this class's class loader.
@throws MojoExecutionException If the user configuration results in an error.
@throws MojoFailureException If the plugin application raises an error. | [
"Resolves",
"a",
"Maven",
"coordinate",
"to",
"a",
"class",
"loader",
"that",
"can",
"load",
"all",
"of",
"the",
"coordinates",
"classes",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-maven-plugin/src/main/java/net/bytebuddy/build/maven/ClassLoaderResolver.java#L117-L136 |
22,815 | raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/loading/ByteArrayClassLoader.java | ByteArrayClassLoader.load | public static Map<TypeDescription, Class<?>> load(ClassLoader classLoader, Map<TypeDescription, byte[]> types) {
return load(classLoader,
types,
ClassLoadingStrategy.NO_PROTECTION_DOMAIN,
PersistenceHandler.LATENT,
PackageDefinitionStrategy.Trivial.INSTANCE,
false,
true);
} | java | public static Map<TypeDescription, Class<?>> load(ClassLoader classLoader, Map<TypeDescription, byte[]> types) {
return load(classLoader,
types,
ClassLoadingStrategy.NO_PROTECTION_DOMAIN,
PersistenceHandler.LATENT,
PackageDefinitionStrategy.Trivial.INSTANCE,
false,
true);
} | [
"public",
"static",
"Map",
"<",
"TypeDescription",
",",
"Class",
"<",
"?",
">",
">",
"load",
"(",
"ClassLoader",
"classLoader",
",",
"Map",
"<",
"TypeDescription",
",",
"byte",
"[",
"]",
">",
"types",
")",
"{",
"return",
"load",
"(",
"classLoader",
",",
"types",
",",
"ClassLoadingStrategy",
".",
"NO_PROTECTION_DOMAIN",
",",
"PersistenceHandler",
".",
"LATENT",
",",
"PackageDefinitionStrategy",
".",
"Trivial",
".",
"INSTANCE",
",",
"false",
",",
"true",
")",
";",
"}"
] | Loads a given set of class descriptions and their binary representations.
@param classLoader The parent class loader.
@param types The unloaded types to be loaded.
@return A map of the given type descriptions pointing to their loaded representations. | [
"Loads",
"a",
"given",
"set",
"of",
"class",
"descriptions",
"and",
"their",
"binary",
"representations",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/loading/ByteArrayClassLoader.java#L261-L269 |
22,816 | raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/loading/ByteArrayClassLoader.java | ChildFirst.load | @SuppressFBWarnings(value = "DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED", justification = "Privilege is explicit user responsibility")
public static Map<TypeDescription, Class<?>> load(ClassLoader classLoader,
Map<TypeDescription, byte[]> types,
ProtectionDomain protectionDomain,
PersistenceHandler persistenceHandler,
PackageDefinitionStrategy packageDefinitionStrategy,
boolean forbidExisting,
boolean sealed) {
Map<String, byte[]> typesByName = new HashMap<String, byte[]>();
for (Map.Entry<TypeDescription, byte[]> entry : types.entrySet()) {
typesByName.put(entry.getKey().getName(), entry.getValue());
}
classLoader = new ChildFirst(classLoader,
sealed,
typesByName,
protectionDomain,
persistenceHandler,
packageDefinitionStrategy,
NoOpClassFileTransformer.INSTANCE);
Map<TypeDescription, Class<?>> result = new LinkedHashMap<TypeDescription, Class<?>>();
for (TypeDescription typeDescription : types.keySet()) {
try {
Class<?> type = Class.forName(typeDescription.getName(), false, classLoader);
if (forbidExisting && type.getClassLoader() != classLoader) {
throw new IllegalStateException("Class already loaded: " + type);
}
result.put(typeDescription, type);
} catch (ClassNotFoundException exception) {
throw new IllegalStateException("Cannot load class " + typeDescription, exception);
}
}
return result;
} | java | @SuppressFBWarnings(value = "DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED", justification = "Privilege is explicit user responsibility")
public static Map<TypeDescription, Class<?>> load(ClassLoader classLoader,
Map<TypeDescription, byte[]> types,
ProtectionDomain protectionDomain,
PersistenceHandler persistenceHandler,
PackageDefinitionStrategy packageDefinitionStrategy,
boolean forbidExisting,
boolean sealed) {
Map<String, byte[]> typesByName = new HashMap<String, byte[]>();
for (Map.Entry<TypeDescription, byte[]> entry : types.entrySet()) {
typesByName.put(entry.getKey().getName(), entry.getValue());
}
classLoader = new ChildFirst(classLoader,
sealed,
typesByName,
protectionDomain,
persistenceHandler,
packageDefinitionStrategy,
NoOpClassFileTransformer.INSTANCE);
Map<TypeDescription, Class<?>> result = new LinkedHashMap<TypeDescription, Class<?>>();
for (TypeDescription typeDescription : types.keySet()) {
try {
Class<?> type = Class.forName(typeDescription.getName(), false, classLoader);
if (forbidExisting && type.getClassLoader() != classLoader) {
throw new IllegalStateException("Class already loaded: " + type);
}
result.put(typeDescription, type);
} catch (ClassNotFoundException exception) {
throw new IllegalStateException("Cannot load class " + typeDescription, exception);
}
}
return result;
} | [
"@",
"SuppressFBWarnings",
"(",
"value",
"=",
"\"DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED\"",
",",
"justification",
"=",
"\"Privilege is explicit user responsibility\"",
")",
"public",
"static",
"Map",
"<",
"TypeDescription",
",",
"Class",
"<",
"?",
">",
">",
"load",
"(",
"ClassLoader",
"classLoader",
",",
"Map",
"<",
"TypeDescription",
",",
"byte",
"[",
"]",
">",
"types",
",",
"ProtectionDomain",
"protectionDomain",
",",
"PersistenceHandler",
"persistenceHandler",
",",
"PackageDefinitionStrategy",
"packageDefinitionStrategy",
",",
"boolean",
"forbidExisting",
",",
"boolean",
"sealed",
")",
"{",
"Map",
"<",
"String",
",",
"byte",
"[",
"]",
">",
"typesByName",
"=",
"new",
"HashMap",
"<",
"String",
",",
"byte",
"[",
"]",
">",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"TypeDescription",
",",
"byte",
"[",
"]",
">",
"entry",
":",
"types",
".",
"entrySet",
"(",
")",
")",
"{",
"typesByName",
".",
"put",
"(",
"entry",
".",
"getKey",
"(",
")",
".",
"getName",
"(",
")",
",",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"classLoader",
"=",
"new",
"ChildFirst",
"(",
"classLoader",
",",
"sealed",
",",
"typesByName",
",",
"protectionDomain",
",",
"persistenceHandler",
",",
"packageDefinitionStrategy",
",",
"NoOpClassFileTransformer",
".",
"INSTANCE",
")",
";",
"Map",
"<",
"TypeDescription",
",",
"Class",
"<",
"?",
">",
">",
"result",
"=",
"new",
"LinkedHashMap",
"<",
"TypeDescription",
",",
"Class",
"<",
"?",
">",
">",
"(",
")",
";",
"for",
"(",
"TypeDescription",
"typeDescription",
":",
"types",
".",
"keySet",
"(",
")",
")",
"{",
"try",
"{",
"Class",
"<",
"?",
">",
"type",
"=",
"Class",
".",
"forName",
"(",
"typeDescription",
".",
"getName",
"(",
")",
",",
"false",
",",
"classLoader",
")",
";",
"if",
"(",
"forbidExisting",
"&&",
"type",
".",
"getClassLoader",
"(",
")",
"!=",
"classLoader",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Class already loaded: \"",
"+",
"type",
")",
";",
"}",
"result",
".",
"put",
"(",
"typeDescription",
",",
"type",
")",
";",
"}",
"catch",
"(",
"ClassNotFoundException",
"exception",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot load class \"",
"+",
"typeDescription",
",",
"exception",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] | Loads a given set of class descriptions and their binary representations using a child-first class loader.
@param classLoader The parent class loader.
@param types The unloaded types to be loaded.
@param protectionDomain The protection domain to apply where {@code null} references an implicit protection domain.
@param persistenceHandler The persistence handler of the created class loader.
@param packageDefinitionStrategy The package definer to be queried for package definitions.
@param forbidExisting {@code true} if the class loading should throw an exception if a class was already loaded by a parent class loader.
@param sealed {@code true} if the class loader should be sealed.
@return A map of the given type descriptions pointing to their loaded representations. | [
"Loads",
"a",
"given",
"set",
"of",
"class",
"descriptions",
"and",
"their",
"binary",
"representations",
"using",
"a",
"child",
"-",
"first",
"class",
"loader",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/loading/ByteArrayClassLoader.java#L1134-L1166 |
22,817 | raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/loading/ByteArrayClassLoader.java | ChildFirst.isShadowed | private boolean isShadowed(String resourceName) {
if (persistenceHandler.isManifest() || !resourceName.endsWith(CLASS_FILE_SUFFIX)) {
return false;
}
// This synchronization is required to avoid a racing condition to the actual class loading.
synchronized (this) {
String typeName = resourceName.replace('/', '.').substring(0, resourceName.length() - CLASS_FILE_SUFFIX.length());
if (typeDefinitions.containsKey(typeName)) {
return true;
}
Class<?> loadedClass = findLoadedClass(typeName);
return loadedClass != null && loadedClass.getClassLoader() == this;
}
} | java | private boolean isShadowed(String resourceName) {
if (persistenceHandler.isManifest() || !resourceName.endsWith(CLASS_FILE_SUFFIX)) {
return false;
}
// This synchronization is required to avoid a racing condition to the actual class loading.
synchronized (this) {
String typeName = resourceName.replace('/', '.').substring(0, resourceName.length() - CLASS_FILE_SUFFIX.length());
if (typeDefinitions.containsKey(typeName)) {
return true;
}
Class<?> loadedClass = findLoadedClass(typeName);
return loadedClass != null && loadedClass.getClassLoader() == this;
}
} | [
"private",
"boolean",
"isShadowed",
"(",
"String",
"resourceName",
")",
"{",
"if",
"(",
"persistenceHandler",
".",
"isManifest",
"(",
")",
"||",
"!",
"resourceName",
".",
"endsWith",
"(",
"CLASS_FILE_SUFFIX",
")",
")",
"{",
"return",
"false",
";",
"}",
"// This synchronization is required to avoid a racing condition to the actual class loading.",
"synchronized",
"(",
"this",
")",
"{",
"String",
"typeName",
"=",
"resourceName",
".",
"replace",
"(",
"'",
"'",
",",
"'",
"'",
")",
".",
"substring",
"(",
"0",
",",
"resourceName",
".",
"length",
"(",
")",
"-",
"CLASS_FILE_SUFFIX",
".",
"length",
"(",
")",
")",
";",
"if",
"(",
"typeDefinitions",
".",
"containsKey",
"(",
"typeName",
")",
")",
"{",
"return",
"true",
";",
"}",
"Class",
"<",
"?",
">",
"loadedClass",
"=",
"findLoadedClass",
"(",
"typeName",
")",
";",
"return",
"loadedClass",
"!=",
"null",
"&&",
"loadedClass",
".",
"getClassLoader",
"(",
")",
"==",
"this",
";",
"}",
"}"
] | Checks if a resource name represents a class file of a class that was loaded by this class loader.
@param resourceName The resource name of the class to be exposed as its class file.
@return {@code true} if this class represents a class that is being loaded by this class loader. | [
"Checks",
"if",
"a",
"resource",
"name",
"represents",
"a",
"class",
"file",
"of",
"a",
"class",
"that",
"was",
"loaded",
"by",
"this",
"class",
"loader",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/dynamic/loading/ByteArrayClassLoader.java#L1221-L1234 |
22,818 | raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodDelegation.java | MethodDelegation.toMethodReturnOf | public static MethodDelegation toMethodReturnOf(String name, MethodGraph.Compiler methodGraphCompiler) {
return withDefaultConfiguration().toMethodReturnOf(name, methodGraphCompiler);
} | java | public static MethodDelegation toMethodReturnOf(String name, MethodGraph.Compiler methodGraphCompiler) {
return withDefaultConfiguration().toMethodReturnOf(name, methodGraphCompiler);
} | [
"public",
"static",
"MethodDelegation",
"toMethodReturnOf",
"(",
"String",
"name",
",",
"MethodGraph",
".",
"Compiler",
"methodGraphCompiler",
")",
"{",
"return",
"withDefaultConfiguration",
"(",
")",
".",
"toMethodReturnOf",
"(",
"name",
",",
"methodGraphCompiler",
")",
";",
"}"
] | Delegates any intercepted method to invoke a method on an instance that is returned by a parameterless method of the
given name. To be considered a valid delegation target, a method must be visible and accessible to the instrumented type.
This is the case if the method's declaring type is either public or in the same package as the instrumented type and if
the method is either public or non-private and in the same package as the instrumented type. Private methods can only
be used as a delegation target if the delegation is targeting the instrumented type.
@param name The name of the method that returns the delegation target.
@param methodGraphCompiler The method graph compiler to use.
@return A delegation that redirects invocations to the return value of a method that is declared by the instrumented type. | [
"Delegates",
"any",
"intercepted",
"method",
"to",
"invoke",
"a",
"method",
"on",
"an",
"instance",
"that",
"is",
"returned",
"by",
"a",
"parameterless",
"method",
"of",
"the",
"given",
"name",
".",
"To",
"be",
"considered",
"a",
"valid",
"delegation",
"target",
"a",
"method",
"must",
"be",
"visible",
"and",
"accessible",
"to",
"the",
"instrumented",
"type",
".",
"This",
"is",
"the",
"case",
"if",
"the",
"method",
"s",
"declaring",
"type",
"is",
"either",
"public",
"or",
"in",
"the",
"same",
"package",
"as",
"the",
"instrumented",
"type",
"and",
"if",
"the",
"method",
"is",
"either",
"public",
"or",
"non",
"-",
"private",
"and",
"in",
"the",
"same",
"package",
"as",
"the",
"instrumented",
"type",
".",
"Private",
"methods",
"can",
"only",
"be",
"used",
"as",
"a",
"delegation",
"target",
"if",
"the",
"delegation",
"is",
"targeting",
"the",
"instrumented",
"type",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodDelegation.java#L525-L527 |
22,819 | raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodDelegation.java | MethodDelegation.withAssigner | public Implementation.Composable withAssigner(Assigner assigner) {
return new MethodDelegation(implementationDelegate,
parameterBinders,
ambiguityResolver,
terminationHandler,
bindingResolver,
assigner);
} | java | public Implementation.Composable withAssigner(Assigner assigner) {
return new MethodDelegation(implementationDelegate,
parameterBinders,
ambiguityResolver,
terminationHandler,
bindingResolver,
assigner);
} | [
"public",
"Implementation",
".",
"Composable",
"withAssigner",
"(",
"Assigner",
"assigner",
")",
"{",
"return",
"new",
"MethodDelegation",
"(",
"implementationDelegate",
",",
"parameterBinders",
",",
"ambiguityResolver",
",",
"terminationHandler",
",",
"bindingResolver",
",",
"assigner",
")",
";",
"}"
] | Applies an assigner to the method delegation that is used for assigning method return and parameter types.
@param assigner The assigner to apply.
@return A method delegation implementation that makes use of the given designer. | [
"Applies",
"an",
"assigner",
"to",
"the",
"method",
"delegation",
"that",
"is",
"used",
"for",
"assigning",
"method",
"return",
"and",
"parameter",
"types",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodDelegation.java#L557-L564 |
22,820 | raphw/byte-buddy | byte-buddy-benchmark/src/main/java/net/bytebuddy/benchmark/runner/QuickRunner.java | QuickRunner.main | public static void main(String[] args) throws RunnerException {
new Runner(new OptionsBuilder()
.include(WILDCARD + SuperClassInvocationBenchmark.class.getSimpleName() + WILDCARD)
.include(WILDCARD + StubInvocationBenchmark.class.getSimpleName() + WILDCARD)
.include(WILDCARD + ClassByImplementationBenchmark.class.getSimpleName() + WILDCARD)
.include(WILDCARD + ClassByExtensionBenchmark.class.getSimpleName() + WILDCARD)
.include(WILDCARD + TrivialClassCreationBenchmark.class.getSimpleName() + WILDCARD)
.forks(0) // Should rather be 1 but there seems to be a bug in JMH.
.build()).run();
} | java | public static void main(String[] args) throws RunnerException {
new Runner(new OptionsBuilder()
.include(WILDCARD + SuperClassInvocationBenchmark.class.getSimpleName() + WILDCARD)
.include(WILDCARD + StubInvocationBenchmark.class.getSimpleName() + WILDCARD)
.include(WILDCARD + ClassByImplementationBenchmark.class.getSimpleName() + WILDCARD)
.include(WILDCARD + ClassByExtensionBenchmark.class.getSimpleName() + WILDCARD)
.include(WILDCARD + TrivialClassCreationBenchmark.class.getSimpleName() + WILDCARD)
.forks(0) // Should rather be 1 but there seems to be a bug in JMH.
.build()).run();
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"throws",
"RunnerException",
"{",
"new",
"Runner",
"(",
"new",
"OptionsBuilder",
"(",
")",
".",
"include",
"(",
"WILDCARD",
"+",
"SuperClassInvocationBenchmark",
".",
"class",
".",
"getSimpleName",
"(",
")",
"+",
"WILDCARD",
")",
".",
"include",
"(",
"WILDCARD",
"+",
"StubInvocationBenchmark",
".",
"class",
".",
"getSimpleName",
"(",
")",
"+",
"WILDCARD",
")",
".",
"include",
"(",
"WILDCARD",
"+",
"ClassByImplementationBenchmark",
".",
"class",
".",
"getSimpleName",
"(",
")",
"+",
"WILDCARD",
")",
".",
"include",
"(",
"WILDCARD",
"+",
"ClassByExtensionBenchmark",
".",
"class",
".",
"getSimpleName",
"(",
")",
"+",
"WILDCARD",
")",
".",
"include",
"(",
"WILDCARD",
"+",
"TrivialClassCreationBenchmark",
".",
"class",
".",
"getSimpleName",
"(",
")",
"+",
"WILDCARD",
")",
".",
"forks",
"(",
"0",
")",
"// Should rather be 1 but there seems to be a bug in JMH.",
".",
"build",
"(",
")",
")",
".",
"run",
"(",
")",
";",
"}"
] | Executes the benchmark.
@param args Unused arguments.
@throws RunnerException If the benchmark causes an exception. | [
"Executes",
"the",
"benchmark",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-benchmark/src/main/java/net/bytebuddy/benchmark/runner/QuickRunner.java#L48-L57 |
22,821 | raphw/byte-buddy | byte-buddy-gradle-plugin/src/main/java/net/bytebuddy/build/gradle/PostCompilationAction.java | PostCompilationAction.of | public static Action<AbstractCompile> of(Project project) {
return new PostCompilationAction(project, project.getExtensions().create("byteBuddy", ByteBuddyExtension.class, project));
} | java | public static Action<AbstractCompile> of(Project project) {
return new PostCompilationAction(project, project.getExtensions().create("byteBuddy", ByteBuddyExtension.class, project));
} | [
"public",
"static",
"Action",
"<",
"AbstractCompile",
">",
"of",
"(",
"Project",
"project",
")",
"{",
"return",
"new",
"PostCompilationAction",
"(",
"project",
",",
"project",
".",
"getExtensions",
"(",
")",
".",
"create",
"(",
"\"byteBuddy\"",
",",
"ByteBuddyExtension",
".",
"class",
",",
"project",
")",
")",
";",
"}"
] | Creates a post compilation action.
@param project The project to apply the action upon.
@return An appropriate action. | [
"Creates",
"a",
"post",
"compilation",
"action",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-gradle-plugin/src/main/java/net/bytebuddy/build/gradle/PostCompilationAction.java#L54-L56 |
22,822 | raphw/byte-buddy | byte-buddy-gradle-plugin/src/main/java/net/bytebuddy/build/gradle/ClassLoaderResolver.java | ClassLoaderResolver.doResolve | private ClassLoader doResolve(Set<? extends File> classPath) {
List<URL> urls = new ArrayList<URL>(classPath.size());
for (File file : classPath) {
try {
urls.add(file.toURI().toURL());
} catch (MalformedURLException exception) {
throw new GradleException("Cannot resolve " + file + " as URL", exception);
}
}
return new URLClassLoader(urls.toArray(new URL[0]), ByteBuddy.class.getClassLoader());
} | java | private ClassLoader doResolve(Set<? extends File> classPath) {
List<URL> urls = new ArrayList<URL>(classPath.size());
for (File file : classPath) {
try {
urls.add(file.toURI().toURL());
} catch (MalformedURLException exception) {
throw new GradleException("Cannot resolve " + file + " as URL", exception);
}
}
return new URLClassLoader(urls.toArray(new URL[0]), ByteBuddy.class.getClassLoader());
} | [
"private",
"ClassLoader",
"doResolve",
"(",
"Set",
"<",
"?",
"extends",
"File",
">",
"classPath",
")",
"{",
"List",
"<",
"URL",
">",
"urls",
"=",
"new",
"ArrayList",
"<",
"URL",
">",
"(",
"classPath",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"File",
"file",
":",
"classPath",
")",
"{",
"try",
"{",
"urls",
".",
"add",
"(",
"file",
".",
"toURI",
"(",
")",
".",
"toURL",
"(",
")",
")",
";",
"}",
"catch",
"(",
"MalformedURLException",
"exception",
")",
"{",
"throw",
"new",
"GradleException",
"(",
"\"Cannot resolve \"",
"+",
"file",
"+",
"\" as URL\"",
",",
"exception",
")",
";",
"}",
"}",
"return",
"new",
"URLClassLoader",
"(",
"urls",
".",
"toArray",
"(",
"new",
"URL",
"[",
"0",
"]",
")",
",",
"ByteBuddy",
".",
"class",
".",
"getClassLoader",
"(",
")",
")",
";",
"}"
] | Resolves a class path to a class loader.
@param classPath The class path to consider.
@return A class loader for the supplied class path. | [
"Resolves",
"a",
"class",
"path",
"to",
"a",
"class",
"loader",
"."
] | 4d2dac80efb6bed89367567260f6811c2f712d12 | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-gradle-plugin/src/main/java/net/bytebuddy/build/gradle/ClassLoaderResolver.java#L88-L98 |
22,823 | graknlabs/grakn | server/src/graql/gremlin/spanningtree/ChuLiuEdmonds.java | ChuLiuEdmonds.getMaxArborescence | public static Weighted<Arborescence<Node>> getMaxArborescence(WeightedGraph graph, Node root) {
// remove all edges incoming to `root`. resulting arborescence is then forced to be rooted at `root`.
return getMaxArborescence(graph.filterEdges(not(DirectedEdge.hasDestination(root))));
} | java | public static Weighted<Arborescence<Node>> getMaxArborescence(WeightedGraph graph, Node root) {
// remove all edges incoming to `root`. resulting arborescence is then forced to be rooted at `root`.
return getMaxArborescence(graph.filterEdges(not(DirectedEdge.hasDestination(root))));
} | [
"public",
"static",
"Weighted",
"<",
"Arborescence",
"<",
"Node",
">",
">",
"getMaxArborescence",
"(",
"WeightedGraph",
"graph",
",",
"Node",
"root",
")",
"{",
"// remove all edges incoming to `root`. resulting arborescence is then forced to be rooted at `root`.",
"return",
"getMaxArborescence",
"(",
"graph",
".",
"filterEdges",
"(",
"not",
"(",
"DirectedEdge",
".",
"hasDestination",
"(",
"root",
")",
")",
")",
")",
";",
"}"
] | Find an optimal arborescence of the given graph `graph`, rooted in the given node `root`. | [
"Find",
"an",
"optimal",
"arborescence",
"of",
"the",
"given",
"graph",
"graph",
"rooted",
"in",
"the",
"given",
"node",
"root",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/gremlin/spanningtree/ChuLiuEdmonds.java#L217-L220 |
22,824 | graknlabs/grakn | server/src/graql/gremlin/spanningtree/ChuLiuEdmonds.java | ChuLiuEdmonds.getMaxArborescence | public static Weighted<Arborescence<Node>> getMaxArborescence(WeightedGraph graph) {
final PartialSolution partialSolution =
PartialSolution.initialize(graph.filterEdges(not(DirectedEdge.isAutoCycle())));
// In the beginning, subgraph has no edges, so no SCC has in-edges.
final Deque<Node> componentsWithNoInEdges = new ArrayDeque<>(partialSolution.getNodes());
// Work our way through all componentsWithNoInEdges, in no particular order
while (!componentsWithNoInEdges.isEmpty()) {
final Node component = componentsWithNoInEdges.poll();
// find maximum edge entering 'component' from outside 'component'.
final Optional<ExclusiveEdge> oMaxInEdge = partialSolution.popBestEdge(component);
if (!oMaxInEdge.isPresent()) continue; // No in-edges left to consider for this component. Done with it!
final ExclusiveEdge maxInEdge = oMaxInEdge.get();
// add the new edge to subgraph, merging SCCs if necessary
final Optional<Node> newComponent = partialSolution.addEdge(maxInEdge);
if (newComponent.isPresent()) {
// addEdge created a cycle/component, which means the new component doesn't have any incoming edges
componentsWithNoInEdges.add(newComponent.get());
}
}
// Once no component has incoming edges left to consider, it's time to recover the optimal branching.
return partialSolution.recoverBestArborescence();
} | java | public static Weighted<Arborescence<Node>> getMaxArborescence(WeightedGraph graph) {
final PartialSolution partialSolution =
PartialSolution.initialize(graph.filterEdges(not(DirectedEdge.isAutoCycle())));
// In the beginning, subgraph has no edges, so no SCC has in-edges.
final Deque<Node> componentsWithNoInEdges = new ArrayDeque<>(partialSolution.getNodes());
// Work our way through all componentsWithNoInEdges, in no particular order
while (!componentsWithNoInEdges.isEmpty()) {
final Node component = componentsWithNoInEdges.poll();
// find maximum edge entering 'component' from outside 'component'.
final Optional<ExclusiveEdge> oMaxInEdge = partialSolution.popBestEdge(component);
if (!oMaxInEdge.isPresent()) continue; // No in-edges left to consider for this component. Done with it!
final ExclusiveEdge maxInEdge = oMaxInEdge.get();
// add the new edge to subgraph, merging SCCs if necessary
final Optional<Node> newComponent = partialSolution.addEdge(maxInEdge);
if (newComponent.isPresent()) {
// addEdge created a cycle/component, which means the new component doesn't have any incoming edges
componentsWithNoInEdges.add(newComponent.get());
}
}
// Once no component has incoming edges left to consider, it's time to recover the optimal branching.
return partialSolution.recoverBestArborescence();
} | [
"public",
"static",
"Weighted",
"<",
"Arborescence",
"<",
"Node",
">",
">",
"getMaxArborescence",
"(",
"WeightedGraph",
"graph",
")",
"{",
"final",
"PartialSolution",
"partialSolution",
"=",
"PartialSolution",
".",
"initialize",
"(",
"graph",
".",
"filterEdges",
"(",
"not",
"(",
"DirectedEdge",
".",
"isAutoCycle",
"(",
")",
")",
")",
")",
";",
"// In the beginning, subgraph has no edges, so no SCC has in-edges.",
"final",
"Deque",
"<",
"Node",
">",
"componentsWithNoInEdges",
"=",
"new",
"ArrayDeque",
"<>",
"(",
"partialSolution",
".",
"getNodes",
"(",
")",
")",
";",
"// Work our way through all componentsWithNoInEdges, in no particular order",
"while",
"(",
"!",
"componentsWithNoInEdges",
".",
"isEmpty",
"(",
")",
")",
"{",
"final",
"Node",
"component",
"=",
"componentsWithNoInEdges",
".",
"poll",
"(",
")",
";",
"// find maximum edge entering 'component' from outside 'component'.",
"final",
"Optional",
"<",
"ExclusiveEdge",
">",
"oMaxInEdge",
"=",
"partialSolution",
".",
"popBestEdge",
"(",
"component",
")",
";",
"if",
"(",
"!",
"oMaxInEdge",
".",
"isPresent",
"(",
")",
")",
"continue",
";",
"// No in-edges left to consider for this component. Done with it!",
"final",
"ExclusiveEdge",
"maxInEdge",
"=",
"oMaxInEdge",
".",
"get",
"(",
")",
";",
"// add the new edge to subgraph, merging SCCs if necessary",
"final",
"Optional",
"<",
"Node",
">",
"newComponent",
"=",
"partialSolution",
".",
"addEdge",
"(",
"maxInEdge",
")",
";",
"if",
"(",
"newComponent",
".",
"isPresent",
"(",
")",
")",
"{",
"// addEdge created a cycle/component, which means the new component doesn't have any incoming edges",
"componentsWithNoInEdges",
".",
"add",
"(",
"newComponent",
".",
"get",
"(",
")",
")",
";",
"}",
"}",
"// Once no component has incoming edges left to consider, it's time to recover the optimal branching.",
"return",
"partialSolution",
".",
"recoverBestArborescence",
"(",
")",
";",
"}"
] | Find an optimal arborescence of the given graph. | [
"Find",
"an",
"optimal",
"arborescence",
"of",
"the",
"given",
"graph",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/gremlin/spanningtree/ChuLiuEdmonds.java#L231-L253 |
22,825 | graknlabs/grakn | server/src/server/kb/concept/Serialiser.java | Serialiser.of | public static <DESERIALISED> Serialiser<DESERIALISED, ?> of(AttributeType.DataType<DESERIALISED> dataType) {
Serialiser<?, ?> serialiser = serialisers.get(dataType);
if (serialiser == null){
throw new UnsupportedOperationException("Unsupported DataType: " + dataType.toString());
}
return (Serialiser<DESERIALISED, ?>) serialiser;
} | java | public static <DESERIALISED> Serialiser<DESERIALISED, ?> of(AttributeType.DataType<DESERIALISED> dataType) {
Serialiser<?, ?> serialiser = serialisers.get(dataType);
if (serialiser == null){
throw new UnsupportedOperationException("Unsupported DataType: " + dataType.toString());
}
return (Serialiser<DESERIALISED, ?>) serialiser;
} | [
"public",
"static",
"<",
"DESERIALISED",
">",
"Serialiser",
"<",
"DESERIALISED",
",",
"?",
">",
"of",
"(",
"AttributeType",
".",
"DataType",
"<",
"DESERIALISED",
">",
"dataType",
")",
"{",
"Serialiser",
"<",
"?",
",",
"?",
">",
"serialiser",
"=",
"serialisers",
".",
"get",
"(",
"dataType",
")",
";",
"if",
"(",
"serialiser",
"==",
"null",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"Unsupported DataType: \"",
"+",
"dataType",
".",
"toString",
"(",
")",
")",
";",
"}",
"return",
"(",
"Serialiser",
"<",
"DESERIALISED",
",",
"?",
">",
")",
"serialiser",
";",
"}"
] | accessed via the constant properties defined above. | [
"accessed",
"via",
"the",
"constant",
"properties",
"defined",
"above",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/kb/concept/Serialiser.java#L57-L64 |
22,826 | graknlabs/grakn | server/src/graql/reasoner/atom/binary/AttributeAtom.java | AttributeAtom.rewriteWithRelationVariable | private AttributeAtom rewriteWithRelationVariable(Atom parentAtom){
if (parentAtom.isResource() && ((AttributeAtom) parentAtom).getRelationVariable().isReturned()) return rewriteWithRelationVariable();
return this;
} | java | private AttributeAtom rewriteWithRelationVariable(Atom parentAtom){
if (parentAtom.isResource() && ((AttributeAtom) parentAtom).getRelationVariable().isReturned()) return rewriteWithRelationVariable();
return this;
} | [
"private",
"AttributeAtom",
"rewriteWithRelationVariable",
"(",
"Atom",
"parentAtom",
")",
"{",
"if",
"(",
"parentAtom",
".",
"isResource",
"(",
")",
"&&",
"(",
"(",
"AttributeAtom",
")",
"parentAtom",
")",
".",
"getRelationVariable",
"(",
")",
".",
"isReturned",
"(",
")",
")",
"return",
"rewriteWithRelationVariable",
"(",
")",
";",
"return",
"this",
";",
"}"
] | rewrites the atom to one with relation variable
@param parentAtom parent atom that triggers rewrite
@return rewritten atom | [
"rewrites",
"the",
"atom",
"to",
"one",
"with",
"relation",
"variable"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/reasoner/atom/binary/AttributeAtom.java#L389-L392 |
22,827 | graknlabs/grakn | server/src/graql/gremlin/ConjunctionQuery.java | ConjunctionQuery.allFragmentOrders | Set<List<Fragment>> allFragmentOrders() {
Collection<List<EquivalentFragmentSet>> fragmentSetPermutations = Collections2.permutations(equivalentFragmentSets);
return fragmentSetPermutations.stream().flatMap(ConjunctionQuery::cartesianProduct).collect(toSet());
} | java | Set<List<Fragment>> allFragmentOrders() {
Collection<List<EquivalentFragmentSet>> fragmentSetPermutations = Collections2.permutations(equivalentFragmentSets);
return fragmentSetPermutations.stream().flatMap(ConjunctionQuery::cartesianProduct).collect(toSet());
} | [
"Set",
"<",
"List",
"<",
"Fragment",
">",
">",
"allFragmentOrders",
"(",
")",
"{",
"Collection",
"<",
"List",
"<",
"EquivalentFragmentSet",
">>",
"fragmentSetPermutations",
"=",
"Collections2",
".",
"permutations",
"(",
"equivalentFragmentSets",
")",
";",
"return",
"fragmentSetPermutations",
".",
"stream",
"(",
")",
".",
"flatMap",
"(",
"ConjunctionQuery",
"::",
"cartesianProduct",
")",
".",
"collect",
"(",
"toSet",
"(",
")",
")",
";",
"}"
] | Get all possible orderings of fragments | [
"Get",
"all",
"possible",
"orderings",
"of",
"fragments"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/gremlin/ConjunctionQuery.java#L112-L115 |
22,828 | graknlabs/grakn | server/src/graql/gremlin/GreedyTreeTraversal.java | GreedyTreeTraversal.branchWeight | private static double branchWeight(Node node, Arborescence<Node> arborescence,
Map<Node, Set<Node>> edgesParentToChild,
Map<Node, Map<Node, Fragment>> edgeFragmentChildToParent) {
Double nodeWeight = node.getNodeWeight();
if (nodeWeight == null) {
nodeWeight = getEdgeFragmentCost(node, arborescence, edgeFragmentChildToParent) + nodeFragmentWeight(node);
node.setNodeWeight(nodeWeight);
}
Double branchWeight = node.getBranchWeight();
if (branchWeight == null) {
final double[] weight = {nodeWeight};
if (edgesParentToChild.containsKey(node)) {
edgesParentToChild.get(node).forEach(child ->
weight[0] += branchWeight(child, arborescence, edgesParentToChild, edgeFragmentChildToParent));
}
branchWeight = weight[0];
node.setBranchWeight(branchWeight);
}
return branchWeight;
} | java | private static double branchWeight(Node node, Arborescence<Node> arborescence,
Map<Node, Set<Node>> edgesParentToChild,
Map<Node, Map<Node, Fragment>> edgeFragmentChildToParent) {
Double nodeWeight = node.getNodeWeight();
if (nodeWeight == null) {
nodeWeight = getEdgeFragmentCost(node, arborescence, edgeFragmentChildToParent) + nodeFragmentWeight(node);
node.setNodeWeight(nodeWeight);
}
Double branchWeight = node.getBranchWeight();
if (branchWeight == null) {
final double[] weight = {nodeWeight};
if (edgesParentToChild.containsKey(node)) {
edgesParentToChild.get(node).forEach(child ->
weight[0] += branchWeight(child, arborescence, edgesParentToChild, edgeFragmentChildToParent));
}
branchWeight = weight[0];
node.setBranchWeight(branchWeight);
}
return branchWeight;
} | [
"private",
"static",
"double",
"branchWeight",
"(",
"Node",
"node",
",",
"Arborescence",
"<",
"Node",
">",
"arborescence",
",",
"Map",
"<",
"Node",
",",
"Set",
"<",
"Node",
">",
">",
"edgesParentToChild",
",",
"Map",
"<",
"Node",
",",
"Map",
"<",
"Node",
",",
"Fragment",
">",
">",
"edgeFragmentChildToParent",
")",
"{",
"Double",
"nodeWeight",
"=",
"node",
".",
"getNodeWeight",
"(",
")",
";",
"if",
"(",
"nodeWeight",
"==",
"null",
")",
"{",
"nodeWeight",
"=",
"getEdgeFragmentCost",
"(",
"node",
",",
"arborescence",
",",
"edgeFragmentChildToParent",
")",
"+",
"nodeFragmentWeight",
"(",
"node",
")",
";",
"node",
".",
"setNodeWeight",
"(",
"nodeWeight",
")",
";",
"}",
"Double",
"branchWeight",
"=",
"node",
".",
"getBranchWeight",
"(",
")",
";",
"if",
"(",
"branchWeight",
"==",
"null",
")",
"{",
"final",
"double",
"[",
"]",
"weight",
"=",
"{",
"nodeWeight",
"}",
";",
"if",
"(",
"edgesParentToChild",
".",
"containsKey",
"(",
"node",
")",
")",
"{",
"edgesParentToChild",
".",
"get",
"(",
"node",
")",
".",
"forEach",
"(",
"child",
"->",
"weight",
"[",
"0",
"]",
"+=",
"branchWeight",
"(",
"child",
",",
"arborescence",
",",
"edgesParentToChild",
",",
"edgeFragmentChildToParent",
")",
")",
";",
"}",
"branchWeight",
"=",
"weight",
"[",
"0",
"]",
";",
"node",
".",
"setBranchWeight",
"(",
"branchWeight",
")",
";",
"}",
"return",
"branchWeight",
";",
"}"
] | recursively compute the weight of a branch | [
"recursively",
"compute",
"the",
"weight",
"of",
"a",
"branch"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/gremlin/GreedyTreeTraversal.java#L83-L107 |
22,829 | graknlabs/grakn | server/src/graql/gremlin/GreedyTreeTraversal.java | GreedyTreeTraversal.nodeFragmentWeight | private static double nodeFragmentWeight(Node node) {
double costFragmentsWithoutDependency = node.getFragmentsWithoutDependency().stream()
.mapToDouble(Fragment::fragmentCost).sum();
double costFragmentsWithDependencyVisited = node.getFragmentsWithDependencyVisited().stream()
.mapToDouble(Fragment::fragmentCost).sum();
double costFragmentsWithDependency = node.getFragmentsWithDependency().stream()
.mapToDouble(Fragment::fragmentCost).sum();
return costFragmentsWithoutDependency + node.getFixedFragmentCost() +
(costFragmentsWithDependencyVisited + costFragmentsWithDependency) / 2D;
} | java | private static double nodeFragmentWeight(Node node) {
double costFragmentsWithoutDependency = node.getFragmentsWithoutDependency().stream()
.mapToDouble(Fragment::fragmentCost).sum();
double costFragmentsWithDependencyVisited = node.getFragmentsWithDependencyVisited().stream()
.mapToDouble(Fragment::fragmentCost).sum();
double costFragmentsWithDependency = node.getFragmentsWithDependency().stream()
.mapToDouble(Fragment::fragmentCost).sum();
return costFragmentsWithoutDependency + node.getFixedFragmentCost() +
(costFragmentsWithDependencyVisited + costFragmentsWithDependency) / 2D;
} | [
"private",
"static",
"double",
"nodeFragmentWeight",
"(",
"Node",
"node",
")",
"{",
"double",
"costFragmentsWithoutDependency",
"=",
"node",
".",
"getFragmentsWithoutDependency",
"(",
")",
".",
"stream",
"(",
")",
".",
"mapToDouble",
"(",
"Fragment",
"::",
"fragmentCost",
")",
".",
"sum",
"(",
")",
";",
"double",
"costFragmentsWithDependencyVisited",
"=",
"node",
".",
"getFragmentsWithDependencyVisited",
"(",
")",
".",
"stream",
"(",
")",
".",
"mapToDouble",
"(",
"Fragment",
"::",
"fragmentCost",
")",
".",
"sum",
"(",
")",
";",
"double",
"costFragmentsWithDependency",
"=",
"node",
".",
"getFragmentsWithDependency",
"(",
")",
".",
"stream",
"(",
")",
".",
"mapToDouble",
"(",
"Fragment",
"::",
"fragmentCost",
")",
".",
"sum",
"(",
")",
";",
"return",
"costFragmentsWithoutDependency",
"+",
"node",
".",
"getFixedFragmentCost",
"(",
")",
"+",
"(",
"costFragmentsWithDependencyVisited",
"+",
"costFragmentsWithDependency",
")",
"/",
"2D",
";",
"}"
] | compute the total cost of a node | [
"compute",
"the",
"total",
"cost",
"of",
"a",
"node"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/gremlin/GreedyTreeTraversal.java#L110-L119 |
22,830 | graknlabs/grakn | server/src/graql/gremlin/GreedyTreeTraversal.java | GreedyTreeTraversal.getEdgeFragmentCost | private static double getEdgeFragmentCost(Node node, Arborescence<Node> arborescence,
Map<Node, Map<Node, Fragment>> edgeToFragment) {
Fragment fragment = getEdgeFragment(node, arborescence, edgeToFragment);
if (fragment != null) return fragment.fragmentCost();
return 0D;
} | java | private static double getEdgeFragmentCost(Node node, Arborescence<Node> arborescence,
Map<Node, Map<Node, Fragment>> edgeToFragment) {
Fragment fragment = getEdgeFragment(node, arborescence, edgeToFragment);
if (fragment != null) return fragment.fragmentCost();
return 0D;
} | [
"private",
"static",
"double",
"getEdgeFragmentCost",
"(",
"Node",
"node",
",",
"Arborescence",
"<",
"Node",
">",
"arborescence",
",",
"Map",
"<",
"Node",
",",
"Map",
"<",
"Node",
",",
"Fragment",
">",
">",
"edgeToFragment",
")",
"{",
"Fragment",
"fragment",
"=",
"getEdgeFragment",
"(",
"node",
",",
"arborescence",
",",
"edgeToFragment",
")",
";",
"if",
"(",
"fragment",
"!=",
"null",
")",
"return",
"fragment",
".",
"fragmentCost",
"(",
")",
";",
"return",
"0D",
";",
"}"
] | get edge fragment cost in order to map branch cost | [
"get",
"edge",
"fragment",
"cost",
"in",
"order",
"to",
"map",
"branch",
"cost"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/gremlin/GreedyTreeTraversal.java#L122-L129 |
22,831 | graknlabs/grakn | server/src/graql/reasoner/cache/IndexedAnswerSet.java | IndexedAnswerSet.add | public boolean add(ConceptMap answer, ConceptMap answerIndex){
Index ind = Index.of(answerIndex.vars());
if (ind.equals(index)) {
return indexedAnswers.put(answerIndex, answer);
}
throw new IllegalStateException("Illegal index: " + answerIndex + " indices: " + index);
} | java | public boolean add(ConceptMap answer, ConceptMap answerIndex){
Index ind = Index.of(answerIndex.vars());
if (ind.equals(index)) {
return indexedAnswers.put(answerIndex, answer);
}
throw new IllegalStateException("Illegal index: " + answerIndex + " indices: " + index);
} | [
"public",
"boolean",
"add",
"(",
"ConceptMap",
"answer",
",",
"ConceptMap",
"answerIndex",
")",
"{",
"Index",
"ind",
"=",
"Index",
".",
"of",
"(",
"answerIndex",
".",
"vars",
"(",
")",
")",
";",
"if",
"(",
"ind",
".",
"equals",
"(",
"index",
")",
")",
"{",
"return",
"indexedAnswers",
".",
"put",
"(",
"answerIndex",
",",
"answer",
")",
";",
"}",
"throw",
"new",
"IllegalStateException",
"(",
"\"Illegal index: \"",
"+",
"answerIndex",
"+",
"\" indices: \"",
"+",
"index",
")",
";",
"}"
] | add answer with specific index | [
"add",
"answer",
"with",
"specific",
"index"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/reasoner/cache/IndexedAnswerSet.java#L118-L124 |
22,832 | graknlabs/grakn | server/src/graql/reasoner/query/ReasonerQueryImpl.java | ReasonerQueryImpl.idTransform | public Map<Variable, ConceptId> idTransform(ReasonerQueryImpl query, Unifier unifier){
Map<Variable, ConceptId> transform = new HashMap<>();
this.getAtoms(IdPredicate.class)
.forEach(thisP -> {
Collection<Variable> vars = unifier.get(thisP.getVarName());
Variable var = !vars.isEmpty()? Iterators.getOnlyElement(vars.iterator()) : thisP.getVarName();
IdPredicate p2 = query.getIdPredicate(var);
if ( p2 != null) transform.put(thisP.getVarName(), p2.getPredicate());
});
return transform;
} | java | public Map<Variable, ConceptId> idTransform(ReasonerQueryImpl query, Unifier unifier){
Map<Variable, ConceptId> transform = new HashMap<>();
this.getAtoms(IdPredicate.class)
.forEach(thisP -> {
Collection<Variable> vars = unifier.get(thisP.getVarName());
Variable var = !vars.isEmpty()? Iterators.getOnlyElement(vars.iterator()) : thisP.getVarName();
IdPredicate p2 = query.getIdPredicate(var);
if ( p2 != null) transform.put(thisP.getVarName(), p2.getPredicate());
});
return transform;
} | [
"public",
"Map",
"<",
"Variable",
",",
"ConceptId",
">",
"idTransform",
"(",
"ReasonerQueryImpl",
"query",
",",
"Unifier",
"unifier",
")",
"{",
"Map",
"<",
"Variable",
",",
"ConceptId",
">",
"transform",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"this",
".",
"getAtoms",
"(",
"IdPredicate",
".",
"class",
")",
".",
"forEach",
"(",
"thisP",
"->",
"{",
"Collection",
"<",
"Variable",
">",
"vars",
"=",
"unifier",
".",
"get",
"(",
"thisP",
".",
"getVarName",
"(",
")",
")",
";",
"Variable",
"var",
"=",
"!",
"vars",
".",
"isEmpty",
"(",
")",
"?",
"Iterators",
".",
"getOnlyElement",
"(",
"vars",
".",
"iterator",
"(",
")",
")",
":",
"thisP",
".",
"getVarName",
"(",
")",
";",
"IdPredicate",
"p2",
"=",
"query",
".",
"getIdPredicate",
"(",
"var",
")",
";",
"if",
"(",
"p2",
"!=",
"null",
")",
"transform",
".",
"put",
"(",
"thisP",
".",
"getVarName",
"(",
")",
",",
"p2",
".",
"getPredicate",
"(",
")",
")",
";",
"}",
")",
";",
"return",
"transform",
";",
"}"
] | returns id transform that would convert this query to a query alpha-equivalent to the query,
provided they are structurally equivalent
@param query for which the transform is to be constructed
@param unifier between this query and provided query
@return id transform | [
"returns",
"id",
"transform",
"that",
"would",
"convert",
"this",
"query",
"to",
"a",
"query",
"alpha",
"-",
"equivalent",
"to",
"the",
"query",
"provided",
"they",
"are",
"structurally",
"equivalent"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/reasoner/query/ReasonerQueryImpl.java#L416-L426 |
22,833 | graknlabs/grakn | server/src/graql/reasoner/query/ReasonerQueryImpl.java | ReasonerQueryImpl.getSubstitution | public ConceptMap getSubstitution(){
if (substitution == null) {
Set<Variable> varNames = getVarNames();
Set<IdPredicate> predicates = getAtoms(IsaAtomBase.class)
.map(IsaAtomBase::getTypePredicate)
.filter(Objects::nonNull)
.filter(p -> varNames.contains(p.getVarName()))
.collect(Collectors.toSet());
getAtoms(IdPredicate.class).forEach(predicates::add);
HashMap<Variable, Concept> answerMap = new HashMap<>();
predicates.forEach(p -> {
Concept concept = tx().getConcept(p.getPredicate());
if (concept == null) throw GraqlCheckedException.idNotFound(p.getPredicate());
answerMap.put(p.getVarName(), concept);
});
substitution = new ConceptMap(answerMap);
}
return substitution;
} | java | public ConceptMap getSubstitution(){
if (substitution == null) {
Set<Variable> varNames = getVarNames();
Set<IdPredicate> predicates = getAtoms(IsaAtomBase.class)
.map(IsaAtomBase::getTypePredicate)
.filter(Objects::nonNull)
.filter(p -> varNames.contains(p.getVarName()))
.collect(Collectors.toSet());
getAtoms(IdPredicate.class).forEach(predicates::add);
HashMap<Variable, Concept> answerMap = new HashMap<>();
predicates.forEach(p -> {
Concept concept = tx().getConcept(p.getPredicate());
if (concept == null) throw GraqlCheckedException.idNotFound(p.getPredicate());
answerMap.put(p.getVarName(), concept);
});
substitution = new ConceptMap(answerMap);
}
return substitution;
} | [
"public",
"ConceptMap",
"getSubstitution",
"(",
")",
"{",
"if",
"(",
"substitution",
"==",
"null",
")",
"{",
"Set",
"<",
"Variable",
">",
"varNames",
"=",
"getVarNames",
"(",
")",
";",
"Set",
"<",
"IdPredicate",
">",
"predicates",
"=",
"getAtoms",
"(",
"IsaAtomBase",
".",
"class",
")",
".",
"map",
"(",
"IsaAtomBase",
"::",
"getTypePredicate",
")",
".",
"filter",
"(",
"Objects",
"::",
"nonNull",
")",
".",
"filter",
"(",
"p",
"->",
"varNames",
".",
"contains",
"(",
"p",
".",
"getVarName",
"(",
")",
")",
")",
".",
"collect",
"(",
"Collectors",
".",
"toSet",
"(",
")",
")",
";",
"getAtoms",
"(",
"IdPredicate",
".",
"class",
")",
".",
"forEach",
"(",
"predicates",
"::",
"add",
")",
";",
"HashMap",
"<",
"Variable",
",",
"Concept",
">",
"answerMap",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"predicates",
".",
"forEach",
"(",
"p",
"->",
"{",
"Concept",
"concept",
"=",
"tx",
"(",
")",
".",
"getConcept",
"(",
"p",
".",
"getPredicate",
"(",
")",
")",
";",
"if",
"(",
"concept",
"==",
"null",
")",
"throw",
"GraqlCheckedException",
".",
"idNotFound",
"(",
"p",
".",
"getPredicate",
"(",
")",
")",
";",
"answerMap",
".",
"put",
"(",
"p",
".",
"getVarName",
"(",
")",
",",
"concept",
")",
";",
"}",
")",
";",
"substitution",
"=",
"new",
"ConceptMap",
"(",
"answerMap",
")",
";",
"}",
"return",
"substitution",
";",
"}"
] | Does id predicates -> answer conversion
@return substitution obtained from all id predicates (including internal) in the query | [
"Does",
"id",
"predicates",
"-",
">",
"answer",
"conversion"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/reasoner/query/ReasonerQueryImpl.java#L431-L450 |
22,834 | graknlabs/grakn | server/src/server/kb/concept/RelationReified.java | RelationReified.castingsRelation | public Stream<Casting> castingsRelation(Role... roles) {
Set<Role> roleSet = new HashSet<>(Arrays.asList(roles));
if (roleSet.isEmpty()) {
return vertex().getEdgesOfType(Direction.OUT, Schema.EdgeLabel.ROLE_PLAYER).
map(edge -> Casting.withRelation(edge, owner));
}
//Traversal is used so we can potentially optimise on the index
Set<Integer> roleTypesIds = roleSet.stream().map(r -> r.labelId().getValue()).collect(Collectors.toSet());
return vertex().tx().getTinkerTraversal().V().
hasId(elementId()).
outE(Schema.EdgeLabel.ROLE_PLAYER.getLabel()).
has(Schema.EdgeProperty.RELATION_TYPE_LABEL_ID.name(), type().labelId().getValue()).
has(Schema.EdgeProperty.ROLE_LABEL_ID.name(), P.within(roleTypesIds)).
toStream().
map(edge -> vertex().tx().factory().buildEdgeElement(edge)).
map(edge -> Casting.withRelation(edge, owner));
} | java | public Stream<Casting> castingsRelation(Role... roles) {
Set<Role> roleSet = new HashSet<>(Arrays.asList(roles));
if (roleSet.isEmpty()) {
return vertex().getEdgesOfType(Direction.OUT, Schema.EdgeLabel.ROLE_PLAYER).
map(edge -> Casting.withRelation(edge, owner));
}
//Traversal is used so we can potentially optimise on the index
Set<Integer> roleTypesIds = roleSet.stream().map(r -> r.labelId().getValue()).collect(Collectors.toSet());
return vertex().tx().getTinkerTraversal().V().
hasId(elementId()).
outE(Schema.EdgeLabel.ROLE_PLAYER.getLabel()).
has(Schema.EdgeProperty.RELATION_TYPE_LABEL_ID.name(), type().labelId().getValue()).
has(Schema.EdgeProperty.ROLE_LABEL_ID.name(), P.within(roleTypesIds)).
toStream().
map(edge -> vertex().tx().factory().buildEdgeElement(edge)).
map(edge -> Casting.withRelation(edge, owner));
} | [
"public",
"Stream",
"<",
"Casting",
">",
"castingsRelation",
"(",
"Role",
"...",
"roles",
")",
"{",
"Set",
"<",
"Role",
">",
"roleSet",
"=",
"new",
"HashSet",
"<>",
"(",
"Arrays",
".",
"asList",
"(",
"roles",
")",
")",
";",
"if",
"(",
"roleSet",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"vertex",
"(",
")",
".",
"getEdgesOfType",
"(",
"Direction",
".",
"OUT",
",",
"Schema",
".",
"EdgeLabel",
".",
"ROLE_PLAYER",
")",
".",
"map",
"(",
"edge",
"->",
"Casting",
".",
"withRelation",
"(",
"edge",
",",
"owner",
")",
")",
";",
"}",
"//Traversal is used so we can potentially optimise on the index",
"Set",
"<",
"Integer",
">",
"roleTypesIds",
"=",
"roleSet",
".",
"stream",
"(",
")",
".",
"map",
"(",
"r",
"->",
"r",
".",
"labelId",
"(",
")",
".",
"getValue",
"(",
")",
")",
".",
"collect",
"(",
"Collectors",
".",
"toSet",
"(",
")",
")",
";",
"return",
"vertex",
"(",
")",
".",
"tx",
"(",
")",
".",
"getTinkerTraversal",
"(",
")",
".",
"V",
"(",
")",
".",
"hasId",
"(",
"elementId",
"(",
")",
")",
".",
"outE",
"(",
"Schema",
".",
"EdgeLabel",
".",
"ROLE_PLAYER",
".",
"getLabel",
"(",
")",
")",
".",
"has",
"(",
"Schema",
".",
"EdgeProperty",
".",
"RELATION_TYPE_LABEL_ID",
".",
"name",
"(",
")",
",",
"type",
"(",
")",
".",
"labelId",
"(",
")",
".",
"getValue",
"(",
")",
")",
".",
"has",
"(",
"Schema",
".",
"EdgeProperty",
".",
"ROLE_LABEL_ID",
".",
"name",
"(",
")",
",",
"P",
".",
"within",
"(",
"roleTypesIds",
")",
")",
".",
"toStream",
"(",
")",
".",
"map",
"(",
"edge",
"->",
"vertex",
"(",
")",
".",
"tx",
"(",
")",
".",
"factory",
"(",
")",
".",
"buildEdgeElement",
"(",
"edge",
")",
")",
".",
"map",
"(",
"edge",
"->",
"Casting",
".",
"withRelation",
"(",
"edge",
",",
"owner",
")",
")",
";",
"}"
] | Castings are retrieved from the perspective of the Relation
@param roles The Role which the Things are playing
@return The Casting which unify a Role and Thing with this Relation | [
"Castings",
"are",
"retrieved",
"from",
"the",
"perspective",
"of",
"the",
"Relation"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/kb/concept/RelationReified.java#L167-L184 |
22,835 | graknlabs/grakn | concept/answer/Explanation.java | Explanation.childOf | @CheckReturnValue
public Explanation childOf(ConceptMap ans) {
return new Explanation(getPattern(), ans.explanation().getAnswers());
} | java | @CheckReturnValue
public Explanation childOf(ConceptMap ans) {
return new Explanation(getPattern(), ans.explanation().getAnswers());
} | [
"@",
"CheckReturnValue",
"public",
"Explanation",
"childOf",
"(",
"ConceptMap",
"ans",
")",
"{",
"return",
"new",
"Explanation",
"(",
"getPattern",
"(",
")",
",",
"ans",
".",
"explanation",
"(",
")",
".",
"getAnswers",
"(",
")",
")",
";",
"}"
] | produce a new explanation with a provided parent answer
@param ans parent answer
@return new explanation with dependent answers | [
"produce",
"a",
"new",
"explanation",
"with",
"a",
"provided",
"parent",
"answer"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/concept/answer/Explanation.java#L82-L85 |
22,836 | graknlabs/grakn | server/src/graql/executor/ConceptBuilder.java | ConceptBuilder.validate | private void validate(Concept concept) {
validateParam(concept, TYPE, Thing.class, Thing::type);
validateParam(concept, SUPER_CONCEPT, SchemaConcept.class, SchemaConcept::sup);
validateParam(concept, LABEL, SchemaConcept.class, SchemaConcept::label);
validateParam(concept, ID, Concept.class, Concept::id);
validateParam(concept, VALUE, Attribute.class, Attribute::value);
validateParam(concept, DATA_TYPE, AttributeType.class, AttributeType::dataType);
validateParam(concept, WHEN, Rule.class, Rule::when);
validateParam(concept, THEN, Rule.class, Rule::then);
} | java | private void validate(Concept concept) {
validateParam(concept, TYPE, Thing.class, Thing::type);
validateParam(concept, SUPER_CONCEPT, SchemaConcept.class, SchemaConcept::sup);
validateParam(concept, LABEL, SchemaConcept.class, SchemaConcept::label);
validateParam(concept, ID, Concept.class, Concept::id);
validateParam(concept, VALUE, Attribute.class, Attribute::value);
validateParam(concept, DATA_TYPE, AttributeType.class, AttributeType::dataType);
validateParam(concept, WHEN, Rule.class, Rule::when);
validateParam(concept, THEN, Rule.class, Rule::then);
} | [
"private",
"void",
"validate",
"(",
"Concept",
"concept",
")",
"{",
"validateParam",
"(",
"concept",
",",
"TYPE",
",",
"Thing",
".",
"class",
",",
"Thing",
"::",
"type",
")",
";",
"validateParam",
"(",
"concept",
",",
"SUPER_CONCEPT",
",",
"SchemaConcept",
".",
"class",
",",
"SchemaConcept",
"::",
"sup",
")",
";",
"validateParam",
"(",
"concept",
",",
"LABEL",
",",
"SchemaConcept",
".",
"class",
",",
"SchemaConcept",
"::",
"label",
")",
";",
"validateParam",
"(",
"concept",
",",
"ID",
",",
"Concept",
".",
"class",
",",
"Concept",
"::",
"id",
")",
";",
"validateParam",
"(",
"concept",
",",
"VALUE",
",",
"Attribute",
".",
"class",
",",
"Attribute",
"::",
"value",
")",
";",
"validateParam",
"(",
"concept",
",",
"DATA_TYPE",
",",
"AttributeType",
".",
"class",
",",
"AttributeType",
"::",
"dataType",
")",
";",
"validateParam",
"(",
"concept",
",",
"WHEN",
",",
"Rule",
".",
"class",
",",
"Rule",
"::",
"when",
")",
";",
"validateParam",
"(",
"concept",
",",
"THEN",
",",
"Rule",
".",
"class",
",",
"Rule",
"::",
"then",
")",
";",
"}"
] | Check if this pre-existing concept conforms to all specified parameters
@throws GraqlQueryException if any parameter does not match | [
"Check",
"if",
"this",
"pre",
"-",
"existing",
"concept",
"conforms",
"to",
"all",
"specified",
"parameters"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ConceptBuilder.java#L360-L369 |
22,837 | graknlabs/grakn | server/src/graql/executor/ConceptBuilder.java | ConceptBuilder.validateParam | private <S extends Concept, T> void validateParam(
Concept concept, BuilderParam<T> param, Class<S> conceptType, Function<S, T> getter) {
if (has(param)) {
T value = use(param);
boolean isInstance = conceptType.isInstance(concept);
if (!isInstance || !Objects.equals(getter.apply(conceptType.cast(concept)), value)) {
throw GraqlQueryException.insertPropertyOnExistingConcept(param.name(), value, concept);
}
}
} | java | private <S extends Concept, T> void validateParam(
Concept concept, BuilderParam<T> param, Class<S> conceptType, Function<S, T> getter) {
if (has(param)) {
T value = use(param);
boolean isInstance = conceptType.isInstance(concept);
if (!isInstance || !Objects.equals(getter.apply(conceptType.cast(concept)), value)) {
throw GraqlQueryException.insertPropertyOnExistingConcept(param.name(), value, concept);
}
}
} | [
"private",
"<",
"S",
"extends",
"Concept",
",",
"T",
">",
"void",
"validateParam",
"(",
"Concept",
"concept",
",",
"BuilderParam",
"<",
"T",
">",
"param",
",",
"Class",
"<",
"S",
">",
"conceptType",
",",
"Function",
"<",
"S",
",",
"T",
">",
"getter",
")",
"{",
"if",
"(",
"has",
"(",
"param",
")",
")",
"{",
"T",
"value",
"=",
"use",
"(",
"param",
")",
";",
"boolean",
"isInstance",
"=",
"conceptType",
".",
"isInstance",
"(",
"concept",
")",
";",
"if",
"(",
"!",
"isInstance",
"||",
"!",
"Objects",
".",
"equals",
"(",
"getter",
".",
"apply",
"(",
"conceptType",
".",
"cast",
"(",
"concept",
")",
")",
",",
"value",
")",
")",
"{",
"throw",
"GraqlQueryException",
".",
"insertPropertyOnExistingConcept",
"(",
"param",
".",
"name",
"(",
")",
",",
"value",
",",
"concept",
")",
";",
"}",
"}",
"}"
] | Check if the concept is of the given type and has a property that matches the given parameter.
@throws GraqlQueryException if the concept does not satisfy the parameter | [
"Check",
"if",
"the",
"concept",
"is",
"of",
"the",
"given",
"type",
"and",
"has",
"a",
"property",
"that",
"matches",
"the",
"given",
"parameter",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ConceptBuilder.java#L376-L388 |
22,838 | graknlabs/grakn | server/src/graql/executor/ConceptBuilder.java | ConceptBuilder.setSuper | public static void setSuper(SchemaConcept subConcept, SchemaConcept superConcept) {
if (superConcept.isEntityType()) {
subConcept.asEntityType().sup(superConcept.asEntityType());
} else if (superConcept.isRelationType()) {
subConcept.asRelationType().sup(superConcept.asRelationType());
} else if (superConcept.isRole()) {
subConcept.asRole().sup(superConcept.asRole());
} else if (superConcept.isAttributeType()) {
subConcept.asAttributeType().sup(superConcept.asAttributeType());
} else if (superConcept.isRule()) {
subConcept.asRule().sup(superConcept.asRule());
} else {
throw InvalidKBException.insertMetaType(subConcept.label(), superConcept);
}
} | java | public static void setSuper(SchemaConcept subConcept, SchemaConcept superConcept) {
if (superConcept.isEntityType()) {
subConcept.asEntityType().sup(superConcept.asEntityType());
} else if (superConcept.isRelationType()) {
subConcept.asRelationType().sup(superConcept.asRelationType());
} else if (superConcept.isRole()) {
subConcept.asRole().sup(superConcept.asRole());
} else if (superConcept.isAttributeType()) {
subConcept.asAttributeType().sup(superConcept.asAttributeType());
} else if (superConcept.isRule()) {
subConcept.asRule().sup(superConcept.asRule());
} else {
throw InvalidKBException.insertMetaType(subConcept.label(), superConcept);
}
} | [
"public",
"static",
"void",
"setSuper",
"(",
"SchemaConcept",
"subConcept",
",",
"SchemaConcept",
"superConcept",
")",
"{",
"if",
"(",
"superConcept",
".",
"isEntityType",
"(",
")",
")",
"{",
"subConcept",
".",
"asEntityType",
"(",
")",
".",
"sup",
"(",
"superConcept",
".",
"asEntityType",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"superConcept",
".",
"isRelationType",
"(",
")",
")",
"{",
"subConcept",
".",
"asRelationType",
"(",
")",
".",
"sup",
"(",
"superConcept",
".",
"asRelationType",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"superConcept",
".",
"isRole",
"(",
")",
")",
"{",
"subConcept",
".",
"asRole",
"(",
")",
".",
"sup",
"(",
"superConcept",
".",
"asRole",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"superConcept",
".",
"isAttributeType",
"(",
")",
")",
"{",
"subConcept",
".",
"asAttributeType",
"(",
")",
".",
"sup",
"(",
"superConcept",
".",
"asAttributeType",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"superConcept",
".",
"isRule",
"(",
")",
")",
"{",
"subConcept",
".",
"asRule",
"(",
")",
".",
"sup",
"(",
"superConcept",
".",
"asRule",
"(",
")",
")",
";",
"}",
"else",
"{",
"throw",
"InvalidKBException",
".",
"insertMetaType",
"(",
"subConcept",
".",
"label",
"(",
")",
",",
"superConcept",
")",
";",
"}",
"}"
] | Make the second argument the super of the first argument
@throws GraqlQueryException if the types are different, or setting the super to be a meta-type | [
"Make",
"the",
"second",
"argument",
"the",
"super",
"of",
"the",
"first",
"argument"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ConceptBuilder.java#L438-L452 |
22,839 | graknlabs/grakn | server/src/server/deduplicator/AttributeDeduplicatorDaemon.java | AttributeDeduplicatorDaemon.markForDeduplication | public void markForDeduplication(KeyspaceImpl keyspace, String index, ConceptId conceptId) {
Attribute attribute = Attribute.create(keyspace, index, conceptId);
LOG.trace("insert({})", attribute);
queue.insert(attribute);
} | java | public void markForDeduplication(KeyspaceImpl keyspace, String index, ConceptId conceptId) {
Attribute attribute = Attribute.create(keyspace, index, conceptId);
LOG.trace("insert({})", attribute);
queue.insert(attribute);
} | [
"public",
"void",
"markForDeduplication",
"(",
"KeyspaceImpl",
"keyspace",
",",
"String",
"index",
",",
"ConceptId",
"conceptId",
")",
"{",
"Attribute",
"attribute",
"=",
"Attribute",
".",
"create",
"(",
"keyspace",
",",
"index",
",",
"conceptId",
")",
";",
"LOG",
".",
"trace",
"(",
"\"insert({})\"",
",",
"attribute",
")",
";",
"queue",
".",
"insert",
"(",
"attribute",
")",
";",
"}"
] | Marks an attribute for deduplication. The attribute will be inserted to an internal queue to be processed by the de-duplicator daemon in real-time.
The attribute must have been inserted to the database, prior to calling this method.
@param keyspace keyspace of the attribute
@param index the value of the attribute
@param conceptId the concept id of the attribute | [
"Marks",
"an",
"attribute",
"for",
"deduplication",
".",
"The",
"attribute",
"will",
"be",
"inserted",
"to",
"an",
"internal",
"queue",
"to",
"be",
"processed",
"by",
"the",
"de",
"-",
"duplicator",
"daemon",
"in",
"real",
"-",
"time",
".",
"The",
"attribute",
"must",
"have",
"been",
"inserted",
"to",
"the",
"database",
"prior",
"to",
"calling",
"this",
"method",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/deduplicator/AttributeDeduplicatorDaemon.java#L83-L87 |
22,840 | graknlabs/grakn | server/src/graql/util/Partition.java | Partition.singletons | public static <T> Partition<T> singletons(Collection<T> nodes) {
final Map<T, T> parents = Maps.newHashMap();
final Map<T, Integer> ranks = Maps.newHashMap();
for (T node : nodes) {
parents.put(node, node); // each node is its own head
ranks.put(node, 0); // every node has depth 0 to start
}
return new Partition<T>(parents, ranks);
} | java | public static <T> Partition<T> singletons(Collection<T> nodes) {
final Map<T, T> parents = Maps.newHashMap();
final Map<T, Integer> ranks = Maps.newHashMap();
for (T node : nodes) {
parents.put(node, node); // each node is its own head
ranks.put(node, 0); // every node has depth 0 to start
}
return new Partition<T>(parents, ranks);
} | [
"public",
"static",
"<",
"T",
">",
"Partition",
"<",
"T",
">",
"singletons",
"(",
"Collection",
"<",
"T",
">",
"nodes",
")",
"{",
"final",
"Map",
"<",
"T",
",",
"T",
">",
"parents",
"=",
"Maps",
".",
"newHashMap",
"(",
")",
";",
"final",
"Map",
"<",
"T",
",",
"Integer",
">",
"ranks",
"=",
"Maps",
".",
"newHashMap",
"(",
")",
";",
"for",
"(",
"T",
"node",
":",
"nodes",
")",
"{",
"parents",
".",
"put",
"(",
"node",
",",
"node",
")",
";",
"// each node is its own head",
"ranks",
".",
"put",
"(",
"node",
",",
"0",
")",
";",
"// every node has depth 0 to start",
"}",
"return",
"new",
"Partition",
"<",
"T",
">",
"(",
"parents",
",",
"ranks",
")",
";",
"}"
] | Constructs a new partition of singletons | [
"Constructs",
"a",
"new",
"partition",
"of",
"singletons"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/util/Partition.java#L44-L52 |
22,841 | graknlabs/grakn | server/src/graql/util/Partition.java | Partition.componentOf | public V componentOf(V i) {
final V parent = parents.getOrDefault(i, i);
if (parent.equals(i)) {
return i;
} else {
// collapse, so next lookup is O(1)
parents.put(i, componentOf(parent));
}
return parents.get(i);
} | java | public V componentOf(V i) {
final V parent = parents.getOrDefault(i, i);
if (parent.equals(i)) {
return i;
} else {
// collapse, so next lookup is O(1)
parents.put(i, componentOf(parent));
}
return parents.get(i);
} | [
"public",
"V",
"componentOf",
"(",
"V",
"i",
")",
"{",
"final",
"V",
"parent",
"=",
"parents",
".",
"getOrDefault",
"(",
"i",
",",
"i",
")",
";",
"if",
"(",
"parent",
".",
"equals",
"(",
"i",
")",
")",
"{",
"return",
"i",
";",
"}",
"else",
"{",
"// collapse, so next lookup is O(1)",
"parents",
".",
"put",
"(",
"i",
",",
"componentOf",
"(",
"parent",
")",
")",
";",
"}",
"return",
"parents",
".",
"get",
"(",
"i",
")",
";",
"}"
] | Find the representative for the given item | [
"Find",
"the",
"representative",
"for",
"the",
"given",
"item"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/util/Partition.java#L57-L66 |
22,842 | graknlabs/grakn | server/src/graql/util/Partition.java | Partition.merge | public V merge(V a, V b) {
final V aHead = componentOf(a);
final V bHead = componentOf(b);
if (aHead.equals(bHead)) return aHead;
// add the shorter tree underneath the taller tree
final int aRank = ranks.getOrDefault(aHead, 0);
final int bRank = ranks.getOrDefault(bHead, 0);
if (aRank > bRank) {
parents.put(bHead, aHead);
return aHead;
} else if (bRank > aRank) {
parents.put(aHead, bHead);
return bHead;
} else {
// whoops, the tree got taller
parents.put(bHead, aHead);
ranks.put(aHead, aRank + 1);
return aHead;
}
} | java | public V merge(V a, V b) {
final V aHead = componentOf(a);
final V bHead = componentOf(b);
if (aHead.equals(bHead)) return aHead;
// add the shorter tree underneath the taller tree
final int aRank = ranks.getOrDefault(aHead, 0);
final int bRank = ranks.getOrDefault(bHead, 0);
if (aRank > bRank) {
parents.put(bHead, aHead);
return aHead;
} else if (bRank > aRank) {
parents.put(aHead, bHead);
return bHead;
} else {
// whoops, the tree got taller
parents.put(bHead, aHead);
ranks.put(aHead, aRank + 1);
return aHead;
}
} | [
"public",
"V",
"merge",
"(",
"V",
"a",
",",
"V",
"b",
")",
"{",
"final",
"V",
"aHead",
"=",
"componentOf",
"(",
"a",
")",
";",
"final",
"V",
"bHead",
"=",
"componentOf",
"(",
"b",
")",
";",
"if",
"(",
"aHead",
".",
"equals",
"(",
"bHead",
")",
")",
"return",
"aHead",
";",
"// add the shorter tree underneath the taller tree",
"final",
"int",
"aRank",
"=",
"ranks",
".",
"getOrDefault",
"(",
"aHead",
",",
"0",
")",
";",
"final",
"int",
"bRank",
"=",
"ranks",
".",
"getOrDefault",
"(",
"bHead",
",",
"0",
")",
";",
"if",
"(",
"aRank",
">",
"bRank",
")",
"{",
"parents",
".",
"put",
"(",
"bHead",
",",
"aHead",
")",
";",
"return",
"aHead",
";",
"}",
"else",
"if",
"(",
"bRank",
">",
"aRank",
")",
"{",
"parents",
".",
"put",
"(",
"aHead",
",",
"bHead",
")",
";",
"return",
"bHead",
";",
"}",
"else",
"{",
"// whoops, the tree got taller",
"parents",
".",
"put",
"(",
"bHead",
",",
"aHead",
")",
";",
"ranks",
".",
"put",
"(",
"aHead",
",",
"aRank",
"+",
"1",
")",
";",
"return",
"aHead",
";",
"}",
"}"
] | Merges the given components and returns the representative of the new component | [
"Merges",
"the",
"given",
"components",
"and",
"returns",
"the",
"representative",
"of",
"the",
"new",
"component"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/util/Partition.java#L71-L90 |
22,843 | graknlabs/grakn | server/src/graql/util/Partition.java | Partition.sameComponent | public boolean sameComponent(V a, V b) {
return componentOf(a).equals(componentOf(b));
} | java | public boolean sameComponent(V a, V b) {
return componentOf(a).equals(componentOf(b));
} | [
"public",
"boolean",
"sameComponent",
"(",
"V",
"a",
",",
"V",
"b",
")",
"{",
"return",
"componentOf",
"(",
"a",
")",
".",
"equals",
"(",
"componentOf",
"(",
"b",
")",
")",
";",
"}"
] | Determines whether the two items are in the same component or not | [
"Determines",
"whether",
"the",
"two",
"items",
"are",
"in",
"the",
"same",
"component",
"or",
"not"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/util/Partition.java#L95-L97 |
22,844 | graknlabs/grakn | server/src/server/kb/Validator.java | Validator.validateRelationType | private void validateRelationType(RelationType relationType) {
ValidateGlobalRules.validateHasMinimumRoles(relationType).ifPresent(errorsFound::add);
errorsFound.addAll(ValidateGlobalRules.validateRelationTypesToRolesSchema(relationType));
} | java | private void validateRelationType(RelationType relationType) {
ValidateGlobalRules.validateHasMinimumRoles(relationType).ifPresent(errorsFound::add);
errorsFound.addAll(ValidateGlobalRules.validateRelationTypesToRolesSchema(relationType));
} | [
"private",
"void",
"validateRelationType",
"(",
"RelationType",
"relationType",
")",
"{",
"ValidateGlobalRules",
".",
"validateHasMinimumRoles",
"(",
"relationType",
")",
".",
"ifPresent",
"(",
"errorsFound",
"::",
"add",
")",
";",
"errorsFound",
".",
"addAll",
"(",
"ValidateGlobalRules",
".",
"validateRelationTypesToRolesSchema",
"(",
"relationType",
")",
")",
";",
"}"
] | Validation rules exclusive to relation types
@param relationType The relationTypes to validate | [
"Validation",
"rules",
"exclusive",
"to",
"relation",
"types"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/kb/Validator.java#L125-L128 |
22,845 | graknlabs/grakn | server/src/server/kb/structure/Shard.java | Shard.link | public void link(ConceptImpl concept) {
concept.vertex().addEdge(vertex(), Schema.EdgeLabel.ISA);
} | java | public void link(ConceptImpl concept) {
concept.vertex().addEdge(vertex(), Schema.EdgeLabel.ISA);
} | [
"public",
"void",
"link",
"(",
"ConceptImpl",
"concept",
")",
"{",
"concept",
".",
"vertex",
"(",
")",
".",
"addEdge",
"(",
"vertex",
"(",
")",
",",
"Schema",
".",
"EdgeLabel",
".",
"ISA",
")",
";",
"}"
] | Links a new concept to this shard.
@param concept The concept to link to this shard | [
"Links",
"a",
"new",
"concept",
"to",
"this",
"shard",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/kb/structure/Shard.java#L69-L71 |
22,846 | graknlabs/grakn | server/src/graql/analytics/Utility.java | Utility.isAlive | static boolean isAlive(Vertex vertex) {
if (vertex == null) return false;
try {
return Sets.newHashSet(Schema.BaseType.values()).contains(Schema.BaseType.valueOf(vertex.label()));
} catch (IllegalStateException e) {
return false;
}
} | java | static boolean isAlive(Vertex vertex) {
if (vertex == null) return false;
try {
return Sets.newHashSet(Schema.BaseType.values()).contains(Schema.BaseType.valueOf(vertex.label()));
} catch (IllegalStateException e) {
return false;
}
} | [
"static",
"boolean",
"isAlive",
"(",
"Vertex",
"vertex",
")",
"{",
"if",
"(",
"vertex",
"==",
"null",
")",
"return",
"false",
";",
"try",
"{",
"return",
"Sets",
".",
"newHashSet",
"(",
"Schema",
".",
"BaseType",
".",
"values",
"(",
")",
")",
".",
"contains",
"(",
"Schema",
".",
"BaseType",
".",
"valueOf",
"(",
"vertex",
".",
"label",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"IllegalStateException",
"e",
")",
"{",
"return",
"false",
";",
"}",
"}"
] | The state of the vertex in the database. This may detect ghost nodes and allow them to be excluded from
computations. If the vertex is alive it is likely to be a valid Grakn concept.
@return if the vertex is alive | [
"The",
"state",
"of",
"the",
"vertex",
"in",
"the",
"database",
".",
"This",
"may",
"detect",
"ghost",
"nodes",
"and",
"allow",
"them",
"to",
"be",
"excluded",
"from",
"computations",
".",
"If",
"the",
"vertex",
"is",
"alive",
"it",
"is",
"likely",
"to",
"be",
"a",
"valid",
"Grakn",
"concept",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/analytics/Utility.java#L74-L82 |
22,847 | graknlabs/grakn | server/src/graql/analytics/Utility.java | Utility.reduceSet | static <T> Set<T> reduceSet(Iterator<Set<T>> values) {
Set<T> set = new HashSet<>();
while (values.hasNext()) {
set.addAll(values.next());
}
return set;
} | java | static <T> Set<T> reduceSet(Iterator<Set<T>> values) {
Set<T> set = new HashSet<>();
while (values.hasNext()) {
set.addAll(values.next());
}
return set;
} | [
"static",
"<",
"T",
">",
"Set",
"<",
"T",
">",
"reduceSet",
"(",
"Iterator",
"<",
"Set",
"<",
"T",
">",
">",
"values",
")",
"{",
"Set",
"<",
"T",
">",
"set",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"while",
"(",
"values",
".",
"hasNext",
"(",
")",
")",
"{",
"set",
".",
"addAll",
"(",
"values",
".",
"next",
"(",
")",
")",
";",
"}",
"return",
"set",
";",
"}"
] | A helper method for set MapReduce. It simply combines sets into one set.
@param values the aggregated values associated with the key
@param <T> the type of the set
@return the combined set | [
"A",
"helper",
"method",
"for",
"set",
"MapReduce",
".",
"It",
"simply",
"combines",
"sets",
"into",
"one",
"set",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/analytics/Utility.java#L91-L97 |
22,848 | graknlabs/grakn | server/src/graql/analytics/Utility.java | Utility.keyValuesToMap | static <K, V> Map<K, V> keyValuesToMap(Iterator<KeyValue<K, V>> keyValues) {
Map<K, V> map = new HashMap<>();
keyValues.forEachRemaining(pair -> map.put(pair.getKey(), pair.getValue()));
return map;
} | java | static <K, V> Map<K, V> keyValuesToMap(Iterator<KeyValue<K, V>> keyValues) {
Map<K, V> map = new HashMap<>();
keyValues.forEachRemaining(pair -> map.put(pair.getKey(), pair.getValue()));
return map;
} | [
"static",
"<",
"K",
",",
"V",
">",
"Map",
"<",
"K",
",",
"V",
">",
"keyValuesToMap",
"(",
"Iterator",
"<",
"KeyValue",
"<",
"K",
",",
"V",
">",
">",
"keyValues",
")",
"{",
"Map",
"<",
"K",
",",
"V",
">",
"map",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"keyValues",
".",
"forEachRemaining",
"(",
"pair",
"->",
"map",
".",
"put",
"(",
"pair",
".",
"getKey",
"(",
")",
",",
"pair",
".",
"getValue",
"(",
")",
")",
")",
";",
"return",
"map",
";",
"}"
] | Transforms an iterator of key-value pairs into a map
@param keyValues an iterator of key-value pairs
@param <K> the type of the keys
@param <V> the type of the values
@return the resulting map | [
"Transforms",
"an",
"iterator",
"of",
"key",
"-",
"value",
"pairs",
"into",
"a",
"map"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/analytics/Utility.java#L107-L111 |
22,849 | graknlabs/grakn | server/src/graql/analytics/Utility.java | Utility.mayHaveResourceEdge | private static boolean mayHaveResourceEdge(TransactionOLTP graknGraph, ConceptId conceptId1, ConceptId conceptId2) {
Concept concept1 = graknGraph.getConcept(conceptId1);
Concept concept2 = graknGraph.getConcept(conceptId2);
return concept1 != null && concept2 != null && (concept1.isAttribute() || concept2.isAttribute());
} | java | private static boolean mayHaveResourceEdge(TransactionOLTP graknGraph, ConceptId conceptId1, ConceptId conceptId2) {
Concept concept1 = graknGraph.getConcept(conceptId1);
Concept concept2 = graknGraph.getConcept(conceptId2);
return concept1 != null && concept2 != null && (concept1.isAttribute() || concept2.isAttribute());
} | [
"private",
"static",
"boolean",
"mayHaveResourceEdge",
"(",
"TransactionOLTP",
"graknGraph",
",",
"ConceptId",
"conceptId1",
",",
"ConceptId",
"conceptId2",
")",
"{",
"Concept",
"concept1",
"=",
"graknGraph",
".",
"getConcept",
"(",
"conceptId1",
")",
";",
"Concept",
"concept2",
"=",
"graknGraph",
".",
"getConcept",
"(",
"conceptId2",
")",
";",
"return",
"concept1",
"!=",
"null",
"&&",
"concept2",
"!=",
"null",
"&&",
"(",
"concept1",
".",
"isAttribute",
"(",
")",
"||",
"concept2",
".",
"isAttribute",
"(",
")",
")",
";",
"}"
] | Check whether it is possible that there is a resource edge between the two given concepts. | [
"Check",
"whether",
"it",
"is",
"possible",
"that",
"there",
"is",
"a",
"resource",
"edge",
"between",
"the",
"two",
"given",
"concepts",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/analytics/Utility.java#L116-L120 |
22,850 | graknlabs/grakn | server/src/graql/analytics/Utility.java | Utility.getResourceEdgeId | public static ConceptId getResourceEdgeId(TransactionOLTP graph, ConceptId conceptId1, ConceptId conceptId2) {
if (mayHaveResourceEdge(graph, conceptId1, conceptId2)) {
Optional<Concept> firstConcept = graph.stream(Graql.match(
var("x").id(conceptId1.getValue()),
var("y").id(conceptId2.getValue()),
var("z").rel(var("x")).rel(var("y")))
.get("z"))
.map(answer -> answer.get("z"))
.findFirst();
if (firstConcept.isPresent()) {
return firstConcept.get().id();
}
}
return null;
} | java | public static ConceptId getResourceEdgeId(TransactionOLTP graph, ConceptId conceptId1, ConceptId conceptId2) {
if (mayHaveResourceEdge(graph, conceptId1, conceptId2)) {
Optional<Concept> firstConcept = graph.stream(Graql.match(
var("x").id(conceptId1.getValue()),
var("y").id(conceptId2.getValue()),
var("z").rel(var("x")).rel(var("y")))
.get("z"))
.map(answer -> answer.get("z"))
.findFirst();
if (firstConcept.isPresent()) {
return firstConcept.get().id();
}
}
return null;
} | [
"public",
"static",
"ConceptId",
"getResourceEdgeId",
"(",
"TransactionOLTP",
"graph",
",",
"ConceptId",
"conceptId1",
",",
"ConceptId",
"conceptId2",
")",
"{",
"if",
"(",
"mayHaveResourceEdge",
"(",
"graph",
",",
"conceptId1",
",",
"conceptId2",
")",
")",
"{",
"Optional",
"<",
"Concept",
">",
"firstConcept",
"=",
"graph",
".",
"stream",
"(",
"Graql",
".",
"match",
"(",
"var",
"(",
"\"x\"",
")",
".",
"id",
"(",
"conceptId1",
".",
"getValue",
"(",
")",
")",
",",
"var",
"(",
"\"y\"",
")",
".",
"id",
"(",
"conceptId2",
".",
"getValue",
"(",
")",
")",
",",
"var",
"(",
"\"z\"",
")",
".",
"rel",
"(",
"var",
"(",
"\"x\"",
")",
")",
".",
"rel",
"(",
"var",
"(",
"\"y\"",
")",
")",
")",
".",
"get",
"(",
"\"z\"",
")",
")",
".",
"map",
"(",
"answer",
"->",
"answer",
".",
"get",
"(",
"\"z\"",
")",
")",
".",
"findFirst",
"(",
")",
";",
"if",
"(",
"firstConcept",
".",
"isPresent",
"(",
")",
")",
"{",
"return",
"firstConcept",
".",
"get",
"(",
")",
".",
"id",
"(",
")",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Get the resource edge id if there is one. Return null if not. | [
"Get",
"the",
"resource",
"edge",
"id",
"if",
"there",
"is",
"one",
".",
"Return",
"null",
"if",
"not",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/analytics/Utility.java#L125-L139 |
22,851 | graknlabs/grakn | server/src/server/ServerFactory.java | ServerFactory.createServer | public static Server createServer(boolean benchmark) {
// Grakn Server configuration
ServerID serverID = ServerID.me();
Config config = Config.create();
JanusGraphFactory janusGraphFactory = new JanusGraphFactory(config);
// locks
LockManager lockManager = new ServerLockManager();
KeyspaceManager keyspaceStore = new KeyspaceManager(janusGraphFactory, config);
// session factory
SessionFactory sessionFactory = new SessionFactory(lockManager, janusGraphFactory, keyspaceStore, config);
// post-processing
AttributeDeduplicatorDaemon attributeDeduplicatorDaemon = new AttributeDeduplicatorDaemon(sessionFactory);
// Enable server tracing
if (benchmark) {
ServerTracing.initInstrumentation("server-instrumentation");
}
// create gRPC server
io.grpc.Server serverRPC = createServerRPC(config, sessionFactory, attributeDeduplicatorDaemon, keyspaceStore, janusGraphFactory);
return createServer(serverID, serverRPC, lockManager, attributeDeduplicatorDaemon, keyspaceStore);
} | java | public static Server createServer(boolean benchmark) {
// Grakn Server configuration
ServerID serverID = ServerID.me();
Config config = Config.create();
JanusGraphFactory janusGraphFactory = new JanusGraphFactory(config);
// locks
LockManager lockManager = new ServerLockManager();
KeyspaceManager keyspaceStore = new KeyspaceManager(janusGraphFactory, config);
// session factory
SessionFactory sessionFactory = new SessionFactory(lockManager, janusGraphFactory, keyspaceStore, config);
// post-processing
AttributeDeduplicatorDaemon attributeDeduplicatorDaemon = new AttributeDeduplicatorDaemon(sessionFactory);
// Enable server tracing
if (benchmark) {
ServerTracing.initInstrumentation("server-instrumentation");
}
// create gRPC server
io.grpc.Server serverRPC = createServerRPC(config, sessionFactory, attributeDeduplicatorDaemon, keyspaceStore, janusGraphFactory);
return createServer(serverID, serverRPC, lockManager, attributeDeduplicatorDaemon, keyspaceStore);
} | [
"public",
"static",
"Server",
"createServer",
"(",
"boolean",
"benchmark",
")",
"{",
"// Grakn Server configuration",
"ServerID",
"serverID",
"=",
"ServerID",
".",
"me",
"(",
")",
";",
"Config",
"config",
"=",
"Config",
".",
"create",
"(",
")",
";",
"JanusGraphFactory",
"janusGraphFactory",
"=",
"new",
"JanusGraphFactory",
"(",
"config",
")",
";",
"// locks",
"LockManager",
"lockManager",
"=",
"new",
"ServerLockManager",
"(",
")",
";",
"KeyspaceManager",
"keyspaceStore",
"=",
"new",
"KeyspaceManager",
"(",
"janusGraphFactory",
",",
"config",
")",
";",
"// session factory",
"SessionFactory",
"sessionFactory",
"=",
"new",
"SessionFactory",
"(",
"lockManager",
",",
"janusGraphFactory",
",",
"keyspaceStore",
",",
"config",
")",
";",
"// post-processing",
"AttributeDeduplicatorDaemon",
"attributeDeduplicatorDaemon",
"=",
"new",
"AttributeDeduplicatorDaemon",
"(",
"sessionFactory",
")",
";",
"// Enable server tracing",
"if",
"(",
"benchmark",
")",
"{",
"ServerTracing",
".",
"initInstrumentation",
"(",
"\"server-instrumentation\"",
")",
";",
"}",
"// create gRPC server",
"io",
".",
"grpc",
".",
"Server",
"serverRPC",
"=",
"createServerRPC",
"(",
"config",
",",
"sessionFactory",
",",
"attributeDeduplicatorDaemon",
",",
"keyspaceStore",
",",
"janusGraphFactory",
")",
";",
"return",
"createServer",
"(",
"serverID",
",",
"serverRPC",
",",
"lockManager",
",",
"attributeDeduplicatorDaemon",
",",
"keyspaceStore",
")",
";",
"}"
] | Create a Server configured for Grakn Core.
@return a Server instance configured for Grakn Core | [
"Create",
"a",
"Server",
"configured",
"for",
"Grakn",
"Core",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/ServerFactory.java#L46-L73 |
22,852 | graknlabs/grakn | server/src/server/ServerFactory.java | ServerFactory.createServer | public static Server createServer(
ServerID serverID, io.grpc.Server rpcServer,
LockManager lockManager, AttributeDeduplicatorDaemon attributeDeduplicatorDaemon, KeyspaceManager keyspaceStore) {
Server server = new Server(serverID, lockManager, rpcServer, attributeDeduplicatorDaemon, keyspaceStore);
Runtime.getRuntime().addShutdownHook(new Thread(server::close, "grakn-server-shutdown"));
return server;
} | java | public static Server createServer(
ServerID serverID, io.grpc.Server rpcServer,
LockManager lockManager, AttributeDeduplicatorDaemon attributeDeduplicatorDaemon, KeyspaceManager keyspaceStore) {
Server server = new Server(serverID, lockManager, rpcServer, attributeDeduplicatorDaemon, keyspaceStore);
Runtime.getRuntime().addShutdownHook(new Thread(server::close, "grakn-server-shutdown"));
return server;
} | [
"public",
"static",
"Server",
"createServer",
"(",
"ServerID",
"serverID",
",",
"io",
".",
"grpc",
".",
"Server",
"rpcServer",
",",
"LockManager",
"lockManager",
",",
"AttributeDeduplicatorDaemon",
"attributeDeduplicatorDaemon",
",",
"KeyspaceManager",
"keyspaceStore",
")",
"{",
"Server",
"server",
"=",
"new",
"Server",
"(",
"serverID",
",",
"lockManager",
",",
"rpcServer",
",",
"attributeDeduplicatorDaemon",
",",
"keyspaceStore",
")",
";",
"Runtime",
".",
"getRuntime",
"(",
")",
".",
"addShutdownHook",
"(",
"new",
"Thread",
"(",
"server",
"::",
"close",
",",
"\"grakn-server-shutdown\"",
")",
")",
";",
"return",
"server",
";",
"}"
] | Allows the creation of a Server instance with various configurations
@return a Server instance | [
"Allows",
"the",
"creation",
"of",
"a",
"Server",
"instance",
"with",
"various",
"configurations"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/ServerFactory.java#L81-L90 |
22,853 | graknlabs/grakn | server/src/graql/gremlin/spanningtree/EdgeQueueMap.java | EdgeQueueMap.popBestEdge | public Optional<ExclusiveEdge> popBestEdge(Node component, Arborescence<Node> best) {
if (!queueByDestination.containsKey(component)) return Optional.empty();
return queueByDestination.get(component).popBestEdge(best);
} | java | public Optional<ExclusiveEdge> popBestEdge(Node component, Arborescence<Node> best) {
if (!queueByDestination.containsKey(component)) return Optional.empty();
return queueByDestination.get(component).popBestEdge(best);
} | [
"public",
"Optional",
"<",
"ExclusiveEdge",
">",
"popBestEdge",
"(",
"Node",
"component",
",",
"Arborescence",
"<",
"Node",
">",
"best",
")",
"{",
"if",
"(",
"!",
"queueByDestination",
".",
"containsKey",
"(",
"component",
")",
")",
"return",
"Optional",
".",
"empty",
"(",
")",
";",
"return",
"queueByDestination",
".",
"get",
"(",
"component",
")",
".",
"popBestEdge",
"(",
"best",
")",
";",
"}"
] | Always breaks ties in favor of edges in best | [
"Always",
"breaks",
"ties",
"in",
"favor",
"of",
"edges",
"in",
"best"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/gremlin/spanningtree/EdgeQueueMap.java#L114-L117 |
22,854 | graknlabs/grakn | server/src/graql/gremlin/RelationTypeInference.java | RelationTypeInference.inferRelationTypes | public static Set<Fragment> inferRelationTypes(TransactionOLTP tx, Set<Fragment> allFragments) {
Set<Fragment> inferredFragments = new HashSet<>();
Map<Variable, Type> labelVarTypeMap = getLabelVarTypeMap(tx, allFragments);
if (labelVarTypeMap.isEmpty()) return inferredFragments;
Multimap<Variable, Type> instanceVarTypeMap = getInstanceVarTypeMap(allFragments, labelVarTypeMap);
Multimap<Variable, Variable> relationRolePlayerMap = getRelationRolePlayerMap(allFragments, instanceVarTypeMap);
if (relationRolePlayerMap.isEmpty()) return inferredFragments;
// for each type, get all possible relation type it could be in
Multimap<Type, RelationType> relationMap = HashMultimap.create();
labelVarTypeMap.values().stream().distinct().forEach(
type -> addAllPossibleRelations(relationMap, type));
// inferred labels should be kept separately, even if they are already in allFragments set
Map<Label, Statement> inferredLabels = new HashMap<>();
relationRolePlayerMap.asMap().forEach((relationVar, rolePlayerVars) -> {
Set<Type> possibleRelationTypes = rolePlayerVars.stream()
.filter(instanceVarTypeMap::containsKey)
.map(rolePlayer -> getAllPossibleRelationTypes(
instanceVarTypeMap.get(rolePlayer), relationMap))
.reduce(Sets::intersection).orElse(Collections.emptySet());
//TODO: if possibleRelationTypes here is empty, the query will not match any data
if (possibleRelationTypes.size() == 1) {
Type relationType = possibleRelationTypes.iterator().next();
Label label = relationType.label();
// add label fragment if this label has not been inferred
if (!inferredLabels.containsKey(label)) {
Statement labelVar = var();
inferredLabels.put(label, labelVar);
Fragment labelFragment = Fragments.label(new TypeProperty(label.getValue()), labelVar.var(), ImmutableSet.of(label));
inferredFragments.add(labelFragment);
}
// finally, add inferred isa fragments
Statement labelVar = inferredLabels.get(label);
IsaProperty isaProperty = new IsaProperty(labelVar);
EquivalentFragmentSet isaEquivalentFragmentSet = EquivalentFragmentSets.isa(isaProperty,
relationVar, labelVar.var(), relationType.isImplicit());
inferredFragments.addAll(isaEquivalentFragmentSet.fragments());
}
});
return inferredFragments;
} | java | public static Set<Fragment> inferRelationTypes(TransactionOLTP tx, Set<Fragment> allFragments) {
Set<Fragment> inferredFragments = new HashSet<>();
Map<Variable, Type> labelVarTypeMap = getLabelVarTypeMap(tx, allFragments);
if (labelVarTypeMap.isEmpty()) return inferredFragments;
Multimap<Variable, Type> instanceVarTypeMap = getInstanceVarTypeMap(allFragments, labelVarTypeMap);
Multimap<Variable, Variable> relationRolePlayerMap = getRelationRolePlayerMap(allFragments, instanceVarTypeMap);
if (relationRolePlayerMap.isEmpty()) return inferredFragments;
// for each type, get all possible relation type it could be in
Multimap<Type, RelationType> relationMap = HashMultimap.create();
labelVarTypeMap.values().stream().distinct().forEach(
type -> addAllPossibleRelations(relationMap, type));
// inferred labels should be kept separately, even if they are already in allFragments set
Map<Label, Statement> inferredLabels = new HashMap<>();
relationRolePlayerMap.asMap().forEach((relationVar, rolePlayerVars) -> {
Set<Type> possibleRelationTypes = rolePlayerVars.stream()
.filter(instanceVarTypeMap::containsKey)
.map(rolePlayer -> getAllPossibleRelationTypes(
instanceVarTypeMap.get(rolePlayer), relationMap))
.reduce(Sets::intersection).orElse(Collections.emptySet());
//TODO: if possibleRelationTypes here is empty, the query will not match any data
if (possibleRelationTypes.size() == 1) {
Type relationType = possibleRelationTypes.iterator().next();
Label label = relationType.label();
// add label fragment if this label has not been inferred
if (!inferredLabels.containsKey(label)) {
Statement labelVar = var();
inferredLabels.put(label, labelVar);
Fragment labelFragment = Fragments.label(new TypeProperty(label.getValue()), labelVar.var(), ImmutableSet.of(label));
inferredFragments.add(labelFragment);
}
// finally, add inferred isa fragments
Statement labelVar = inferredLabels.get(label);
IsaProperty isaProperty = new IsaProperty(labelVar);
EquivalentFragmentSet isaEquivalentFragmentSet = EquivalentFragmentSets.isa(isaProperty,
relationVar, labelVar.var(), relationType.isImplicit());
inferredFragments.addAll(isaEquivalentFragmentSet.fragments());
}
});
return inferredFragments;
} | [
"public",
"static",
"Set",
"<",
"Fragment",
">",
"inferRelationTypes",
"(",
"TransactionOLTP",
"tx",
",",
"Set",
"<",
"Fragment",
">",
"allFragments",
")",
"{",
"Set",
"<",
"Fragment",
">",
"inferredFragments",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"Map",
"<",
"Variable",
",",
"Type",
">",
"labelVarTypeMap",
"=",
"getLabelVarTypeMap",
"(",
"tx",
",",
"allFragments",
")",
";",
"if",
"(",
"labelVarTypeMap",
".",
"isEmpty",
"(",
")",
")",
"return",
"inferredFragments",
";",
"Multimap",
"<",
"Variable",
",",
"Type",
">",
"instanceVarTypeMap",
"=",
"getInstanceVarTypeMap",
"(",
"allFragments",
",",
"labelVarTypeMap",
")",
";",
"Multimap",
"<",
"Variable",
",",
"Variable",
">",
"relationRolePlayerMap",
"=",
"getRelationRolePlayerMap",
"(",
"allFragments",
",",
"instanceVarTypeMap",
")",
";",
"if",
"(",
"relationRolePlayerMap",
".",
"isEmpty",
"(",
")",
")",
"return",
"inferredFragments",
";",
"// for each type, get all possible relation type it could be in",
"Multimap",
"<",
"Type",
",",
"RelationType",
">",
"relationMap",
"=",
"HashMultimap",
".",
"create",
"(",
")",
";",
"labelVarTypeMap",
".",
"values",
"(",
")",
".",
"stream",
"(",
")",
".",
"distinct",
"(",
")",
".",
"forEach",
"(",
"type",
"->",
"addAllPossibleRelations",
"(",
"relationMap",
",",
"type",
")",
")",
";",
"// inferred labels should be kept separately, even if they are already in allFragments set",
"Map",
"<",
"Label",
",",
"Statement",
">",
"inferredLabels",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"relationRolePlayerMap",
".",
"asMap",
"(",
")",
".",
"forEach",
"(",
"(",
"relationVar",
",",
"rolePlayerVars",
")",
"->",
"{",
"Set",
"<",
"Type",
">",
"possibleRelationTypes",
"=",
"rolePlayerVars",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"instanceVarTypeMap",
"::",
"containsKey",
")",
".",
"map",
"(",
"rolePlayer",
"->",
"getAllPossibleRelationTypes",
"(",
"instanceVarTypeMap",
".",
"get",
"(",
"rolePlayer",
")",
",",
"relationMap",
")",
")",
".",
"reduce",
"(",
"Sets",
"::",
"intersection",
")",
".",
"orElse",
"(",
"Collections",
".",
"emptySet",
"(",
")",
")",
";",
"//TODO: if possibleRelationTypes here is empty, the query will not match any data",
"if",
"(",
"possibleRelationTypes",
".",
"size",
"(",
")",
"==",
"1",
")",
"{",
"Type",
"relationType",
"=",
"possibleRelationTypes",
".",
"iterator",
"(",
")",
".",
"next",
"(",
")",
";",
"Label",
"label",
"=",
"relationType",
".",
"label",
"(",
")",
";",
"// add label fragment if this label has not been inferred",
"if",
"(",
"!",
"inferredLabels",
".",
"containsKey",
"(",
"label",
")",
")",
"{",
"Statement",
"labelVar",
"=",
"var",
"(",
")",
";",
"inferredLabels",
".",
"put",
"(",
"label",
",",
"labelVar",
")",
";",
"Fragment",
"labelFragment",
"=",
"Fragments",
".",
"label",
"(",
"new",
"TypeProperty",
"(",
"label",
".",
"getValue",
"(",
")",
")",
",",
"labelVar",
".",
"var",
"(",
")",
",",
"ImmutableSet",
".",
"of",
"(",
"label",
")",
")",
";",
"inferredFragments",
".",
"add",
"(",
"labelFragment",
")",
";",
"}",
"// finally, add inferred isa fragments",
"Statement",
"labelVar",
"=",
"inferredLabels",
".",
"get",
"(",
"label",
")",
";",
"IsaProperty",
"isaProperty",
"=",
"new",
"IsaProperty",
"(",
"labelVar",
")",
";",
"EquivalentFragmentSet",
"isaEquivalentFragmentSet",
"=",
"EquivalentFragmentSets",
".",
"isa",
"(",
"isaProperty",
",",
"relationVar",
",",
"labelVar",
".",
"var",
"(",
")",
",",
"relationType",
".",
"isImplicit",
"(",
")",
")",
";",
"inferredFragments",
".",
"addAll",
"(",
"isaEquivalentFragmentSet",
".",
"fragments",
"(",
")",
")",
";",
"}",
"}",
")",
";",
"return",
"inferredFragments",
";",
"}"
] | add label fragment and isa fragment if we can infer any | [
"add",
"label",
"fragment",
"and",
"isa",
"fragment",
"if",
"we",
"can",
"infer",
"any"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/gremlin/RelationTypeInference.java#L56-L107 |
22,855 | graknlabs/grakn | server/src/graql/gremlin/RelationTypeInference.java | RelationTypeInference.getInstanceVarTypeMap | private static Multimap<Variable, Type> getInstanceVarTypeMap(
Set<Fragment> allFragments, Map<Variable, Type> labelVarTypeMap) {
Multimap<Variable, Type> instanceVarTypeMap = HashMultimap.create();
int oldSize;
do {
oldSize = instanceVarTypeMap.size();
allFragments.stream()
.filter(fragment -> labelVarTypeMap.containsKey(fragment.start())) // restrict to types
.filter(fragment -> fragment instanceof InIsaFragment || fragment instanceof InSubFragment) //
.forEach(fragment -> instanceVarTypeMap.put(fragment.end(), labelVarTypeMap.get(fragment.start())));
} while (oldSize != instanceVarTypeMap.size());
return instanceVarTypeMap;
} | java | private static Multimap<Variable, Type> getInstanceVarTypeMap(
Set<Fragment> allFragments, Map<Variable, Type> labelVarTypeMap) {
Multimap<Variable, Type> instanceVarTypeMap = HashMultimap.create();
int oldSize;
do {
oldSize = instanceVarTypeMap.size();
allFragments.stream()
.filter(fragment -> labelVarTypeMap.containsKey(fragment.start())) // restrict to types
.filter(fragment -> fragment instanceof InIsaFragment || fragment instanceof InSubFragment) //
.forEach(fragment -> instanceVarTypeMap.put(fragment.end(), labelVarTypeMap.get(fragment.start())));
} while (oldSize != instanceVarTypeMap.size());
return instanceVarTypeMap;
} | [
"private",
"static",
"Multimap",
"<",
"Variable",
",",
"Type",
">",
"getInstanceVarTypeMap",
"(",
"Set",
"<",
"Fragment",
">",
"allFragments",
",",
"Map",
"<",
"Variable",
",",
"Type",
">",
"labelVarTypeMap",
")",
"{",
"Multimap",
"<",
"Variable",
",",
"Type",
">",
"instanceVarTypeMap",
"=",
"HashMultimap",
".",
"create",
"(",
")",
";",
"int",
"oldSize",
";",
"do",
"{",
"oldSize",
"=",
"instanceVarTypeMap",
".",
"size",
"(",
")",
";",
"allFragments",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"fragment",
"->",
"labelVarTypeMap",
".",
"containsKey",
"(",
"fragment",
".",
"start",
"(",
")",
")",
")",
"// restrict to types",
".",
"filter",
"(",
"fragment",
"->",
"fragment",
"instanceof",
"InIsaFragment",
"||",
"fragment",
"instanceof",
"InSubFragment",
")",
"//",
".",
"forEach",
"(",
"fragment",
"->",
"instanceVarTypeMap",
".",
"put",
"(",
"fragment",
".",
"end",
"(",
")",
",",
"labelVarTypeMap",
".",
"get",
"(",
"fragment",
".",
"start",
"(",
")",
")",
")",
")",
";",
"}",
"while",
"(",
"oldSize",
"!=",
"instanceVarTypeMap",
".",
"size",
"(",
")",
")",
";",
"return",
"instanceVarTypeMap",
";",
"}"
] | find all vars with direct or indirect out isa edges | [
"find",
"all",
"vars",
"with",
"direct",
"or",
"indirect",
"out",
"isa",
"edges"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/gremlin/RelationTypeInference.java#L110-L122 |
22,856 | graknlabs/grakn | server/src/graql/gremlin/RelationTypeInference.java | RelationTypeInference.getLabelVarTypeMap | private static Map<Variable, Type> getLabelVarTypeMap(TransactionOLTP tx, Set<Fragment> allFragments) {
Map<Variable, Type> labelVarTypeMap = new HashMap<>();
allFragments.stream()
.filter(LabelFragment.class::isInstance)
.forEach(fragment -> {
// TODO: labels() should return ONE label instead of a set
SchemaConcept schemaConcept = tx.getSchemaConcept(
Iterators.getOnlyElement(((LabelFragment) fragment).labels().iterator()));
if (schemaConcept != null && !schemaConcept.isRole() && !schemaConcept.isRule()) {
labelVarTypeMap.put(fragment.start(), schemaConcept.asType());
}
});
return labelVarTypeMap;
} | java | private static Map<Variable, Type> getLabelVarTypeMap(TransactionOLTP tx, Set<Fragment> allFragments) {
Map<Variable, Type> labelVarTypeMap = new HashMap<>();
allFragments.stream()
.filter(LabelFragment.class::isInstance)
.forEach(fragment -> {
// TODO: labels() should return ONE label instead of a set
SchemaConcept schemaConcept = tx.getSchemaConcept(
Iterators.getOnlyElement(((LabelFragment) fragment).labels().iterator()));
if (schemaConcept != null && !schemaConcept.isRole() && !schemaConcept.isRule()) {
labelVarTypeMap.put(fragment.start(), schemaConcept.asType());
}
});
return labelVarTypeMap;
} | [
"private",
"static",
"Map",
"<",
"Variable",
",",
"Type",
">",
"getLabelVarTypeMap",
"(",
"TransactionOLTP",
"tx",
",",
"Set",
"<",
"Fragment",
">",
"allFragments",
")",
"{",
"Map",
"<",
"Variable",
",",
"Type",
">",
"labelVarTypeMap",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"allFragments",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"LabelFragment",
".",
"class",
"::",
"isInstance",
")",
".",
"forEach",
"(",
"fragment",
"->",
"{",
"// TODO: labels() should return ONE label instead of a set",
"SchemaConcept",
"schemaConcept",
"=",
"tx",
".",
"getSchemaConcept",
"(",
"Iterators",
".",
"getOnlyElement",
"(",
"(",
"(",
"LabelFragment",
")",
"fragment",
")",
".",
"labels",
"(",
")",
".",
"iterator",
"(",
")",
")",
")",
";",
"if",
"(",
"schemaConcept",
"!=",
"null",
"&&",
"!",
"schemaConcept",
".",
"isRole",
"(",
")",
"&&",
"!",
"schemaConcept",
".",
"isRule",
"(",
")",
")",
"{",
"labelVarTypeMap",
".",
"put",
"(",
"fragment",
".",
"start",
"(",
")",
",",
"schemaConcept",
".",
"asType",
"(",
")",
")",
";",
"}",
"}",
")",
";",
"return",
"labelVarTypeMap",
";",
"}"
] | find all vars representing types | [
"find",
"all",
"vars",
"representing",
"types"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/gremlin/RelationTypeInference.java#L125-L138 |
22,857 | graknlabs/grakn | server/src/server/kb/concept/TypeImpl.java | TypeImpl.addInstance | V addInstance(Schema.BaseType instanceBaseType, BiFunction<VertexElement, T, V> producer, boolean isInferred) {
preCheckForInstanceCreation();
if (isAbstract()) throw TransactionException.addingInstancesToAbstractType(this);
VertexElement instanceVertex = vertex().tx().addVertexElement(instanceBaseType);
vertex().tx().ruleCache().ackTypeInstance(this);
if (!Schema.MetaSchema.isMetaLabel(label())) {
vertex().tx().cache().addedInstance(id());
if (isInferred) instanceVertex.property(Schema.VertexProperty.IS_INFERRED, true);
}
V instance = producer.apply(instanceVertex, getThis());
assert instance != null : "producer should never return null";
return instance;
} | java | V addInstance(Schema.BaseType instanceBaseType, BiFunction<VertexElement, T, V> producer, boolean isInferred) {
preCheckForInstanceCreation();
if (isAbstract()) throw TransactionException.addingInstancesToAbstractType(this);
VertexElement instanceVertex = vertex().tx().addVertexElement(instanceBaseType);
vertex().tx().ruleCache().ackTypeInstance(this);
if (!Schema.MetaSchema.isMetaLabel(label())) {
vertex().tx().cache().addedInstance(id());
if (isInferred) instanceVertex.property(Schema.VertexProperty.IS_INFERRED, true);
}
V instance = producer.apply(instanceVertex, getThis());
assert instance != null : "producer should never return null";
return instance;
} | [
"V",
"addInstance",
"(",
"Schema",
".",
"BaseType",
"instanceBaseType",
",",
"BiFunction",
"<",
"VertexElement",
",",
"T",
",",
"V",
">",
"producer",
",",
"boolean",
"isInferred",
")",
"{",
"preCheckForInstanceCreation",
"(",
")",
";",
"if",
"(",
"isAbstract",
"(",
")",
")",
"throw",
"TransactionException",
".",
"addingInstancesToAbstractType",
"(",
"this",
")",
";",
"VertexElement",
"instanceVertex",
"=",
"vertex",
"(",
")",
".",
"tx",
"(",
")",
".",
"addVertexElement",
"(",
"instanceBaseType",
")",
";",
"vertex",
"(",
")",
".",
"tx",
"(",
")",
".",
"ruleCache",
"(",
")",
".",
"ackTypeInstance",
"(",
"this",
")",
";",
"if",
"(",
"!",
"Schema",
".",
"MetaSchema",
".",
"isMetaLabel",
"(",
"label",
"(",
")",
")",
")",
"{",
"vertex",
"(",
")",
".",
"tx",
"(",
")",
".",
"cache",
"(",
")",
".",
"addedInstance",
"(",
"id",
"(",
")",
")",
";",
"if",
"(",
"isInferred",
")",
"instanceVertex",
".",
"property",
"(",
"Schema",
".",
"VertexProperty",
".",
"IS_INFERRED",
",",
"true",
")",
";",
"}",
"V",
"instance",
"=",
"producer",
".",
"apply",
"(",
"instanceVertex",
",",
"getThis",
"(",
")",
")",
";",
"assert",
"instance",
"!=",
"null",
":",
"\"producer should never return null\"",
";",
"return",
"instance",
";",
"}"
] | Utility method used to create an instance of this type
@param instanceBaseType The base type of the instances of this type
@param producer The factory method to produce the instance
@return A new instance | [
"Utility",
"method",
"used",
"to",
"create",
"an",
"instance",
"of",
"this",
"type"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/kb/concept/TypeImpl.java#L92-L108 |
22,858 | graknlabs/grakn | server/src/server/kb/concept/TypeImpl.java | TypeImpl.delete | @Override
public void delete() {
//If the deletion is successful we will need to update the cache of linked concepts. To do this caches must be loaded
Map<Role, Boolean> plays = cachedDirectPlays.get();
super.delete();
//Updated caches of linked types
plays.keySet().forEach(roleType -> ((RoleImpl) roleType).deleteCachedDirectPlaysByType(getThis()));
} | java | @Override
public void delete() {
//If the deletion is successful we will need to update the cache of linked concepts. To do this caches must be loaded
Map<Role, Boolean> plays = cachedDirectPlays.get();
super.delete();
//Updated caches of linked types
plays.keySet().forEach(roleType -> ((RoleImpl) roleType).deleteCachedDirectPlaysByType(getThis()));
} | [
"@",
"Override",
"public",
"void",
"delete",
"(",
")",
"{",
"//If the deletion is successful we will need to update the cache of linked concepts. To do this caches must be loaded",
"Map",
"<",
"Role",
",",
"Boolean",
">",
"plays",
"=",
"cachedDirectPlays",
".",
"get",
"(",
")",
";",
"super",
".",
"delete",
"(",
")",
";",
"//Updated caches of linked types",
"plays",
".",
"keySet",
"(",
")",
".",
"forEach",
"(",
"roleType",
"->",
"(",
"(",
"RoleImpl",
")",
"roleType",
")",
".",
"deleteCachedDirectPlaysByType",
"(",
"getThis",
"(",
")",
")",
")",
";",
"}"
] | Deletes the concept as type | [
"Deletes",
"the",
"concept",
"as",
"type"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/kb/concept/TypeImpl.java#L170-L180 |
22,859 | graknlabs/grakn | server/src/server/kb/concept/TypeImpl.java | TypeImpl.has | private T has(AttributeType attributeType, Schema.ImplicitType has, Schema.ImplicitType hasValue, Schema.ImplicitType hasOwner, boolean required) {
Label attributeLabel = attributeType.label();
Role ownerRole = vertex().tx().putRoleTypeImplicit(hasOwner.getLabel(attributeLabel));
Role valueRole = vertex().tx().putRoleTypeImplicit(hasValue.getLabel(attributeLabel));
RelationType relationType = vertex().tx().putRelationTypeImplicit(has.getLabel(attributeLabel)).
relates(ownerRole).
relates(valueRole);
//this plays ownerRole;
this.play(ownerRole, required);
//TODO: Use explicit cardinality of 0-1 rather than just false
//attributeType plays valueRole;
((AttributeTypeImpl) attributeType).play(valueRole, false);
updateAttributeRelationHierarchy(attributeType, has, hasValue, hasOwner, ownerRole, valueRole, relationType);
return getThis();
} | java | private T has(AttributeType attributeType, Schema.ImplicitType has, Schema.ImplicitType hasValue, Schema.ImplicitType hasOwner, boolean required) {
Label attributeLabel = attributeType.label();
Role ownerRole = vertex().tx().putRoleTypeImplicit(hasOwner.getLabel(attributeLabel));
Role valueRole = vertex().tx().putRoleTypeImplicit(hasValue.getLabel(attributeLabel));
RelationType relationType = vertex().tx().putRelationTypeImplicit(has.getLabel(attributeLabel)).
relates(ownerRole).
relates(valueRole);
//this plays ownerRole;
this.play(ownerRole, required);
//TODO: Use explicit cardinality of 0-1 rather than just false
//attributeType plays valueRole;
((AttributeTypeImpl) attributeType).play(valueRole, false);
updateAttributeRelationHierarchy(attributeType, has, hasValue, hasOwner, ownerRole, valueRole, relationType);
return getThis();
} | [
"private",
"T",
"has",
"(",
"AttributeType",
"attributeType",
",",
"Schema",
".",
"ImplicitType",
"has",
",",
"Schema",
".",
"ImplicitType",
"hasValue",
",",
"Schema",
".",
"ImplicitType",
"hasOwner",
",",
"boolean",
"required",
")",
"{",
"Label",
"attributeLabel",
"=",
"attributeType",
".",
"label",
"(",
")",
";",
"Role",
"ownerRole",
"=",
"vertex",
"(",
")",
".",
"tx",
"(",
")",
".",
"putRoleTypeImplicit",
"(",
"hasOwner",
".",
"getLabel",
"(",
"attributeLabel",
")",
")",
";",
"Role",
"valueRole",
"=",
"vertex",
"(",
")",
".",
"tx",
"(",
")",
".",
"putRoleTypeImplicit",
"(",
"hasValue",
".",
"getLabel",
"(",
"attributeLabel",
")",
")",
";",
"RelationType",
"relationType",
"=",
"vertex",
"(",
")",
".",
"tx",
"(",
")",
".",
"putRelationTypeImplicit",
"(",
"has",
".",
"getLabel",
"(",
"attributeLabel",
")",
")",
".",
"relates",
"(",
"ownerRole",
")",
".",
"relates",
"(",
"valueRole",
")",
";",
"//this plays ownerRole;",
"this",
".",
"play",
"(",
"ownerRole",
",",
"required",
")",
";",
"//TODO: Use explicit cardinality of 0-1 rather than just false",
"//attributeType plays valueRole;",
"(",
"(",
"AttributeTypeImpl",
")",
"attributeType",
")",
".",
"play",
"(",
"valueRole",
",",
"false",
")",
";",
"updateAttributeRelationHierarchy",
"(",
"attributeType",
",",
"has",
",",
"hasValue",
",",
"hasOwner",
",",
"ownerRole",
",",
"valueRole",
",",
"relationType",
")",
";",
"return",
"getThis",
"(",
")",
";",
"}"
] | Creates a relation type which allows this type and a Attribute type to be linked.
@param attributeType The AttributeType which instances of this type should be allowed to play.
@param has the implicit relation type to build
@param hasValue the implicit role type to build for the AttributeType
@param hasOwner the implicit role type to build for the type
@param required Indicates if the Attribute is required on the entity
@return The Type itself | [
"Creates",
"a",
"relation",
"type",
"which",
"allows",
"this",
"type",
"and",
"a",
"Attribute",
"type",
"to",
"be",
"linked",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/kb/concept/TypeImpl.java#L402-L419 |
22,860 | graknlabs/grakn | server/src/server/kb/concept/TypeImpl.java | TypeImpl.checkNonOverlapOfImplicitRelations | private void checkNonOverlapOfImplicitRelations(Schema.ImplicitType implicitType, AttributeType attributeType) {
if (attributes(implicitType).anyMatch(rt -> rt.equals(attributeType))) {
throw TransactionException.duplicateHas(this, attributeType);
}
} | java | private void checkNonOverlapOfImplicitRelations(Schema.ImplicitType implicitType, AttributeType attributeType) {
if (attributes(implicitType).anyMatch(rt -> rt.equals(attributeType))) {
throw TransactionException.duplicateHas(this, attributeType);
}
} | [
"private",
"void",
"checkNonOverlapOfImplicitRelations",
"(",
"Schema",
".",
"ImplicitType",
"implicitType",
",",
"AttributeType",
"attributeType",
")",
"{",
"if",
"(",
"attributes",
"(",
"implicitType",
")",
".",
"anyMatch",
"(",
"rt",
"->",
"rt",
".",
"equals",
"(",
"attributeType",
")",
")",
")",
"{",
"throw",
"TransactionException",
".",
"duplicateHas",
"(",
"this",
",",
"attributeType",
")",
";",
"}",
"}"
] | Checks if the provided AttributeType is already used in an other implicit relation.
@param implicitType The implicit relation to check against.
@param attributeType The AttributeType which should not be in that implicit relation
@throws TransactionException when the AttributeType is already used in another implicit relation | [
"Checks",
"if",
"the",
"provided",
"AttributeType",
"is",
"already",
"used",
"in",
"an",
"other",
"implicit",
"relation",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/kb/concept/TypeImpl.java#L453-L457 |
22,861 | graknlabs/grakn | server/src/server/exception/InvalidKBException.java | InvalidKBException.validationErrors | public static InvalidKBException validationErrors(List<String> errors){
StringBuilder message = new StringBuilder();
message.append(ErrorMessage.VALIDATION.getMessage(errors.size()));
for (String s : errors) {
message.append(s);
}
return create(message.toString());
} | java | public static InvalidKBException validationErrors(List<String> errors){
StringBuilder message = new StringBuilder();
message.append(ErrorMessage.VALIDATION.getMessage(errors.size()));
for (String s : errors) {
message.append(s);
}
return create(message.toString());
} | [
"public",
"static",
"InvalidKBException",
"validationErrors",
"(",
"List",
"<",
"String",
">",
"errors",
")",
"{",
"StringBuilder",
"message",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"message",
".",
"append",
"(",
"ErrorMessage",
".",
"VALIDATION",
".",
"getMessage",
"(",
"errors",
".",
"size",
"(",
")",
")",
")",
";",
"for",
"(",
"String",
"s",
":",
"errors",
")",
"{",
"message",
".",
"append",
"(",
"s",
")",
";",
"}",
"return",
"create",
"(",
"message",
".",
"toString",
"(",
")",
")",
";",
"}"
] | Thrown on commit when validation errors are found | [
"Thrown",
"on",
"commit",
"when",
"validation",
"errors",
"are",
"found"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/exception/InvalidKBException.java#L59-L66 |
22,862 | graknlabs/grakn | server/src/server/kb/cache/Cache.java | Cache.get | @Nullable
public V get() {
if (!valueRetrieved) {
cacheValue = databaseReader.get();
valueRetrieved = true;
}
return cacheValue;
} | java | @Nullable
public V get() {
if (!valueRetrieved) {
cacheValue = databaseReader.get();
valueRetrieved = true;
}
return cacheValue;
} | [
"@",
"Nullable",
"public",
"V",
"get",
"(",
")",
"{",
"if",
"(",
"!",
"valueRetrieved",
")",
"{",
"cacheValue",
"=",
"databaseReader",
".",
"get",
"(",
")",
";",
"valueRetrieved",
"=",
"true",
";",
"}",
"return",
"cacheValue",
";",
"}"
] | Retrieves the object in the cache. If nothing is cached the database is read.
@return The cached object. | [
"Retrieves",
"the",
"object",
"in",
"the",
"cache",
".",
"If",
"nothing",
"is",
"cached",
"the",
"database",
"is",
"read",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/kb/cache/Cache.java#L49-L56 |
22,863 | graknlabs/grakn | server/src/server/session/SessionImpl.java | SessionImpl.initialiseMetaConcepts | private void initialiseMetaConcepts(TransactionOLTP tx) {
VertexElement type = tx.addTypeVertex(Schema.MetaSchema.THING.getId(), Schema.MetaSchema.THING.getLabel(), Schema.BaseType.TYPE);
VertexElement entityType = tx.addTypeVertex(Schema.MetaSchema.ENTITY.getId(), Schema.MetaSchema.ENTITY.getLabel(), Schema.BaseType.ENTITY_TYPE);
VertexElement relationType = tx.addTypeVertex(Schema.MetaSchema.RELATION.getId(), Schema.MetaSchema.RELATION.getLabel(), Schema.BaseType.RELATION_TYPE);
VertexElement resourceType = tx.addTypeVertex(Schema.MetaSchema.ATTRIBUTE.getId(), Schema.MetaSchema.ATTRIBUTE.getLabel(), Schema.BaseType.ATTRIBUTE_TYPE);
tx.addTypeVertex(Schema.MetaSchema.ROLE.getId(), Schema.MetaSchema.ROLE.getLabel(), Schema.BaseType.ROLE);
tx.addTypeVertex(Schema.MetaSchema.RULE.getId(), Schema.MetaSchema.RULE.getLabel(), Schema.BaseType.RULE);
relationType.property(Schema.VertexProperty.IS_ABSTRACT, true);
resourceType.property(Schema.VertexProperty.IS_ABSTRACT, true);
entityType.property(Schema.VertexProperty.IS_ABSTRACT, true);
relationType.addEdge(type, Schema.EdgeLabel.SUB);
resourceType.addEdge(type, Schema.EdgeLabel.SUB);
entityType.addEdge(type, Schema.EdgeLabel.SUB);
} | java | private void initialiseMetaConcepts(TransactionOLTP tx) {
VertexElement type = tx.addTypeVertex(Schema.MetaSchema.THING.getId(), Schema.MetaSchema.THING.getLabel(), Schema.BaseType.TYPE);
VertexElement entityType = tx.addTypeVertex(Schema.MetaSchema.ENTITY.getId(), Schema.MetaSchema.ENTITY.getLabel(), Schema.BaseType.ENTITY_TYPE);
VertexElement relationType = tx.addTypeVertex(Schema.MetaSchema.RELATION.getId(), Schema.MetaSchema.RELATION.getLabel(), Schema.BaseType.RELATION_TYPE);
VertexElement resourceType = tx.addTypeVertex(Schema.MetaSchema.ATTRIBUTE.getId(), Schema.MetaSchema.ATTRIBUTE.getLabel(), Schema.BaseType.ATTRIBUTE_TYPE);
tx.addTypeVertex(Schema.MetaSchema.ROLE.getId(), Schema.MetaSchema.ROLE.getLabel(), Schema.BaseType.ROLE);
tx.addTypeVertex(Schema.MetaSchema.RULE.getId(), Schema.MetaSchema.RULE.getLabel(), Schema.BaseType.RULE);
relationType.property(Schema.VertexProperty.IS_ABSTRACT, true);
resourceType.property(Schema.VertexProperty.IS_ABSTRACT, true);
entityType.property(Schema.VertexProperty.IS_ABSTRACT, true);
relationType.addEdge(type, Schema.EdgeLabel.SUB);
resourceType.addEdge(type, Schema.EdgeLabel.SUB);
entityType.addEdge(type, Schema.EdgeLabel.SUB);
} | [
"private",
"void",
"initialiseMetaConcepts",
"(",
"TransactionOLTP",
"tx",
")",
"{",
"VertexElement",
"type",
"=",
"tx",
".",
"addTypeVertex",
"(",
"Schema",
".",
"MetaSchema",
".",
"THING",
".",
"getId",
"(",
")",
",",
"Schema",
".",
"MetaSchema",
".",
"THING",
".",
"getLabel",
"(",
")",
",",
"Schema",
".",
"BaseType",
".",
"TYPE",
")",
";",
"VertexElement",
"entityType",
"=",
"tx",
".",
"addTypeVertex",
"(",
"Schema",
".",
"MetaSchema",
".",
"ENTITY",
".",
"getId",
"(",
")",
",",
"Schema",
".",
"MetaSchema",
".",
"ENTITY",
".",
"getLabel",
"(",
")",
",",
"Schema",
".",
"BaseType",
".",
"ENTITY_TYPE",
")",
";",
"VertexElement",
"relationType",
"=",
"tx",
".",
"addTypeVertex",
"(",
"Schema",
".",
"MetaSchema",
".",
"RELATION",
".",
"getId",
"(",
")",
",",
"Schema",
".",
"MetaSchema",
".",
"RELATION",
".",
"getLabel",
"(",
")",
",",
"Schema",
".",
"BaseType",
".",
"RELATION_TYPE",
")",
";",
"VertexElement",
"resourceType",
"=",
"tx",
".",
"addTypeVertex",
"(",
"Schema",
".",
"MetaSchema",
".",
"ATTRIBUTE",
".",
"getId",
"(",
")",
",",
"Schema",
".",
"MetaSchema",
".",
"ATTRIBUTE",
".",
"getLabel",
"(",
")",
",",
"Schema",
".",
"BaseType",
".",
"ATTRIBUTE_TYPE",
")",
";",
"tx",
".",
"addTypeVertex",
"(",
"Schema",
".",
"MetaSchema",
".",
"ROLE",
".",
"getId",
"(",
")",
",",
"Schema",
".",
"MetaSchema",
".",
"ROLE",
".",
"getLabel",
"(",
")",
",",
"Schema",
".",
"BaseType",
".",
"ROLE",
")",
";",
"tx",
".",
"addTypeVertex",
"(",
"Schema",
".",
"MetaSchema",
".",
"RULE",
".",
"getId",
"(",
")",
",",
"Schema",
".",
"MetaSchema",
".",
"RULE",
".",
"getLabel",
"(",
")",
",",
"Schema",
".",
"BaseType",
".",
"RULE",
")",
";",
"relationType",
".",
"property",
"(",
"Schema",
".",
"VertexProperty",
".",
"IS_ABSTRACT",
",",
"true",
")",
";",
"resourceType",
".",
"property",
"(",
"Schema",
".",
"VertexProperty",
".",
"IS_ABSTRACT",
",",
"true",
")",
";",
"entityType",
".",
"property",
"(",
"Schema",
".",
"VertexProperty",
".",
"IS_ABSTRACT",
",",
"true",
")",
";",
"relationType",
".",
"addEdge",
"(",
"type",
",",
"Schema",
".",
"EdgeLabel",
".",
"SUB",
")",
";",
"resourceType",
".",
"addEdge",
"(",
"type",
",",
"Schema",
".",
"EdgeLabel",
".",
"SUB",
")",
";",
"entityType",
".",
"addEdge",
"(",
"type",
",",
"Schema",
".",
"EdgeLabel",
".",
"SUB",
")",
";",
"}"
] | This creates the first meta schema in an empty keyspace which has not been initialised yet
@param tx | [
"This",
"creates",
"the",
"first",
"meta",
"schema",
"in",
"an",
"empty",
"keyspace",
"which",
"has",
"not",
"been",
"initialised",
"yet"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/session/SessionImpl.java#L138-L153 |
22,864 | graknlabs/grakn | server/src/server/session/SessionImpl.java | SessionImpl.copySchemaConceptLabelsToKeyspaceCache | private void copySchemaConceptLabelsToKeyspaceCache(TransactionOLTP tx) {
copyToCache(tx.getMetaConcept());
copyToCache(tx.getMetaRole());
copyToCache(tx.getMetaRule());
} | java | private void copySchemaConceptLabelsToKeyspaceCache(TransactionOLTP tx) {
copyToCache(tx.getMetaConcept());
copyToCache(tx.getMetaRole());
copyToCache(tx.getMetaRule());
} | [
"private",
"void",
"copySchemaConceptLabelsToKeyspaceCache",
"(",
"TransactionOLTP",
"tx",
")",
"{",
"copyToCache",
"(",
"tx",
".",
"getMetaConcept",
"(",
")",
")",
";",
"copyToCache",
"(",
"tx",
".",
"getMetaRole",
"(",
")",
")",
";",
"copyToCache",
"(",
"tx",
".",
"getMetaRule",
"(",
")",
")",
";",
"}"
] | Copy schema concepts labels to current KeyspaceCache
@param tx | [
"Copy",
"schema",
"concepts",
"labels",
"to",
"current",
"KeyspaceCache"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/session/SessionImpl.java#L160-L164 |
22,865 | graknlabs/grakn | server/src/server/session/SessionImpl.java | SessionImpl.copyToCache | private void copyToCache(SchemaConcept schemaConcept) {
schemaConcept.subs().forEach(concept -> keyspaceCache.cacheLabel(concept.label(), concept.labelId()));
} | java | private void copyToCache(SchemaConcept schemaConcept) {
schemaConcept.subs().forEach(concept -> keyspaceCache.cacheLabel(concept.label(), concept.labelId()));
} | [
"private",
"void",
"copyToCache",
"(",
"SchemaConcept",
"schemaConcept",
")",
"{",
"schemaConcept",
".",
"subs",
"(",
")",
".",
"forEach",
"(",
"concept",
"->",
"keyspaceCache",
".",
"cacheLabel",
"(",
"concept",
".",
"label",
"(",
")",
",",
"concept",
".",
"labelId",
"(",
")",
")",
")",
";",
"}"
] | Copy schema concept and all its subs labels to keyspace cache
@param schemaConcept | [
"Copy",
"schema",
"concept",
"and",
"all",
"its",
"subs",
"labels",
"to",
"keyspace",
"cache"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/session/SessionImpl.java#L179-L181 |
22,866 | graknlabs/grakn | server/src/server/session/SessionImpl.java | SessionImpl.close | @Override
public void close() {
if (isClosed) {
return;
}
TransactionOLTP localTx = localOLTPTransactionContainer.get();
if (localTx != null) {
localTx.close(ErrorMessage.SESSION_CLOSED.getMessage(keyspace()));
localOLTPTransactionContainer.set(null);
}
if (this.onClose != null) {
this.onClose.accept(this);
}
isClosed = true;
} | java | @Override
public void close() {
if (isClosed) {
return;
}
TransactionOLTP localTx = localOLTPTransactionContainer.get();
if (localTx != null) {
localTx.close(ErrorMessage.SESSION_CLOSED.getMessage(keyspace()));
localOLTPTransactionContainer.set(null);
}
if (this.onClose != null) {
this.onClose.accept(this);
}
isClosed = true;
} | [
"@",
"Override",
"public",
"void",
"close",
"(",
")",
"{",
"if",
"(",
"isClosed",
")",
"{",
"return",
";",
"}",
"TransactionOLTP",
"localTx",
"=",
"localOLTPTransactionContainer",
".",
"get",
"(",
")",
";",
"if",
"(",
"localTx",
"!=",
"null",
")",
"{",
"localTx",
".",
"close",
"(",
"ErrorMessage",
".",
"SESSION_CLOSED",
".",
"getMessage",
"(",
"keyspace",
"(",
")",
")",
")",
";",
"localOLTPTransactionContainer",
".",
"set",
"(",
"null",
")",
";",
"}",
"if",
"(",
"this",
".",
"onClose",
"!=",
"null",
")",
"{",
"this",
".",
"onClose",
".",
"accept",
"(",
"this",
")",
";",
"}",
"isClosed",
"=",
"true",
";",
"}"
] | Close JanusGraph, it will not be possible to create new transactions using current instance of Session.
This closes current session and local transaction, invoking callback function if one is set. | [
"Close",
"JanusGraph",
"it",
"will",
"not",
"be",
"possible",
"to",
"create",
"new",
"transactions",
"using",
"current",
"instance",
"of",
"Session",
".",
"This",
"closes",
"current",
"session",
"and",
"local",
"transaction",
"invoking",
"callback",
"function",
"if",
"one",
"is",
"set",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/session/SessionImpl.java#L226-L243 |
22,867 | graknlabs/grakn | server/src/server/session/computer/GraknSparkComputer.java | GraknSparkComputer.updateLocalConfiguration | private static void updateLocalConfiguration(final JavaSparkContext sparkContext,
final Configuration configuration) {
/*
* While we could enumerate over the entire SparkConfiguration and copy into the Thread
* Local properties of the Spark Context this could cause adverse effects with future
* versions of Spark. Since the api for setting multiple local properties at once is
* restricted as private, we will only set those properties we know can effect SparkGraphComputer
* Execution rather than applying the entire configuration.
*/
final String[] validPropertyNames = {
"spark.job.description",
"spark.jobGroup.id",
"spark.job.interruptOnCancel",
"spark.scheduler.pool"
};
for (String propertyName : validPropertyNames) {
String propertyValue = configuration.get(propertyName);
if (propertyValue != null) {
LOGGER.info("Setting Thread Local SparkContext Property - "
+ propertyName + " : " + propertyValue);
sparkContext.setLocalProperty(propertyName, configuration.get(propertyName));
}
}
} | java | private static void updateLocalConfiguration(final JavaSparkContext sparkContext,
final Configuration configuration) {
/*
* While we could enumerate over the entire SparkConfiguration and copy into the Thread
* Local properties of the Spark Context this could cause adverse effects with future
* versions of Spark. Since the api for setting multiple local properties at once is
* restricted as private, we will only set those properties we know can effect SparkGraphComputer
* Execution rather than applying the entire configuration.
*/
final String[] validPropertyNames = {
"spark.job.description",
"spark.jobGroup.id",
"spark.job.interruptOnCancel",
"spark.scheduler.pool"
};
for (String propertyName : validPropertyNames) {
String propertyValue = configuration.get(propertyName);
if (propertyValue != null) {
LOGGER.info("Setting Thread Local SparkContext Property - "
+ propertyName + " : " + propertyValue);
sparkContext.setLocalProperty(propertyName, configuration.get(propertyName));
}
}
} | [
"private",
"static",
"void",
"updateLocalConfiguration",
"(",
"final",
"JavaSparkContext",
"sparkContext",
",",
"final",
"Configuration",
"configuration",
")",
"{",
"/*\n * While we could enumerate over the entire SparkConfiguration and copy into the Thread\n * Local properties of the Spark Context this could cause adverse effects with future\n * versions of Spark. Since the api for setting multiple local properties at once is\n * restricted as private, we will only set those properties we know can effect SparkGraphComputer\n * Execution rather than applying the entire configuration.\n */",
"final",
"String",
"[",
"]",
"validPropertyNames",
"=",
"{",
"\"spark.job.description\"",
",",
"\"spark.jobGroup.id\"",
",",
"\"spark.job.interruptOnCancel\"",
",",
"\"spark.scheduler.pool\"",
"}",
";",
"for",
"(",
"String",
"propertyName",
":",
"validPropertyNames",
")",
"{",
"String",
"propertyValue",
"=",
"configuration",
".",
"get",
"(",
"propertyName",
")",
";",
"if",
"(",
"propertyValue",
"!=",
"null",
")",
"{",
"LOGGER",
".",
"info",
"(",
"\"Setting Thread Local SparkContext Property - \"",
"+",
"propertyName",
"+",
"\" : \"",
"+",
"propertyValue",
")",
";",
"sparkContext",
".",
"setLocalProperty",
"(",
"propertyName",
",",
"configuration",
".",
"get",
"(",
"propertyName",
")",
")",
";",
"}",
"}",
"}"
] | When using a persistent context the running Context's configuration will override a passed
in configuration. Spark allows us to override these inherited properties via
SparkContext.setLocalProperty | [
"When",
"using",
"a",
"persistent",
"context",
"the",
"running",
"Context",
"s",
"configuration",
"will",
"override",
"a",
"passed",
"in",
"configuration",
".",
"Spark",
"allows",
"us",
"to",
"override",
"these",
"inherited",
"properties",
"via",
"SparkContext",
".",
"setLocalProperty"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/session/computer/GraknSparkComputer.java#L549-L574 |
22,868 | graknlabs/grakn | server/src/server/keyspace/KeyspaceManager.java | KeyspaceManager.putKeyspace | public void putKeyspace(KeyspaceImpl keyspace) {
if (containsKeyspace(keyspace)) return;
try (TransactionOLTP tx = systemKeyspaceSession.transaction().write()) {
AttributeType<String> keyspaceName = tx.getSchemaConcept(KEYSPACE_RESOURCE);
if (keyspaceName == null) {
throw GraknServerException.initializationException(keyspace);
}
Attribute<String> attribute = keyspaceName.create(keyspace.name());
if (attribute.owner() == null) {
tx.<EntityType>getSchemaConcept(KEYSPACE_ENTITY).create().has(attribute);
}
tx.commit();
// add to cache
existingKeyspaces.add(keyspace);
} catch (InvalidKBException e) {
throw new RuntimeException("Could not add keyspace [" + keyspace + "] to system graph", e);
}
} | java | public void putKeyspace(KeyspaceImpl keyspace) {
if (containsKeyspace(keyspace)) return;
try (TransactionOLTP tx = systemKeyspaceSession.transaction().write()) {
AttributeType<String> keyspaceName = tx.getSchemaConcept(KEYSPACE_RESOURCE);
if (keyspaceName == null) {
throw GraknServerException.initializationException(keyspace);
}
Attribute<String> attribute = keyspaceName.create(keyspace.name());
if (attribute.owner() == null) {
tx.<EntityType>getSchemaConcept(KEYSPACE_ENTITY).create().has(attribute);
}
tx.commit();
// add to cache
existingKeyspaces.add(keyspace);
} catch (InvalidKBException e) {
throw new RuntimeException("Could not add keyspace [" + keyspace + "] to system graph", e);
}
} | [
"public",
"void",
"putKeyspace",
"(",
"KeyspaceImpl",
"keyspace",
")",
"{",
"if",
"(",
"containsKeyspace",
"(",
"keyspace",
")",
")",
"return",
";",
"try",
"(",
"TransactionOLTP",
"tx",
"=",
"systemKeyspaceSession",
".",
"transaction",
"(",
")",
".",
"write",
"(",
")",
")",
"{",
"AttributeType",
"<",
"String",
">",
"keyspaceName",
"=",
"tx",
".",
"getSchemaConcept",
"(",
"KEYSPACE_RESOURCE",
")",
";",
"if",
"(",
"keyspaceName",
"==",
"null",
")",
"{",
"throw",
"GraknServerException",
".",
"initializationException",
"(",
"keyspace",
")",
";",
"}",
"Attribute",
"<",
"String",
">",
"attribute",
"=",
"keyspaceName",
".",
"create",
"(",
"keyspace",
".",
"name",
"(",
")",
")",
";",
"if",
"(",
"attribute",
".",
"owner",
"(",
")",
"==",
"null",
")",
"{",
"tx",
".",
"<",
"EntityType",
">",
"getSchemaConcept",
"(",
"KEYSPACE_ENTITY",
")",
".",
"create",
"(",
")",
".",
"has",
"(",
"attribute",
")",
";",
"}",
"tx",
".",
"commit",
"(",
")",
";",
"// add to cache",
"existingKeyspaces",
".",
"add",
"(",
"keyspace",
")",
";",
"}",
"catch",
"(",
"InvalidKBException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Could not add keyspace [\"",
"+",
"keyspace",
"+",
"\"] to system graph\"",
",",
"e",
")",
";",
"}",
"}"
] | Logs a new KeyspaceImpl to the KeyspaceManager.
@param keyspace The new KeyspaceImpl we have just created | [
"Logs",
"a",
"new",
"KeyspaceImpl",
"to",
"the",
"KeyspaceManager",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/keyspace/KeyspaceManager.java#L72-L91 |
22,869 | graknlabs/grakn | server/src/server/keyspace/KeyspaceManager.java | KeyspaceManager.loadSystemSchema | private void loadSystemSchema(TransactionOLTP tx) {
//Keyspace data
AttributeType<String> keyspaceName = tx.putAttributeType("keyspace-name", AttributeType.DataType.STRING);
tx.putEntityType("keyspace").key(keyspaceName);
} | java | private void loadSystemSchema(TransactionOLTP tx) {
//Keyspace data
AttributeType<String> keyspaceName = tx.putAttributeType("keyspace-name", AttributeType.DataType.STRING);
tx.putEntityType("keyspace").key(keyspaceName);
} | [
"private",
"void",
"loadSystemSchema",
"(",
"TransactionOLTP",
"tx",
")",
"{",
"//Keyspace data",
"AttributeType",
"<",
"String",
">",
"keyspaceName",
"=",
"tx",
".",
"putAttributeType",
"(",
"\"keyspace-name\"",
",",
"AttributeType",
".",
"DataType",
".",
"STRING",
")",
";",
"tx",
".",
"putEntityType",
"(",
"\"keyspace\"",
")",
".",
"key",
"(",
"keyspaceName",
")",
";",
"}"
] | Loads the system schema inside the provided Transaction.
@param tx The tx to contain the system schema | [
"Loads",
"the",
"system",
"schema",
"inside",
"the",
"provided",
"Transaction",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/keyspace/KeyspaceManager.java#L169-L173 |
22,870 | graknlabs/grakn | server/src/server/session/cache/RuleCache.java | RuleCache.clear | public void clear() {
ruleMap.clear();
ruleConversionMap.clear();
absentTypes.clear();
checkedTypes.clear();
checkedRules.clear();
fruitlessRules.clear();
} | java | public void clear() {
ruleMap.clear();
ruleConversionMap.clear();
absentTypes.clear();
checkedTypes.clear();
checkedRules.clear();
fruitlessRules.clear();
} | [
"public",
"void",
"clear",
"(",
")",
"{",
"ruleMap",
".",
"clear",
"(",
")",
";",
"ruleConversionMap",
".",
"clear",
"(",
")",
";",
"absentTypes",
".",
"clear",
"(",
")",
";",
"checkedTypes",
".",
"clear",
"(",
")",
";",
"checkedRules",
".",
"clear",
"(",
")",
";",
"fruitlessRules",
".",
"clear",
"(",
")",
";",
"}"
] | cleans cache contents | [
"cleans",
"cache",
"contents"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/session/cache/RuleCache.java#L180-L187 |
22,871 | graknlabs/grakn | console/ConsoleSession.java | ConsoleSession.openTextEditor | private String openTextEditor() throws IOException, InterruptedException {
String editor = Optional.ofNullable(System.getenv().get("EDITOR")).orElse(EDITOR_DEFAULT);
File tempFile = new File(StandardSystemProperty.JAVA_IO_TMPDIR.value() + EDITOR_FILE);
tempFile.createNewFile();
// Run the editor, pipe input into and out of tty so we can provide the input/output to the editor via Graql
ProcessBuilder builder = new ProcessBuilder(
"/bin/bash", "-c",
editor + " </dev/tty >/dev/tty " + tempFile.getAbsolutePath()
);
builder.start().waitFor();
return String.join("\n", Files.readAllLines(tempFile.toPath()));
} | java | private String openTextEditor() throws IOException, InterruptedException {
String editor = Optional.ofNullable(System.getenv().get("EDITOR")).orElse(EDITOR_DEFAULT);
File tempFile = new File(StandardSystemProperty.JAVA_IO_TMPDIR.value() + EDITOR_FILE);
tempFile.createNewFile();
// Run the editor, pipe input into and out of tty so we can provide the input/output to the editor via Graql
ProcessBuilder builder = new ProcessBuilder(
"/bin/bash", "-c",
editor + " </dev/tty >/dev/tty " + tempFile.getAbsolutePath()
);
builder.start().waitFor();
return String.join("\n", Files.readAllLines(tempFile.toPath()));
} | [
"private",
"String",
"openTextEditor",
"(",
")",
"throws",
"IOException",
",",
"InterruptedException",
"{",
"String",
"editor",
"=",
"Optional",
".",
"ofNullable",
"(",
"System",
".",
"getenv",
"(",
")",
".",
"get",
"(",
"\"EDITOR\"",
")",
")",
".",
"orElse",
"(",
"EDITOR_DEFAULT",
")",
";",
"File",
"tempFile",
"=",
"new",
"File",
"(",
"StandardSystemProperty",
".",
"JAVA_IO_TMPDIR",
".",
"value",
"(",
")",
"+",
"EDITOR_FILE",
")",
";",
"tempFile",
".",
"createNewFile",
"(",
")",
";",
"// Run the editor, pipe input into and out of tty so we can provide the input/output to the editor via Graql",
"ProcessBuilder",
"builder",
"=",
"new",
"ProcessBuilder",
"(",
"\"/bin/bash\"",
",",
"\"-c\"",
",",
"editor",
"+",
"\" </dev/tty >/dev/tty \"",
"+",
"tempFile",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"builder",
".",
"start",
"(",
")",
".",
"waitFor",
"(",
")",
";",
"return",
"String",
".",
"join",
"(",
"\"\\n\"",
",",
"Files",
".",
"readAllLines",
"(",
"tempFile",
".",
"toPath",
"(",
")",
")",
")",
";",
"}"
] | Open the user's preferred editor to write a query
@return the string written in the editor | [
"Open",
"the",
"user",
"s",
"preferred",
"editor",
"to",
"write",
"a",
"query"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/console/ConsoleSession.java#L269-L282 |
22,872 | graknlabs/grakn | server/src/graql/reasoner/query/ReasonerQueries.java | ReasonerQueries.create | public static ReasonerQueryImpl create(Conjunction<Statement> pattern, TransactionOLTP tx) {
ReasonerQueryImpl query = new ReasonerQueryImpl(pattern, tx).inferTypes();
return query.isAtomic()?
new ReasonerAtomicQuery(query.getAtoms(), tx) :
query;
} | java | public static ReasonerQueryImpl create(Conjunction<Statement> pattern, TransactionOLTP tx) {
ReasonerQueryImpl query = new ReasonerQueryImpl(pattern, tx).inferTypes();
return query.isAtomic()?
new ReasonerAtomicQuery(query.getAtoms(), tx) :
query;
} | [
"public",
"static",
"ReasonerQueryImpl",
"create",
"(",
"Conjunction",
"<",
"Statement",
">",
"pattern",
",",
"TransactionOLTP",
"tx",
")",
"{",
"ReasonerQueryImpl",
"query",
"=",
"new",
"ReasonerQueryImpl",
"(",
"pattern",
",",
"tx",
")",
".",
"inferTypes",
"(",
")",
";",
"return",
"query",
".",
"isAtomic",
"(",
")",
"?",
"new",
"ReasonerAtomicQuery",
"(",
"query",
".",
"getAtoms",
"(",
")",
",",
"tx",
")",
":",
"query",
";",
"}"
] | create a reasoner query from a conjunctive pattern with types inferred
@param pattern conjunctive pattern defining the query
@param tx corresponding transaction
@return reasoner query constructed from provided conjunctive pattern | [
"create",
"a",
"reasoner",
"query",
"from",
"a",
"conjunctive",
"pattern",
"with",
"types",
"inferred"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/reasoner/query/ReasonerQueries.java#L91-L96 |
22,873 | graknlabs/grakn | server/src/graql/reasoner/query/ReasonerQueries.java | ReasonerQueries.create | public static ReasonerQueryImpl create(Set<Atomic> as, TransactionOLTP tx){
boolean isAtomic = as.stream().filter(Atomic::isSelectable).count() == 1;
return isAtomic?
new ReasonerAtomicQuery(as, tx).inferTypes() :
new ReasonerQueryImpl(as, tx).inferTypes();
} | java | public static ReasonerQueryImpl create(Set<Atomic> as, TransactionOLTP tx){
boolean isAtomic = as.stream().filter(Atomic::isSelectable).count() == 1;
return isAtomic?
new ReasonerAtomicQuery(as, tx).inferTypes() :
new ReasonerQueryImpl(as, tx).inferTypes();
} | [
"public",
"static",
"ReasonerQueryImpl",
"create",
"(",
"Set",
"<",
"Atomic",
">",
"as",
",",
"TransactionOLTP",
"tx",
")",
"{",
"boolean",
"isAtomic",
"=",
"as",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"Atomic",
"::",
"isSelectable",
")",
".",
"count",
"(",
")",
"==",
"1",
";",
"return",
"isAtomic",
"?",
"new",
"ReasonerAtomicQuery",
"(",
"as",
",",
"tx",
")",
".",
"inferTypes",
"(",
")",
":",
"new",
"ReasonerQueryImpl",
"(",
"as",
",",
"tx",
")",
".",
"inferTypes",
"(",
")",
";",
"}"
] | create a reasoner query from provided set of atomics
@param as set of atomics that define the query
@param tx corresponding transaction
@return reasoner query defined by the provided set of atomics | [
"create",
"a",
"reasoner",
"query",
"from",
"provided",
"set",
"of",
"atomics"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/reasoner/query/ReasonerQueries.java#L104-L109 |
22,874 | graknlabs/grakn | server/src/graql/reasoner/query/ReasonerQueries.java | ReasonerQueries.create | public static ReasonerQueryImpl create(ReasonerQueryImpl q, ConceptMap sub){
return q.withSubstitution(sub).inferTypes();
} | java | public static ReasonerQueryImpl create(ReasonerQueryImpl q, ConceptMap sub){
return q.withSubstitution(sub).inferTypes();
} | [
"public",
"static",
"ReasonerQueryImpl",
"create",
"(",
"ReasonerQueryImpl",
"q",
",",
"ConceptMap",
"sub",
")",
"{",
"return",
"q",
".",
"withSubstitution",
"(",
"sub",
")",
".",
"inferTypes",
"(",
")",
";",
"}"
] | create a reasoner query by combining an existing query and a substitution
@param q base query for substitution to be attached
@param sub (partial) substitution
@return reasoner query with the substitution contained in the query | [
"create",
"a",
"reasoner",
"query",
"by",
"combining",
"an",
"existing",
"query",
"and",
"a",
"substitution"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/reasoner/query/ReasonerQueries.java#L131-L133 |
22,875 | graknlabs/grakn | server/src/graql/reasoner/query/ReasonerQueries.java | ReasonerQueries.atomic | public static ReasonerAtomicQuery atomic(ReasonerAtomicQuery q, ConceptMap sub){
return q.withSubstitution(sub).inferTypes();
} | java | public static ReasonerAtomicQuery atomic(ReasonerAtomicQuery q, ConceptMap sub){
return q.withSubstitution(sub).inferTypes();
} | [
"public",
"static",
"ReasonerAtomicQuery",
"atomic",
"(",
"ReasonerAtomicQuery",
"q",
",",
"ConceptMap",
"sub",
")",
"{",
"return",
"q",
".",
"withSubstitution",
"(",
"sub",
")",
".",
"inferTypes",
"(",
")",
";",
"}"
] | create an atomic query by combining an existing atomic query and a substitution
@param q base query for substitution to be attached
@param sub (partial) substitution
@return atomic query with the substitution contained in the query | [
"create",
"an",
"atomic",
"query",
"by",
"combining",
"an",
"existing",
"atomic",
"query",
"and",
"a",
"substitution"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/reasoner/query/ReasonerQueries.java#L160-L162 |
22,876 | graknlabs/grakn | server/src/graql/reasoner/rule/InferenceRule.java | InferenceRule.requiresMaterialisation | public boolean requiresMaterialisation(Atom parentAtom){
if (requiresMaterialisation == null) {
requiresMaterialisation = parentAtom.requiresMaterialisation()
|| getHead().getAtom().requiresMaterialisation()
|| hasDisconnectedHead();
}
return requiresMaterialisation;
} | java | public boolean requiresMaterialisation(Atom parentAtom){
if (requiresMaterialisation == null) {
requiresMaterialisation = parentAtom.requiresMaterialisation()
|| getHead().getAtom().requiresMaterialisation()
|| hasDisconnectedHead();
}
return requiresMaterialisation;
} | [
"public",
"boolean",
"requiresMaterialisation",
"(",
"Atom",
"parentAtom",
")",
"{",
"if",
"(",
"requiresMaterialisation",
"==",
"null",
")",
"{",
"requiresMaterialisation",
"=",
"parentAtom",
".",
"requiresMaterialisation",
"(",
")",
"||",
"getHead",
"(",
")",
".",
"getAtom",
"(",
")",
".",
"requiresMaterialisation",
"(",
")",
"||",
"hasDisconnectedHead",
"(",
")",
";",
"}",
"return",
"requiresMaterialisation",
";",
"}"
] | rule requires materialisation in the context of resolving parent atom
if parent atom requires materialisation, head atom requires materialisation or if the head contains only fresh variables
@return true if the rule needs to be materialised | [
"rule",
"requires",
"materialisation",
"in",
"the",
"context",
"of",
"resolving",
"parent",
"atom",
"if",
"parent",
"atom",
"requires",
"materialisation",
"head",
"atom",
"requires",
"materialisation",
"or",
"if",
"the",
"head",
"contains",
"only",
"fresh",
"variables"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/reasoner/rule/InferenceRule.java#L166-L173 |
22,877 | graknlabs/grakn | server/src/server/kb/structure/AbstractElement.java | AbstractElement.propertyUnique | public void propertyUnique(P key, String value) {
GraphTraversal<Vertex, Vertex> traversal = tx().getTinkerTraversal().V().has(key.name(), value);
if (traversal.hasNext()) {
Vertex vertex = traversal.next();
if (!vertex.equals(element()) || traversal.hasNext()) {
if (traversal.hasNext()) vertex = traversal.next();
throw PropertyNotUniqueException.cannotChangeProperty(element(), vertex, key, value);
}
}
property(key, value);
} | java | public void propertyUnique(P key, String value) {
GraphTraversal<Vertex, Vertex> traversal = tx().getTinkerTraversal().V().has(key.name(), value);
if (traversal.hasNext()) {
Vertex vertex = traversal.next();
if (!vertex.equals(element()) || traversal.hasNext()) {
if (traversal.hasNext()) vertex = traversal.next();
throw PropertyNotUniqueException.cannotChangeProperty(element(), vertex, key, value);
}
}
property(key, value);
} | [
"public",
"void",
"propertyUnique",
"(",
"P",
"key",
",",
"String",
"value",
")",
"{",
"GraphTraversal",
"<",
"Vertex",
",",
"Vertex",
">",
"traversal",
"=",
"tx",
"(",
")",
".",
"getTinkerTraversal",
"(",
")",
".",
"V",
"(",
")",
".",
"has",
"(",
"key",
".",
"name",
"(",
")",
",",
"value",
")",
";",
"if",
"(",
"traversal",
".",
"hasNext",
"(",
")",
")",
"{",
"Vertex",
"vertex",
"=",
"traversal",
".",
"next",
"(",
")",
";",
"if",
"(",
"!",
"vertex",
".",
"equals",
"(",
"element",
"(",
")",
")",
"||",
"traversal",
".",
"hasNext",
"(",
")",
")",
"{",
"if",
"(",
"traversal",
".",
"hasNext",
"(",
")",
")",
"vertex",
"=",
"traversal",
".",
"next",
"(",
")",
";",
"throw",
"PropertyNotUniqueException",
".",
"cannotChangeProperty",
"(",
"element",
"(",
")",
",",
"vertex",
",",
"key",
",",
"value",
")",
";",
"}",
"}",
"property",
"(",
"key",
",",
"value",
")",
";",
"}"
] | Sets the value of a property with the added restriction that no other vertex can have that property.
@param key The key of the unique property to mutate
@param value The new value of the unique property | [
"Sets",
"the",
"value",
"of",
"a",
"property",
"with",
"the",
"added",
"restriction",
"that",
"no",
"other",
"vertex",
"can",
"have",
"that",
"property",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/kb/structure/AbstractElement.java#L131-L143 |
22,878 | graknlabs/grakn | daemon/executor/Storage.java | Storage.startIfNotRunning | public void startIfNotRunning() {
boolean isStorageRunning = daemonExecutor.isProcessRunning(STORAGE_PIDFILE);
if (isStorageRunning) {
System.out.println(DISPLAY_NAME + " is already running");
} else {
FileUtils.deleteQuietly(STORAGE_PIDFILE.toFile()); // delete dangling STORAGE_PIDFILE, if any
start();
}
} | java | public void startIfNotRunning() {
boolean isStorageRunning = daemonExecutor.isProcessRunning(STORAGE_PIDFILE);
if (isStorageRunning) {
System.out.println(DISPLAY_NAME + " is already running");
} else {
FileUtils.deleteQuietly(STORAGE_PIDFILE.toFile()); // delete dangling STORAGE_PIDFILE, if any
start();
}
} | [
"public",
"void",
"startIfNotRunning",
"(",
")",
"{",
"boolean",
"isStorageRunning",
"=",
"daemonExecutor",
".",
"isProcessRunning",
"(",
"STORAGE_PIDFILE",
")",
";",
"if",
"(",
"isStorageRunning",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"DISPLAY_NAME",
"+",
"\" is already running\"",
")",
";",
"}",
"else",
"{",
"FileUtils",
".",
"deleteQuietly",
"(",
"STORAGE_PIDFILE",
".",
"toFile",
"(",
")",
")",
";",
"// delete dangling STORAGE_PIDFILE, if any",
"start",
"(",
")",
";",
"}",
"}"
] | Attempt to start Storage if it is not already running | [
"Attempt",
"to",
"start",
"Storage",
"if",
"it",
"is",
"not",
"already",
"running"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/daemon/executor/Storage.java#L140-L148 |
22,879 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.runComputeMinMaxMedianOrSum | private Stream<Numeric> runComputeMinMaxMedianOrSum(GraqlCompute.Statistics.Value query) {
Number number = runComputeStatistics(query);
if (number == null) return Stream.empty();
else return Stream.of(new Numeric(number));
} | java | private Stream<Numeric> runComputeMinMaxMedianOrSum(GraqlCompute.Statistics.Value query) {
Number number = runComputeStatistics(query);
if (number == null) return Stream.empty();
else return Stream.of(new Numeric(number));
} | [
"private",
"Stream",
"<",
"Numeric",
">",
"runComputeMinMaxMedianOrSum",
"(",
"GraqlCompute",
".",
"Statistics",
".",
"Value",
"query",
")",
"{",
"Number",
"number",
"=",
"runComputeStatistics",
"(",
"query",
")",
";",
"if",
"(",
"number",
"==",
"null",
")",
"return",
"Stream",
".",
"empty",
"(",
")",
";",
"else",
"return",
"Stream",
".",
"of",
"(",
"new",
"Numeric",
"(",
"number",
")",
")",
";",
"}"
] | The Graql compute min, max, median, or sum query run method
@return a Answer object containing a Number that represents the answer | [
"The",
"Graql",
"compute",
"min",
"max",
"median",
"or",
"sum",
"query",
"run",
"method"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L162-L166 |
22,880 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.runComputeMean | private Stream<Numeric> runComputeMean(GraqlCompute.Statistics.Value query) {
Map<String, Double> meanPair = runComputeStatistics(query);
if (meanPair == null) return Stream.empty();
Double mean = meanPair.get(MeanMapReduce.SUM) / meanPair.get(MeanMapReduce.COUNT);
return Stream.of(new Numeric(mean));
} | java | private Stream<Numeric> runComputeMean(GraqlCompute.Statistics.Value query) {
Map<String, Double> meanPair = runComputeStatistics(query);
if (meanPair == null) return Stream.empty();
Double mean = meanPair.get(MeanMapReduce.SUM) / meanPair.get(MeanMapReduce.COUNT);
return Stream.of(new Numeric(mean));
} | [
"private",
"Stream",
"<",
"Numeric",
">",
"runComputeMean",
"(",
"GraqlCompute",
".",
"Statistics",
".",
"Value",
"query",
")",
"{",
"Map",
"<",
"String",
",",
"Double",
">",
"meanPair",
"=",
"runComputeStatistics",
"(",
"query",
")",
";",
"if",
"(",
"meanPair",
"==",
"null",
")",
"return",
"Stream",
".",
"empty",
"(",
")",
";",
"Double",
"mean",
"=",
"meanPair",
".",
"get",
"(",
"MeanMapReduce",
".",
"SUM",
")",
"/",
"meanPair",
".",
"get",
"(",
"MeanMapReduce",
".",
"COUNT",
")",
";",
"return",
"Stream",
".",
"of",
"(",
"new",
"Numeric",
"(",
"mean",
")",
")",
";",
"}"
] | The Graql compute mean query run method
@return a Answer object containing a Number that represents the answer | [
"The",
"Graql",
"compute",
"mean",
"query",
"run",
"method"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L173-L179 |
22,881 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.runComputeStd | private Stream<Numeric> runComputeStd(GraqlCompute.Statistics.Value query) {
Map<String, Double> stdTuple = runComputeStatistics(query);
if (stdTuple == null) return Stream.empty();
double squareSum = stdTuple.get(StdMapReduce.SQUARE_SUM);
double sum = stdTuple.get(StdMapReduce.SUM);
double count = stdTuple.get(StdMapReduce.COUNT);
Double std = Math.sqrt(squareSum / count - (sum / count) * (sum / count));
return Stream.of(new Numeric(std));
} | java | private Stream<Numeric> runComputeStd(GraqlCompute.Statistics.Value query) {
Map<String, Double> stdTuple = runComputeStatistics(query);
if (stdTuple == null) return Stream.empty();
double squareSum = stdTuple.get(StdMapReduce.SQUARE_SUM);
double sum = stdTuple.get(StdMapReduce.SUM);
double count = stdTuple.get(StdMapReduce.COUNT);
Double std = Math.sqrt(squareSum / count - (sum / count) * (sum / count));
return Stream.of(new Numeric(std));
} | [
"private",
"Stream",
"<",
"Numeric",
">",
"runComputeStd",
"(",
"GraqlCompute",
".",
"Statistics",
".",
"Value",
"query",
")",
"{",
"Map",
"<",
"String",
",",
"Double",
">",
"stdTuple",
"=",
"runComputeStatistics",
"(",
"query",
")",
";",
"if",
"(",
"stdTuple",
"==",
"null",
")",
"return",
"Stream",
".",
"empty",
"(",
")",
";",
"double",
"squareSum",
"=",
"stdTuple",
".",
"get",
"(",
"StdMapReduce",
".",
"SQUARE_SUM",
")",
";",
"double",
"sum",
"=",
"stdTuple",
".",
"get",
"(",
"StdMapReduce",
".",
"SUM",
")",
";",
"double",
"count",
"=",
"stdTuple",
".",
"get",
"(",
"StdMapReduce",
".",
"COUNT",
")",
";",
"Double",
"std",
"=",
"Math",
".",
"sqrt",
"(",
"squareSum",
"/",
"count",
"-",
"(",
"sum",
"/",
"count",
")",
"*",
"(",
"sum",
"/",
"count",
")",
")",
";",
"return",
"Stream",
".",
"of",
"(",
"new",
"Numeric",
"(",
"std",
")",
")",
";",
"}"
] | The Graql compute std query run method
@return a Answer object containing a Number that represents the answer | [
"The",
"Graql",
"compute",
"std",
"query",
"run",
"method"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L186-L196 |
22,882 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.runComputeStatistics | @Nullable
private <S> S runComputeStatistics(GraqlCompute.Statistics.Value query) {
AttributeType.DataType<?> targetDataType = validateAndGetTargetDataType(query);
if (!targetContainsInstance(query)) return null;
Set<LabelId> extendedScopeTypes = convertLabelsToIds(extendedScopeTypeLabels(query));
Set<LabelId> targetTypes = convertLabelsToIds(targetTypeLabels(query));
VertexProgram program = initStatisticsVertexProgram(query, targetTypes, targetDataType);
StatisticsMapReduce<?> mapReduce = initStatisticsMapReduce(query, targetTypes, targetDataType);
ComputerResult computerResult = compute(program, mapReduce, extendedScopeTypes);
if (query.method().equals(MEDIAN)) {
Number result = computerResult.memory().get(MedianVertexProgram.MEDIAN);
LOG.debug("Median = {}", result);
return (S) result;
}
Map<Serializable, S> resultMap = computerResult.memory().get(mapReduce.getClass().getName());
LOG.debug("Result = {}", resultMap.get(MapReduce.NullObject.instance()));
return resultMap.get(MapReduce.NullObject.instance());
} | java | @Nullable
private <S> S runComputeStatistics(GraqlCompute.Statistics.Value query) {
AttributeType.DataType<?> targetDataType = validateAndGetTargetDataType(query);
if (!targetContainsInstance(query)) return null;
Set<LabelId> extendedScopeTypes = convertLabelsToIds(extendedScopeTypeLabels(query));
Set<LabelId> targetTypes = convertLabelsToIds(targetTypeLabels(query));
VertexProgram program = initStatisticsVertexProgram(query, targetTypes, targetDataType);
StatisticsMapReduce<?> mapReduce = initStatisticsMapReduce(query, targetTypes, targetDataType);
ComputerResult computerResult = compute(program, mapReduce, extendedScopeTypes);
if (query.method().equals(MEDIAN)) {
Number result = computerResult.memory().get(MedianVertexProgram.MEDIAN);
LOG.debug("Median = {}", result);
return (S) result;
}
Map<Serializable, S> resultMap = computerResult.memory().get(mapReduce.getClass().getName());
LOG.debug("Result = {}", resultMap.get(MapReduce.NullObject.instance()));
return resultMap.get(MapReduce.NullObject.instance());
} | [
"@",
"Nullable",
"private",
"<",
"S",
">",
"S",
"runComputeStatistics",
"(",
"GraqlCompute",
".",
"Statistics",
".",
"Value",
"query",
")",
"{",
"AttributeType",
".",
"DataType",
"<",
"?",
">",
"targetDataType",
"=",
"validateAndGetTargetDataType",
"(",
"query",
")",
";",
"if",
"(",
"!",
"targetContainsInstance",
"(",
"query",
")",
")",
"return",
"null",
";",
"Set",
"<",
"LabelId",
">",
"extendedScopeTypes",
"=",
"convertLabelsToIds",
"(",
"extendedScopeTypeLabels",
"(",
"query",
")",
")",
";",
"Set",
"<",
"LabelId",
">",
"targetTypes",
"=",
"convertLabelsToIds",
"(",
"targetTypeLabels",
"(",
"query",
")",
")",
";",
"VertexProgram",
"program",
"=",
"initStatisticsVertexProgram",
"(",
"query",
",",
"targetTypes",
",",
"targetDataType",
")",
";",
"StatisticsMapReduce",
"<",
"?",
">",
"mapReduce",
"=",
"initStatisticsMapReduce",
"(",
"query",
",",
"targetTypes",
",",
"targetDataType",
")",
";",
"ComputerResult",
"computerResult",
"=",
"compute",
"(",
"program",
",",
"mapReduce",
",",
"extendedScopeTypes",
")",
";",
"if",
"(",
"query",
".",
"method",
"(",
")",
".",
"equals",
"(",
"MEDIAN",
")",
")",
"{",
"Number",
"result",
"=",
"computerResult",
".",
"memory",
"(",
")",
".",
"get",
"(",
"MedianVertexProgram",
".",
"MEDIAN",
")",
";",
"LOG",
".",
"debug",
"(",
"\"Median = {}\"",
",",
"result",
")",
";",
"return",
"(",
"S",
")",
"result",
";",
"}",
"Map",
"<",
"Serializable",
",",
"S",
">",
"resultMap",
"=",
"computerResult",
".",
"memory",
"(",
")",
".",
"get",
"(",
"mapReduce",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"LOG",
".",
"debug",
"(",
"\"Result = {}\"",
",",
"resultMap",
".",
"get",
"(",
"MapReduce",
".",
"NullObject",
".",
"instance",
"(",
")",
")",
")",
";",
"return",
"resultMap",
".",
"get",
"(",
"MapReduce",
".",
"NullObject",
".",
"instance",
"(",
")",
")",
";",
"}"
] | The compute statistics base algorithm that is called in every compute statistics query
@param <S> The return type of {@link StatisticsMapReduce}
@return result of compute statistics algorithm, which will be of type S | [
"The",
"compute",
"statistics",
"base",
"algorithm",
"that",
"is",
"called",
"in",
"every",
"compute",
"statistics",
"query"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L204-L225 |
22,883 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.validateAndGetTargetDataType | @Nullable
private AttributeType.DataType<?> validateAndGetTargetDataType(GraqlCompute.Statistics.Value query) {
AttributeType.DataType<?> dataType = null;
for (Type type : targetTypes(query)) {
// check if the selected type is a attribute type
if (!type.isAttributeType()) throw GraqlQueryException.mustBeAttributeType(type.label());
AttributeType<?> attributeType = type.asAttributeType();
if (dataType == null) {
// check if the attribute type has data-type LONG or DOUBLE
dataType = attributeType.dataType();
if (!dataType.equals(AttributeType.DataType.LONG) && !dataType.equals(AttributeType.DataType.DOUBLE)) {
throw GraqlQueryException.attributeMustBeANumber(dataType, attributeType.label());
}
} else {
// check if all the attribute types have the same data-type
if (!dataType.equals(attributeType.dataType())) {
throw GraqlQueryException.attributesWithDifferentDataTypes(query.of());
}
}
}
return dataType;
} | java | @Nullable
private AttributeType.DataType<?> validateAndGetTargetDataType(GraqlCompute.Statistics.Value query) {
AttributeType.DataType<?> dataType = null;
for (Type type : targetTypes(query)) {
// check if the selected type is a attribute type
if (!type.isAttributeType()) throw GraqlQueryException.mustBeAttributeType(type.label());
AttributeType<?> attributeType = type.asAttributeType();
if (dataType == null) {
// check if the attribute type has data-type LONG or DOUBLE
dataType = attributeType.dataType();
if (!dataType.equals(AttributeType.DataType.LONG) && !dataType.equals(AttributeType.DataType.DOUBLE)) {
throw GraqlQueryException.attributeMustBeANumber(dataType, attributeType.label());
}
} else {
// check if all the attribute types have the same data-type
if (!dataType.equals(attributeType.dataType())) {
throw GraqlQueryException.attributesWithDifferentDataTypes(query.of());
}
}
}
return dataType;
} | [
"@",
"Nullable",
"private",
"AttributeType",
".",
"DataType",
"<",
"?",
">",
"validateAndGetTargetDataType",
"(",
"GraqlCompute",
".",
"Statistics",
".",
"Value",
"query",
")",
"{",
"AttributeType",
".",
"DataType",
"<",
"?",
">",
"dataType",
"=",
"null",
";",
"for",
"(",
"Type",
"type",
":",
"targetTypes",
"(",
"query",
")",
")",
"{",
"// check if the selected type is a attribute type",
"if",
"(",
"!",
"type",
".",
"isAttributeType",
"(",
")",
")",
"throw",
"GraqlQueryException",
".",
"mustBeAttributeType",
"(",
"type",
".",
"label",
"(",
")",
")",
";",
"AttributeType",
"<",
"?",
">",
"attributeType",
"=",
"type",
".",
"asAttributeType",
"(",
")",
";",
"if",
"(",
"dataType",
"==",
"null",
")",
"{",
"// check if the attribute type has data-type LONG or DOUBLE",
"dataType",
"=",
"attributeType",
".",
"dataType",
"(",
")",
";",
"if",
"(",
"!",
"dataType",
".",
"equals",
"(",
"AttributeType",
".",
"DataType",
".",
"LONG",
")",
"&&",
"!",
"dataType",
".",
"equals",
"(",
"AttributeType",
".",
"DataType",
".",
"DOUBLE",
")",
")",
"{",
"throw",
"GraqlQueryException",
".",
"attributeMustBeANumber",
"(",
"dataType",
",",
"attributeType",
".",
"label",
"(",
")",
")",
";",
"}",
"}",
"else",
"{",
"// check if all the attribute types have the same data-type",
"if",
"(",
"!",
"dataType",
".",
"equals",
"(",
"attributeType",
".",
"dataType",
"(",
")",
")",
")",
"{",
"throw",
"GraqlQueryException",
".",
"attributesWithDifferentDataTypes",
"(",
"query",
".",
"of",
"(",
")",
")",
";",
"}",
"}",
"}",
"return",
"dataType",
";",
"}"
] | Helper method to validate that the target types are of one data type, and get that data type
@return the DataType of the target types | [
"Helper",
"method",
"to",
"validate",
"that",
"the",
"target",
"types",
"are",
"of",
"one",
"data",
"type",
"and",
"get",
"that",
"data",
"type"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L232-L253 |
22,884 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.initStatisticsVertexProgram | private VertexProgram initStatisticsVertexProgram(GraqlCompute query, Set<LabelId> targetTypes, AttributeType.DataType<?> targetDataType) {
if (query.method().equals(MEDIAN)) return new MedianVertexProgram(targetTypes, targetDataType);
else return new DegreeStatisticsVertexProgram(targetTypes);
} | java | private VertexProgram initStatisticsVertexProgram(GraqlCompute query, Set<LabelId> targetTypes, AttributeType.DataType<?> targetDataType) {
if (query.method().equals(MEDIAN)) return new MedianVertexProgram(targetTypes, targetDataType);
else return new DegreeStatisticsVertexProgram(targetTypes);
} | [
"private",
"VertexProgram",
"initStatisticsVertexProgram",
"(",
"GraqlCompute",
"query",
",",
"Set",
"<",
"LabelId",
">",
"targetTypes",
",",
"AttributeType",
".",
"DataType",
"<",
"?",
">",
"targetDataType",
")",
"{",
"if",
"(",
"query",
".",
"method",
"(",
")",
".",
"equals",
"(",
"MEDIAN",
")",
")",
"return",
"new",
"MedianVertexProgram",
"(",
"targetTypes",
",",
"targetDataType",
")",
";",
"else",
"return",
"new",
"DegreeStatisticsVertexProgram",
"(",
"targetTypes",
")",
";",
"}"
] | Helper method to intialise the vertex program for compute statistics queries
@param query representing the compute query
@param targetTypes representing the attribute types in which the statistics computation is targeted for
@param targetDataType representing the data type of the target attribute types
@return an object which is a subclass of VertexProgram | [
"Helper",
"method",
"to",
"intialise",
"the",
"vertex",
"program",
"for",
"compute",
"statistics",
"queries"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L263-L266 |
22,885 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.initStatisticsMapReduce | private StatisticsMapReduce<?> initStatisticsMapReduce(GraqlCompute.Statistics.Value query,
Set<LabelId> targetTypes,
AttributeType.DataType<?> targetDataType) {
Graql.Token.Compute.Method method = query.method();
if (method.equals(MIN)) {
return new MinMapReduce(targetTypes, targetDataType, DegreeVertexProgram.DEGREE);
} else if (method.equals(MAX)) {
return new MaxMapReduce(targetTypes, targetDataType, DegreeVertexProgram.DEGREE);
} else if (method.equals(MEAN)) {
return new MeanMapReduce(targetTypes, targetDataType, DegreeVertexProgram.DEGREE);
}else if (method.equals(STD)) {
return new StdMapReduce(targetTypes, targetDataType, DegreeVertexProgram.DEGREE);
} else if (method.equals(SUM)) {
return new SumMapReduce(targetTypes, targetDataType, DegreeVertexProgram.DEGREE);
}
return null;
} | java | private StatisticsMapReduce<?> initStatisticsMapReduce(GraqlCompute.Statistics.Value query,
Set<LabelId> targetTypes,
AttributeType.DataType<?> targetDataType) {
Graql.Token.Compute.Method method = query.method();
if (method.equals(MIN)) {
return new MinMapReduce(targetTypes, targetDataType, DegreeVertexProgram.DEGREE);
} else if (method.equals(MAX)) {
return new MaxMapReduce(targetTypes, targetDataType, DegreeVertexProgram.DEGREE);
} else if (method.equals(MEAN)) {
return new MeanMapReduce(targetTypes, targetDataType, DegreeVertexProgram.DEGREE);
}else if (method.equals(STD)) {
return new StdMapReduce(targetTypes, targetDataType, DegreeVertexProgram.DEGREE);
} else if (method.equals(SUM)) {
return new SumMapReduce(targetTypes, targetDataType, DegreeVertexProgram.DEGREE);
}
return null;
} | [
"private",
"StatisticsMapReduce",
"<",
"?",
">",
"initStatisticsMapReduce",
"(",
"GraqlCompute",
".",
"Statistics",
".",
"Value",
"query",
",",
"Set",
"<",
"LabelId",
">",
"targetTypes",
",",
"AttributeType",
".",
"DataType",
"<",
"?",
">",
"targetDataType",
")",
"{",
"Graql",
".",
"Token",
".",
"Compute",
".",
"Method",
"method",
"=",
"query",
".",
"method",
"(",
")",
";",
"if",
"(",
"method",
".",
"equals",
"(",
"MIN",
")",
")",
"{",
"return",
"new",
"MinMapReduce",
"(",
"targetTypes",
",",
"targetDataType",
",",
"DegreeVertexProgram",
".",
"DEGREE",
")",
";",
"}",
"else",
"if",
"(",
"method",
".",
"equals",
"(",
"MAX",
")",
")",
"{",
"return",
"new",
"MaxMapReduce",
"(",
"targetTypes",
",",
"targetDataType",
",",
"DegreeVertexProgram",
".",
"DEGREE",
")",
";",
"}",
"else",
"if",
"(",
"method",
".",
"equals",
"(",
"MEAN",
")",
")",
"{",
"return",
"new",
"MeanMapReduce",
"(",
"targetTypes",
",",
"targetDataType",
",",
"DegreeVertexProgram",
".",
"DEGREE",
")",
";",
"}",
"else",
"if",
"(",
"method",
".",
"equals",
"(",
"STD",
")",
")",
"{",
"return",
"new",
"StdMapReduce",
"(",
"targetTypes",
",",
"targetDataType",
",",
"DegreeVertexProgram",
".",
"DEGREE",
")",
";",
"}",
"else",
"if",
"(",
"method",
".",
"equals",
"(",
"SUM",
")",
")",
"{",
"return",
"new",
"SumMapReduce",
"(",
"targetTypes",
",",
"targetDataType",
",",
"DegreeVertexProgram",
".",
"DEGREE",
")",
";",
"}",
"return",
"null",
";",
"}"
] | Helper method to initialise the MapReduce algorithm for compute statistics queries
@param targetTypes representing the attribute types in which the statistics computation is targeted for
@param targetDataType representing the data type of the target attribute types
@return an object which is a subclass of StatisticsMapReduce | [
"Helper",
"method",
"to",
"initialise",
"the",
"MapReduce",
"algorithm",
"for",
"compute",
"statistics",
"queries"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L275-L292 |
22,886 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.runComputeCount | private Stream<Numeric> runComputeCount(GraqlCompute.Statistics.Count query) {
if (!scopeContainsInstance(query)) {
LOG.debug("Count = 0");
return Stream.of(new Numeric(0));
}
Set<LabelId> scopeTypeLabelIDs = convertLabelsToIds(scopeTypeLabels(query));
Set<LabelId> scopeTypeAndImpliedPlayersLabelIDs = convertLabelsToIds(scopeTypeLabelsImplicitPlayers(query));
scopeTypeAndImpliedPlayersLabelIDs.addAll(scopeTypeLabelIDs);
Map<Integer, Long> count;
ComputerResult result = compute(
new CountVertexProgram(),
new CountMapReduceWithAttribute(),
scopeTypeAndImpliedPlayersLabelIDs, false);
count = result.memory().get(CountMapReduceWithAttribute.class.getName());
long finalCount = count.keySet().stream()
.filter(id -> scopeTypeLabelIDs.contains(LabelId.of(id)))
.mapToLong(count::get).sum();
if (count.containsKey(GraknMapReduce.RESERVED_TYPE_LABEL_KEY)) {
finalCount += count.get(GraknMapReduce.RESERVED_TYPE_LABEL_KEY);
}
LOG.debug("Count = {}", finalCount);
return Stream.of(new Numeric(finalCount));
} | java | private Stream<Numeric> runComputeCount(GraqlCompute.Statistics.Count query) {
if (!scopeContainsInstance(query)) {
LOG.debug("Count = 0");
return Stream.of(new Numeric(0));
}
Set<LabelId> scopeTypeLabelIDs = convertLabelsToIds(scopeTypeLabels(query));
Set<LabelId> scopeTypeAndImpliedPlayersLabelIDs = convertLabelsToIds(scopeTypeLabelsImplicitPlayers(query));
scopeTypeAndImpliedPlayersLabelIDs.addAll(scopeTypeLabelIDs);
Map<Integer, Long> count;
ComputerResult result = compute(
new CountVertexProgram(),
new CountMapReduceWithAttribute(),
scopeTypeAndImpliedPlayersLabelIDs, false);
count = result.memory().get(CountMapReduceWithAttribute.class.getName());
long finalCount = count.keySet().stream()
.filter(id -> scopeTypeLabelIDs.contains(LabelId.of(id)))
.mapToLong(count::get).sum();
if (count.containsKey(GraknMapReduce.RESERVED_TYPE_LABEL_KEY)) {
finalCount += count.get(GraknMapReduce.RESERVED_TYPE_LABEL_KEY);
}
LOG.debug("Count = {}", finalCount);
return Stream.of(new Numeric(finalCount));
} | [
"private",
"Stream",
"<",
"Numeric",
">",
"runComputeCount",
"(",
"GraqlCompute",
".",
"Statistics",
".",
"Count",
"query",
")",
"{",
"if",
"(",
"!",
"scopeContainsInstance",
"(",
"query",
")",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"Count = 0\"",
")",
";",
"return",
"Stream",
".",
"of",
"(",
"new",
"Numeric",
"(",
"0",
")",
")",
";",
"}",
"Set",
"<",
"LabelId",
">",
"scopeTypeLabelIDs",
"=",
"convertLabelsToIds",
"(",
"scopeTypeLabels",
"(",
"query",
")",
")",
";",
"Set",
"<",
"LabelId",
">",
"scopeTypeAndImpliedPlayersLabelIDs",
"=",
"convertLabelsToIds",
"(",
"scopeTypeLabelsImplicitPlayers",
"(",
"query",
")",
")",
";",
"scopeTypeAndImpliedPlayersLabelIDs",
".",
"addAll",
"(",
"scopeTypeLabelIDs",
")",
";",
"Map",
"<",
"Integer",
",",
"Long",
">",
"count",
";",
"ComputerResult",
"result",
"=",
"compute",
"(",
"new",
"CountVertexProgram",
"(",
")",
",",
"new",
"CountMapReduceWithAttribute",
"(",
")",
",",
"scopeTypeAndImpliedPlayersLabelIDs",
",",
"false",
")",
";",
"count",
"=",
"result",
".",
"memory",
"(",
")",
".",
"get",
"(",
"CountMapReduceWithAttribute",
".",
"class",
".",
"getName",
"(",
")",
")",
";",
"long",
"finalCount",
"=",
"count",
".",
"keySet",
"(",
")",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"id",
"->",
"scopeTypeLabelIDs",
".",
"contains",
"(",
"LabelId",
".",
"of",
"(",
"id",
")",
")",
")",
".",
"mapToLong",
"(",
"count",
"::",
"get",
")",
".",
"sum",
"(",
")",
";",
"if",
"(",
"count",
".",
"containsKey",
"(",
"GraknMapReduce",
".",
"RESERVED_TYPE_LABEL_KEY",
")",
")",
"{",
"finalCount",
"+=",
"count",
".",
"get",
"(",
"GraknMapReduce",
".",
"RESERVED_TYPE_LABEL_KEY",
")",
";",
"}",
"LOG",
".",
"debug",
"(",
"\"Count = {}\"",
",",
"finalCount",
")",
";",
"return",
"Stream",
".",
"of",
"(",
"new",
"Numeric",
"(",
"finalCount",
")",
")",
";",
"}"
] | Run Graql compute count query
@return a Answer object containing the count value | [
"Run",
"Graql",
"compute",
"count",
"query"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L299-L326 |
22,887 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.runComputePath | private Stream<ConceptList> runComputePath(GraqlCompute.Path query) {
ConceptId fromID = ConceptId.of(query.from());
ConceptId toID = ConceptId.of(query.to());
if (!scopeContainsInstances(query, fromID, toID)) throw GraqlQueryException.instanceDoesNotExist();
if (fromID.equals(toID)) return Stream.of(new ConceptList(ImmutableList.of(fromID)));
Set<LabelId> scopedLabelIds = convertLabelsToIds(scopeTypeLabels(query));
ComputerResult result = compute(new ShortestPathVertexProgram(fromID, toID), null, scopedLabelIds);
Multimap<ConceptId, ConceptId> pathsAsEdgeList = HashMultimap.create();
Map<String, Set<String>> resultFromMemory = result.memory().get(ShortestPathVertexProgram.SHORTEST_PATH);
resultFromMemory.forEach((id, idSet) -> idSet.forEach(id2 -> {
pathsAsEdgeList.put(Schema.conceptIdFromVertexId(id), Schema.conceptIdFromVertexId(id2));
}));
List<List<ConceptId>> paths;
if (!resultFromMemory.isEmpty()) {
paths = getComputePathResultList(pathsAsEdgeList, fromID);
if (scopeIncludesAttributes(query)) {
paths = getComputePathResultListIncludingImplicitRelations(paths);
}
}
else {
paths = Collections.emptyList();
}
return paths.stream().map(ConceptList::new);
} | java | private Stream<ConceptList> runComputePath(GraqlCompute.Path query) {
ConceptId fromID = ConceptId.of(query.from());
ConceptId toID = ConceptId.of(query.to());
if (!scopeContainsInstances(query, fromID, toID)) throw GraqlQueryException.instanceDoesNotExist();
if (fromID.equals(toID)) return Stream.of(new ConceptList(ImmutableList.of(fromID)));
Set<LabelId> scopedLabelIds = convertLabelsToIds(scopeTypeLabels(query));
ComputerResult result = compute(new ShortestPathVertexProgram(fromID, toID), null, scopedLabelIds);
Multimap<ConceptId, ConceptId> pathsAsEdgeList = HashMultimap.create();
Map<String, Set<String>> resultFromMemory = result.memory().get(ShortestPathVertexProgram.SHORTEST_PATH);
resultFromMemory.forEach((id, idSet) -> idSet.forEach(id2 -> {
pathsAsEdgeList.put(Schema.conceptIdFromVertexId(id), Schema.conceptIdFromVertexId(id2));
}));
List<List<ConceptId>> paths;
if (!resultFromMemory.isEmpty()) {
paths = getComputePathResultList(pathsAsEdgeList, fromID);
if (scopeIncludesAttributes(query)) {
paths = getComputePathResultListIncludingImplicitRelations(paths);
}
}
else {
paths = Collections.emptyList();
}
return paths.stream().map(ConceptList::new);
} | [
"private",
"Stream",
"<",
"ConceptList",
">",
"runComputePath",
"(",
"GraqlCompute",
".",
"Path",
"query",
")",
"{",
"ConceptId",
"fromID",
"=",
"ConceptId",
".",
"of",
"(",
"query",
".",
"from",
"(",
")",
")",
";",
"ConceptId",
"toID",
"=",
"ConceptId",
".",
"of",
"(",
"query",
".",
"to",
"(",
")",
")",
";",
"if",
"(",
"!",
"scopeContainsInstances",
"(",
"query",
",",
"fromID",
",",
"toID",
")",
")",
"throw",
"GraqlQueryException",
".",
"instanceDoesNotExist",
"(",
")",
";",
"if",
"(",
"fromID",
".",
"equals",
"(",
"toID",
")",
")",
"return",
"Stream",
".",
"of",
"(",
"new",
"ConceptList",
"(",
"ImmutableList",
".",
"of",
"(",
"fromID",
")",
")",
")",
";",
"Set",
"<",
"LabelId",
">",
"scopedLabelIds",
"=",
"convertLabelsToIds",
"(",
"scopeTypeLabels",
"(",
"query",
")",
")",
";",
"ComputerResult",
"result",
"=",
"compute",
"(",
"new",
"ShortestPathVertexProgram",
"(",
"fromID",
",",
"toID",
")",
",",
"null",
",",
"scopedLabelIds",
")",
";",
"Multimap",
"<",
"ConceptId",
",",
"ConceptId",
">",
"pathsAsEdgeList",
"=",
"HashMultimap",
".",
"create",
"(",
")",
";",
"Map",
"<",
"String",
",",
"Set",
"<",
"String",
">",
">",
"resultFromMemory",
"=",
"result",
".",
"memory",
"(",
")",
".",
"get",
"(",
"ShortestPathVertexProgram",
".",
"SHORTEST_PATH",
")",
";",
"resultFromMemory",
".",
"forEach",
"(",
"(",
"id",
",",
"idSet",
")",
"->",
"idSet",
".",
"forEach",
"(",
"id2",
"->",
"{",
"pathsAsEdgeList",
".",
"put",
"(",
"Schema",
".",
"conceptIdFromVertexId",
"(",
"id",
")",
",",
"Schema",
".",
"conceptIdFromVertexId",
"(",
"id2",
")",
")",
";",
"}",
")",
")",
";",
"List",
"<",
"List",
"<",
"ConceptId",
">",
">",
"paths",
";",
"if",
"(",
"!",
"resultFromMemory",
".",
"isEmpty",
"(",
")",
")",
"{",
"paths",
"=",
"getComputePathResultList",
"(",
"pathsAsEdgeList",
",",
"fromID",
")",
";",
"if",
"(",
"scopeIncludesAttributes",
"(",
"query",
")",
")",
"{",
"paths",
"=",
"getComputePathResultListIncludingImplicitRelations",
"(",
"paths",
")",
";",
"}",
"}",
"else",
"{",
"paths",
"=",
"Collections",
".",
"emptyList",
"(",
")",
";",
"}",
"return",
"paths",
".",
"stream",
"(",
")",
".",
"map",
"(",
"ConceptList",
"::",
"new",
")",
";",
"}"
] | The Graql compute path query run method
@return a Answer containing the list of shortest paths | [
"The",
"Graql",
"compute",
"path",
"query",
"run",
"method"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L333-L362 |
22,888 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.runComputeCentrality | private Stream<ConceptSetMeasure> runComputeCentrality(GraqlCompute.Centrality query) {
if (query.using().equals(DEGREE)) return runComputeDegree(query);
if (query.using().equals(K_CORE)) return runComputeCoreness(query);
throw new IllegalArgumentException("Unrecognised Graql Compute Centrality algorithm: " + query.method());
} | java | private Stream<ConceptSetMeasure> runComputeCentrality(GraqlCompute.Centrality query) {
if (query.using().equals(DEGREE)) return runComputeDegree(query);
if (query.using().equals(K_CORE)) return runComputeCoreness(query);
throw new IllegalArgumentException("Unrecognised Graql Compute Centrality algorithm: " + query.method());
} | [
"private",
"Stream",
"<",
"ConceptSetMeasure",
">",
"runComputeCentrality",
"(",
"GraqlCompute",
".",
"Centrality",
"query",
")",
"{",
"if",
"(",
"query",
".",
"using",
"(",
")",
".",
"equals",
"(",
"DEGREE",
")",
")",
"return",
"runComputeDegree",
"(",
"query",
")",
";",
"if",
"(",
"query",
".",
"using",
"(",
")",
".",
"equals",
"(",
"K_CORE",
")",
")",
"return",
"runComputeCoreness",
"(",
"query",
")",
";",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Unrecognised Graql Compute Centrality algorithm: \"",
"+",
"query",
".",
"method",
"(",
")",
")",
";",
"}"
] | The Graql compute centrality query run method
@return a Answer containing the centrality count map | [
"The",
"Graql",
"compute",
"centrality",
"query",
"run",
"method"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L369-L374 |
22,889 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.runComputeDegree | private Stream<ConceptSetMeasure> runComputeDegree(GraqlCompute.Centrality query) {
Set<Label> targetTypeLabels;
// Check if ofType is valid before returning emptyMap
if (query.of().isEmpty()) {
targetTypeLabels = scopeTypeLabels(query);
} else {
targetTypeLabels = query.of().stream()
.flatMap(t -> {
Label typeLabel = Label.of(t);
Type type = tx.getSchemaConcept(typeLabel);
if (type == null) throw GraqlQueryException.labelNotFound(typeLabel);
return type.subs();
})
.map(SchemaConcept::label)
.collect(toSet());
}
Set<Label> scopeTypeLabels = Sets.union(scopeTypeLabels(query), targetTypeLabels);
if (!scopeContainsInstance(query)) {
return Stream.empty();
}
Set<LabelId> scopeTypeLabelIDs = convertLabelsToIds(scopeTypeLabels);
Set<LabelId> targetTypeLabelIDs = convertLabelsToIds(targetTypeLabels);
ComputerResult computerResult = compute(new DegreeVertexProgram(targetTypeLabelIDs),
new DegreeDistributionMapReduce(targetTypeLabelIDs, DegreeVertexProgram.DEGREE),
scopeTypeLabelIDs);
Map<Long, Set<ConceptId>> centralityMap = computerResult.memory().get(DegreeDistributionMapReduce.class.getName());
return centralityMap.entrySet().stream()
.map(centrality -> new ConceptSetMeasure(centrality.getValue(), centrality.getKey()));
} | java | private Stream<ConceptSetMeasure> runComputeDegree(GraqlCompute.Centrality query) {
Set<Label> targetTypeLabels;
// Check if ofType is valid before returning emptyMap
if (query.of().isEmpty()) {
targetTypeLabels = scopeTypeLabels(query);
} else {
targetTypeLabels = query.of().stream()
.flatMap(t -> {
Label typeLabel = Label.of(t);
Type type = tx.getSchemaConcept(typeLabel);
if (type == null) throw GraqlQueryException.labelNotFound(typeLabel);
return type.subs();
})
.map(SchemaConcept::label)
.collect(toSet());
}
Set<Label> scopeTypeLabels = Sets.union(scopeTypeLabels(query), targetTypeLabels);
if (!scopeContainsInstance(query)) {
return Stream.empty();
}
Set<LabelId> scopeTypeLabelIDs = convertLabelsToIds(scopeTypeLabels);
Set<LabelId> targetTypeLabelIDs = convertLabelsToIds(targetTypeLabels);
ComputerResult computerResult = compute(new DegreeVertexProgram(targetTypeLabelIDs),
new DegreeDistributionMapReduce(targetTypeLabelIDs, DegreeVertexProgram.DEGREE),
scopeTypeLabelIDs);
Map<Long, Set<ConceptId>> centralityMap = computerResult.memory().get(DegreeDistributionMapReduce.class.getName());
return centralityMap.entrySet().stream()
.map(centrality -> new ConceptSetMeasure(centrality.getValue(), centrality.getKey()));
} | [
"private",
"Stream",
"<",
"ConceptSetMeasure",
">",
"runComputeDegree",
"(",
"GraqlCompute",
".",
"Centrality",
"query",
")",
"{",
"Set",
"<",
"Label",
">",
"targetTypeLabels",
";",
"// Check if ofType is valid before returning emptyMap",
"if",
"(",
"query",
".",
"of",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"targetTypeLabels",
"=",
"scopeTypeLabels",
"(",
"query",
")",
";",
"}",
"else",
"{",
"targetTypeLabels",
"=",
"query",
".",
"of",
"(",
")",
".",
"stream",
"(",
")",
".",
"flatMap",
"(",
"t",
"->",
"{",
"Label",
"typeLabel",
"=",
"Label",
".",
"of",
"(",
"t",
")",
";",
"Type",
"type",
"=",
"tx",
".",
"getSchemaConcept",
"(",
"typeLabel",
")",
";",
"if",
"(",
"type",
"==",
"null",
")",
"throw",
"GraqlQueryException",
".",
"labelNotFound",
"(",
"typeLabel",
")",
";",
"return",
"type",
".",
"subs",
"(",
")",
";",
"}",
")",
".",
"map",
"(",
"SchemaConcept",
"::",
"label",
")",
".",
"collect",
"(",
"toSet",
"(",
")",
")",
";",
"}",
"Set",
"<",
"Label",
">",
"scopeTypeLabels",
"=",
"Sets",
".",
"union",
"(",
"scopeTypeLabels",
"(",
"query",
")",
",",
"targetTypeLabels",
")",
";",
"if",
"(",
"!",
"scopeContainsInstance",
"(",
"query",
")",
")",
"{",
"return",
"Stream",
".",
"empty",
"(",
")",
";",
"}",
"Set",
"<",
"LabelId",
">",
"scopeTypeLabelIDs",
"=",
"convertLabelsToIds",
"(",
"scopeTypeLabels",
")",
";",
"Set",
"<",
"LabelId",
">",
"targetTypeLabelIDs",
"=",
"convertLabelsToIds",
"(",
"targetTypeLabels",
")",
";",
"ComputerResult",
"computerResult",
"=",
"compute",
"(",
"new",
"DegreeVertexProgram",
"(",
"targetTypeLabelIDs",
")",
",",
"new",
"DegreeDistributionMapReduce",
"(",
"targetTypeLabelIDs",
",",
"DegreeVertexProgram",
".",
"DEGREE",
")",
",",
"scopeTypeLabelIDs",
")",
";",
"Map",
"<",
"Long",
",",
"Set",
"<",
"ConceptId",
">",
">",
"centralityMap",
"=",
"computerResult",
".",
"memory",
"(",
")",
".",
"get",
"(",
"DegreeDistributionMapReduce",
".",
"class",
".",
"getName",
"(",
")",
")",
";",
"return",
"centralityMap",
".",
"entrySet",
"(",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"centrality",
"->",
"new",
"ConceptSetMeasure",
"(",
"centrality",
".",
"getValue",
"(",
")",
",",
"centrality",
".",
"getKey",
"(",
")",
")",
")",
";",
"}"
] | The Graql compute centrality using degree query run method
@return a Answer containing the centrality count map | [
"The",
"Graql",
"compute",
"centrality",
"using",
"degree",
"query",
"run",
"method"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L381-L416 |
22,890 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.runComputeCoreness | private Stream<ConceptSetMeasure> runComputeCoreness(GraqlCompute.Centrality query) {
long k = query.where().minK().get();
if (k < 2L) throw GraqlQueryException.kValueSmallerThanTwo();
Set<Label> targetTypeLabels;
// Check if ofType is valid before returning emptyMap
if (query.of().isEmpty()) {
targetTypeLabels = scopeTypeLabels(query);
} else {
targetTypeLabels = query.of().stream()
.flatMap(t -> {
Label typeLabel = Label.of(t);
Type type = tx.getSchemaConcept(typeLabel);
if (type == null) throw GraqlQueryException.labelNotFound(typeLabel);
if (type.isRelationType()) throw GraqlQueryException.kCoreOnRelationType(typeLabel);
return type.subs();
})
.map(SchemaConcept::label)
.collect(toSet());
}
Set<Label> scopeTypeLabels = Sets.union(scopeTypeLabels(query), targetTypeLabels);
if (!scopeContainsInstance(query)) {
return Stream.empty();
}
ComputerResult result;
Set<LabelId> scopeTypeLabelIDs = convertLabelsToIds(scopeTypeLabels);
Set<LabelId> targetTypeLabelIDs = convertLabelsToIds(targetTypeLabels);
try {
result = compute(new CorenessVertexProgram(k),
new DegreeDistributionMapReduce(targetTypeLabelIDs, CorenessVertexProgram.CORENESS),
scopeTypeLabelIDs);
} catch (NoResultException e) {
return Stream.empty();
}
Map<Long, Set<ConceptId>> centralityMap = result.memory().get(DegreeDistributionMapReduce.class.getName());
return centralityMap.entrySet().stream()
.map(centrality -> new ConceptSetMeasure(centrality.getValue(), centrality.getKey()));
} | java | private Stream<ConceptSetMeasure> runComputeCoreness(GraqlCompute.Centrality query) {
long k = query.where().minK().get();
if (k < 2L) throw GraqlQueryException.kValueSmallerThanTwo();
Set<Label> targetTypeLabels;
// Check if ofType is valid before returning emptyMap
if (query.of().isEmpty()) {
targetTypeLabels = scopeTypeLabels(query);
} else {
targetTypeLabels = query.of().stream()
.flatMap(t -> {
Label typeLabel = Label.of(t);
Type type = tx.getSchemaConcept(typeLabel);
if (type == null) throw GraqlQueryException.labelNotFound(typeLabel);
if (type.isRelationType()) throw GraqlQueryException.kCoreOnRelationType(typeLabel);
return type.subs();
})
.map(SchemaConcept::label)
.collect(toSet());
}
Set<Label> scopeTypeLabels = Sets.union(scopeTypeLabels(query), targetTypeLabels);
if (!scopeContainsInstance(query)) {
return Stream.empty();
}
ComputerResult result;
Set<LabelId> scopeTypeLabelIDs = convertLabelsToIds(scopeTypeLabels);
Set<LabelId> targetTypeLabelIDs = convertLabelsToIds(targetTypeLabels);
try {
result = compute(new CorenessVertexProgram(k),
new DegreeDistributionMapReduce(targetTypeLabelIDs, CorenessVertexProgram.CORENESS),
scopeTypeLabelIDs);
} catch (NoResultException e) {
return Stream.empty();
}
Map<Long, Set<ConceptId>> centralityMap = result.memory().get(DegreeDistributionMapReduce.class.getName());
return centralityMap.entrySet().stream()
.map(centrality -> new ConceptSetMeasure(centrality.getValue(), centrality.getKey()));
} | [
"private",
"Stream",
"<",
"ConceptSetMeasure",
">",
"runComputeCoreness",
"(",
"GraqlCompute",
".",
"Centrality",
"query",
")",
"{",
"long",
"k",
"=",
"query",
".",
"where",
"(",
")",
".",
"minK",
"(",
")",
".",
"get",
"(",
")",
";",
"if",
"(",
"k",
"<",
"2L",
")",
"throw",
"GraqlQueryException",
".",
"kValueSmallerThanTwo",
"(",
")",
";",
"Set",
"<",
"Label",
">",
"targetTypeLabels",
";",
"// Check if ofType is valid before returning emptyMap",
"if",
"(",
"query",
".",
"of",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"targetTypeLabels",
"=",
"scopeTypeLabels",
"(",
"query",
")",
";",
"}",
"else",
"{",
"targetTypeLabels",
"=",
"query",
".",
"of",
"(",
")",
".",
"stream",
"(",
")",
".",
"flatMap",
"(",
"t",
"->",
"{",
"Label",
"typeLabel",
"=",
"Label",
".",
"of",
"(",
"t",
")",
";",
"Type",
"type",
"=",
"tx",
".",
"getSchemaConcept",
"(",
"typeLabel",
")",
";",
"if",
"(",
"type",
"==",
"null",
")",
"throw",
"GraqlQueryException",
".",
"labelNotFound",
"(",
"typeLabel",
")",
";",
"if",
"(",
"type",
".",
"isRelationType",
"(",
")",
")",
"throw",
"GraqlQueryException",
".",
"kCoreOnRelationType",
"(",
"typeLabel",
")",
";",
"return",
"type",
".",
"subs",
"(",
")",
";",
"}",
")",
".",
"map",
"(",
"SchemaConcept",
"::",
"label",
")",
".",
"collect",
"(",
"toSet",
"(",
")",
")",
";",
"}",
"Set",
"<",
"Label",
">",
"scopeTypeLabels",
"=",
"Sets",
".",
"union",
"(",
"scopeTypeLabels",
"(",
"query",
")",
",",
"targetTypeLabels",
")",
";",
"if",
"(",
"!",
"scopeContainsInstance",
"(",
"query",
")",
")",
"{",
"return",
"Stream",
".",
"empty",
"(",
")",
";",
"}",
"ComputerResult",
"result",
";",
"Set",
"<",
"LabelId",
">",
"scopeTypeLabelIDs",
"=",
"convertLabelsToIds",
"(",
"scopeTypeLabels",
")",
";",
"Set",
"<",
"LabelId",
">",
"targetTypeLabelIDs",
"=",
"convertLabelsToIds",
"(",
"targetTypeLabels",
")",
";",
"try",
"{",
"result",
"=",
"compute",
"(",
"new",
"CorenessVertexProgram",
"(",
"k",
")",
",",
"new",
"DegreeDistributionMapReduce",
"(",
"targetTypeLabelIDs",
",",
"CorenessVertexProgram",
".",
"CORENESS",
")",
",",
"scopeTypeLabelIDs",
")",
";",
"}",
"catch",
"(",
"NoResultException",
"e",
")",
"{",
"return",
"Stream",
".",
"empty",
"(",
")",
";",
"}",
"Map",
"<",
"Long",
",",
"Set",
"<",
"ConceptId",
">",
">",
"centralityMap",
"=",
"result",
".",
"memory",
"(",
")",
".",
"get",
"(",
"DegreeDistributionMapReduce",
".",
"class",
".",
"getName",
"(",
")",
")",
";",
"return",
"centralityMap",
".",
"entrySet",
"(",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"centrality",
"->",
"new",
"ConceptSetMeasure",
"(",
"centrality",
".",
"getValue",
"(",
")",
",",
"centrality",
".",
"getKey",
"(",
")",
")",
")",
";",
"}"
] | The Graql compute centrality using k-core query run method
@return a Answer containing the centrality count map | [
"The",
"Graql",
"compute",
"centrality",
"using",
"k",
"-",
"core",
"query",
"run",
"method"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L423-L468 |
22,891 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.getComputePathResultList | private List<List<ConceptId>> getComputePathResultList(Multimap<ConceptId, ConceptId> resultGraph, ConceptId fromID) {
List<List<ConceptId>> allPaths = new ArrayList<>();
List<ConceptId> firstPath = new ArrayList<>();
firstPath.add(fromID);
Deque<List<ConceptId>> queue = new ArrayDeque<>();
queue.addLast(firstPath);
while (!queue.isEmpty()) {
List<ConceptId> currentPath = queue.pollFirst();
if (resultGraph.containsKey(currentPath.get(currentPath.size() - 1))) {
Collection<ConceptId> successors = resultGraph.get(currentPath.get(currentPath.size() - 1));
Iterator<ConceptId> iterator = successors.iterator();
for (int i = 0; i < successors.size() - 1; i++) {
List<ConceptId> extendedPath = new ArrayList<>(currentPath);
extendedPath.add(iterator.next());
queue.addLast(extendedPath);
}
currentPath.add(iterator.next());
queue.addLast(currentPath);
} else {
allPaths.add(currentPath);
}
}
return allPaths;
} | java | private List<List<ConceptId>> getComputePathResultList(Multimap<ConceptId, ConceptId> resultGraph, ConceptId fromID) {
List<List<ConceptId>> allPaths = new ArrayList<>();
List<ConceptId> firstPath = new ArrayList<>();
firstPath.add(fromID);
Deque<List<ConceptId>> queue = new ArrayDeque<>();
queue.addLast(firstPath);
while (!queue.isEmpty()) {
List<ConceptId> currentPath = queue.pollFirst();
if (resultGraph.containsKey(currentPath.get(currentPath.size() - 1))) {
Collection<ConceptId> successors = resultGraph.get(currentPath.get(currentPath.size() - 1));
Iterator<ConceptId> iterator = successors.iterator();
for (int i = 0; i < successors.size() - 1; i++) {
List<ConceptId> extendedPath = new ArrayList<>(currentPath);
extendedPath.add(iterator.next());
queue.addLast(extendedPath);
}
currentPath.add(iterator.next());
queue.addLast(currentPath);
} else {
allPaths.add(currentPath);
}
}
return allPaths;
} | [
"private",
"List",
"<",
"List",
"<",
"ConceptId",
">",
">",
"getComputePathResultList",
"(",
"Multimap",
"<",
"ConceptId",
",",
"ConceptId",
">",
"resultGraph",
",",
"ConceptId",
"fromID",
")",
"{",
"List",
"<",
"List",
"<",
"ConceptId",
">>",
"allPaths",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"List",
"<",
"ConceptId",
">",
"firstPath",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"firstPath",
".",
"add",
"(",
"fromID",
")",
";",
"Deque",
"<",
"List",
"<",
"ConceptId",
">",
">",
"queue",
"=",
"new",
"ArrayDeque",
"<>",
"(",
")",
";",
"queue",
".",
"addLast",
"(",
"firstPath",
")",
";",
"while",
"(",
"!",
"queue",
".",
"isEmpty",
"(",
")",
")",
"{",
"List",
"<",
"ConceptId",
">",
"currentPath",
"=",
"queue",
".",
"pollFirst",
"(",
")",
";",
"if",
"(",
"resultGraph",
".",
"containsKey",
"(",
"currentPath",
".",
"get",
"(",
"currentPath",
".",
"size",
"(",
")",
"-",
"1",
")",
")",
")",
"{",
"Collection",
"<",
"ConceptId",
">",
"successors",
"=",
"resultGraph",
".",
"get",
"(",
"currentPath",
".",
"get",
"(",
"currentPath",
".",
"size",
"(",
")",
"-",
"1",
")",
")",
";",
"Iterator",
"<",
"ConceptId",
">",
"iterator",
"=",
"successors",
".",
"iterator",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"successors",
".",
"size",
"(",
")",
"-",
"1",
";",
"i",
"++",
")",
"{",
"List",
"<",
"ConceptId",
">",
"extendedPath",
"=",
"new",
"ArrayList",
"<>",
"(",
"currentPath",
")",
";",
"extendedPath",
".",
"add",
"(",
"iterator",
".",
"next",
"(",
")",
")",
";",
"queue",
".",
"addLast",
"(",
"extendedPath",
")",
";",
"}",
"currentPath",
".",
"add",
"(",
"iterator",
".",
"next",
"(",
")",
")",
";",
"queue",
".",
"addLast",
"(",
"currentPath",
")",
";",
"}",
"else",
"{",
"allPaths",
".",
"add",
"(",
"currentPath",
")",
";",
"}",
"}",
"return",
"allPaths",
";",
"}"
] | Helper method to get list of all shortest paths
@param resultGraph edge map
@param fromID starting vertex
@return | [
"Helper",
"method",
"to",
"get",
"list",
"of",
"all",
"shortest",
"paths"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L551-L575 |
22,892 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.getComputePathResultListIncludingImplicitRelations | private List<List<ConceptId>> getComputePathResultListIncludingImplicitRelations(List<List<ConceptId>> allPaths) {
List<List<ConceptId>> extendedPaths = new ArrayList<>();
for (List<ConceptId> currentPath : allPaths) {
boolean hasAttribute = currentPath.stream().anyMatch(conceptID -> tx.getConcept(conceptID).isAttribute());
if (!hasAttribute) {
extendedPaths.add(currentPath);
}
}
// If there exist a path without attributes, we don't need to expand any path
// as paths contain attributes would be longer after implicit relations are added
int numExtensionAllowed = extendedPaths.isEmpty() ? Integer.MAX_VALUE : 0;
for (List<ConceptId> currentPath : allPaths) {
List<ConceptId> extendedPath = new ArrayList<>();
int numExtension = 0; // record the number of extensions needed for the current path
for (int j = 0; j < currentPath.size() - 1; j++) {
extendedPath.add(currentPath.get(j));
ConceptId resourceRelationId = Utility.getResourceEdgeId(tx, currentPath.get(j), currentPath.get(j + 1));
if (resourceRelationId != null) {
numExtension++;
if (numExtension > numExtensionAllowed) break;
extendedPath.add(resourceRelationId);
}
}
if (numExtension == numExtensionAllowed) {
extendedPath.add(currentPath.get(currentPath.size() - 1));
extendedPaths.add(extendedPath);
} else if (numExtension < numExtensionAllowed) {
extendedPath.add(currentPath.get(currentPath.size() - 1));
extendedPaths.clear(); // longer paths are discarded
extendedPaths.add(extendedPath);
// update the minimum number of extensions needed so all the paths have the same length
numExtensionAllowed = numExtension;
}
}
return extendedPaths;
} | java | private List<List<ConceptId>> getComputePathResultListIncludingImplicitRelations(List<List<ConceptId>> allPaths) {
List<List<ConceptId>> extendedPaths = new ArrayList<>();
for (List<ConceptId> currentPath : allPaths) {
boolean hasAttribute = currentPath.stream().anyMatch(conceptID -> tx.getConcept(conceptID).isAttribute());
if (!hasAttribute) {
extendedPaths.add(currentPath);
}
}
// If there exist a path without attributes, we don't need to expand any path
// as paths contain attributes would be longer after implicit relations are added
int numExtensionAllowed = extendedPaths.isEmpty() ? Integer.MAX_VALUE : 0;
for (List<ConceptId> currentPath : allPaths) {
List<ConceptId> extendedPath = new ArrayList<>();
int numExtension = 0; // record the number of extensions needed for the current path
for (int j = 0; j < currentPath.size() - 1; j++) {
extendedPath.add(currentPath.get(j));
ConceptId resourceRelationId = Utility.getResourceEdgeId(tx, currentPath.get(j), currentPath.get(j + 1));
if (resourceRelationId != null) {
numExtension++;
if (numExtension > numExtensionAllowed) break;
extendedPath.add(resourceRelationId);
}
}
if (numExtension == numExtensionAllowed) {
extendedPath.add(currentPath.get(currentPath.size() - 1));
extendedPaths.add(extendedPath);
} else if (numExtension < numExtensionAllowed) {
extendedPath.add(currentPath.get(currentPath.size() - 1));
extendedPaths.clear(); // longer paths are discarded
extendedPaths.add(extendedPath);
// update the minimum number of extensions needed so all the paths have the same length
numExtensionAllowed = numExtension;
}
}
return extendedPaths;
} | [
"private",
"List",
"<",
"List",
"<",
"ConceptId",
">",
">",
"getComputePathResultListIncludingImplicitRelations",
"(",
"List",
"<",
"List",
"<",
"ConceptId",
">",
">",
"allPaths",
")",
"{",
"List",
"<",
"List",
"<",
"ConceptId",
">>",
"extendedPaths",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"List",
"<",
"ConceptId",
">",
"currentPath",
":",
"allPaths",
")",
"{",
"boolean",
"hasAttribute",
"=",
"currentPath",
".",
"stream",
"(",
")",
".",
"anyMatch",
"(",
"conceptID",
"->",
"tx",
".",
"getConcept",
"(",
"conceptID",
")",
".",
"isAttribute",
"(",
")",
")",
";",
"if",
"(",
"!",
"hasAttribute",
")",
"{",
"extendedPaths",
".",
"add",
"(",
"currentPath",
")",
";",
"}",
"}",
"// If there exist a path without attributes, we don't need to expand any path",
"// as paths contain attributes would be longer after implicit relations are added",
"int",
"numExtensionAllowed",
"=",
"extendedPaths",
".",
"isEmpty",
"(",
")",
"?",
"Integer",
".",
"MAX_VALUE",
":",
"0",
";",
"for",
"(",
"List",
"<",
"ConceptId",
">",
"currentPath",
":",
"allPaths",
")",
"{",
"List",
"<",
"ConceptId",
">",
"extendedPath",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"int",
"numExtension",
"=",
"0",
";",
"// record the number of extensions needed for the current path",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"currentPath",
".",
"size",
"(",
")",
"-",
"1",
";",
"j",
"++",
")",
"{",
"extendedPath",
".",
"add",
"(",
"currentPath",
".",
"get",
"(",
"j",
")",
")",
";",
"ConceptId",
"resourceRelationId",
"=",
"Utility",
".",
"getResourceEdgeId",
"(",
"tx",
",",
"currentPath",
".",
"get",
"(",
"j",
")",
",",
"currentPath",
".",
"get",
"(",
"j",
"+",
"1",
")",
")",
";",
"if",
"(",
"resourceRelationId",
"!=",
"null",
")",
"{",
"numExtension",
"++",
";",
"if",
"(",
"numExtension",
">",
"numExtensionAllowed",
")",
"break",
";",
"extendedPath",
".",
"add",
"(",
"resourceRelationId",
")",
";",
"}",
"}",
"if",
"(",
"numExtension",
"==",
"numExtensionAllowed",
")",
"{",
"extendedPath",
".",
"add",
"(",
"currentPath",
".",
"get",
"(",
"currentPath",
".",
"size",
"(",
")",
"-",
"1",
")",
")",
";",
"extendedPaths",
".",
"add",
"(",
"extendedPath",
")",
";",
"}",
"else",
"if",
"(",
"numExtension",
"<",
"numExtensionAllowed",
")",
"{",
"extendedPath",
".",
"add",
"(",
"currentPath",
".",
"get",
"(",
"currentPath",
".",
"size",
"(",
")",
"-",
"1",
")",
")",
";",
"extendedPaths",
".",
"clear",
"(",
")",
";",
"// longer paths are discarded",
"extendedPaths",
".",
"add",
"(",
"extendedPath",
")",
";",
"// update the minimum number of extensions needed so all the paths have the same length",
"numExtensionAllowed",
"=",
"numExtension",
";",
"}",
"}",
"return",
"extendedPaths",
";",
"}"
] | Helper method t get the list of all shortest path, but also including the implicit relations that connect
entities and attributes
@param allPaths
@return | [
"Helper",
"method",
"t",
"get",
"the",
"list",
"of",
"all",
"shortest",
"path",
"but",
"also",
"including",
"the",
"implicit",
"relations",
"that",
"connect",
"entities",
"and",
"attributes"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L584-L620 |
22,893 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.scopeTypeLabelsImplicitPlayers | private Set<Label> scopeTypeLabelsImplicitPlayers(GraqlCompute query) {
return scopeTypes(query)
.filter(Concept::isRelationType)
.map(Concept::asRelationType)
.filter(RelationType::isImplicit)
.flatMap(RelationType::roles)
.flatMap(Role::players)
.map(SchemaConcept::label)
.collect(toSet());
} | java | private Set<Label> scopeTypeLabelsImplicitPlayers(GraqlCompute query) {
return scopeTypes(query)
.filter(Concept::isRelationType)
.map(Concept::asRelationType)
.filter(RelationType::isImplicit)
.flatMap(RelationType::roles)
.flatMap(Role::players)
.map(SchemaConcept::label)
.collect(toSet());
} | [
"private",
"Set",
"<",
"Label",
">",
"scopeTypeLabelsImplicitPlayers",
"(",
"GraqlCompute",
"query",
")",
"{",
"return",
"scopeTypes",
"(",
"query",
")",
".",
"filter",
"(",
"Concept",
"::",
"isRelationType",
")",
".",
"map",
"(",
"Concept",
"::",
"asRelationType",
")",
".",
"filter",
"(",
"RelationType",
"::",
"isImplicit",
")",
".",
"flatMap",
"(",
"RelationType",
"::",
"roles",
")",
".",
"flatMap",
"(",
"Role",
"::",
"players",
")",
".",
"map",
"(",
"SchemaConcept",
"::",
"label",
")",
".",
"collect",
"(",
"toSet",
"(",
")",
")",
";",
"}"
] | Helper method to get the label IDs of role players in a relation
@return a set of type label IDs | [
"Helper",
"method",
"to",
"get",
"the",
"label",
"IDs",
"of",
"role",
"players",
"in",
"a",
"relation"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L627-L636 |
22,894 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.getAttributeImplicitRelationTypeLabes | private static Set<Label> getAttributeImplicitRelationTypeLabes(Set<Type> types) {
// If the sub graph contains attributes, we may need to add implicit relations to the path
return types.stream()
.filter(Concept::isAttributeType)
.map(attributeType -> Schema.ImplicitType.HAS.getLabel(attributeType.label()))
.collect(toSet());
} | java | private static Set<Label> getAttributeImplicitRelationTypeLabes(Set<Type> types) {
// If the sub graph contains attributes, we may need to add implicit relations to the path
return types.stream()
.filter(Concept::isAttributeType)
.map(attributeType -> Schema.ImplicitType.HAS.getLabel(attributeType.label()))
.collect(toSet());
} | [
"private",
"static",
"Set",
"<",
"Label",
">",
"getAttributeImplicitRelationTypeLabes",
"(",
"Set",
"<",
"Type",
">",
"types",
")",
"{",
"// If the sub graph contains attributes, we may need to add implicit relations to the path",
"return",
"types",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"Concept",
"::",
"isAttributeType",
")",
".",
"map",
"(",
"attributeType",
"->",
"Schema",
".",
"ImplicitType",
".",
"HAS",
".",
"getLabel",
"(",
"attributeType",
".",
"label",
"(",
")",
")",
")",
".",
"collect",
"(",
"toSet",
"(",
")",
")",
";",
"}"
] | Helper method to get implicit relation types of attributes
@param types
@return a set of type Labels | [
"Helper",
"method",
"to",
"get",
"implicit",
"relation",
"types",
"of",
"attributes"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L644-L650 |
22,895 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.targetTypes | private ImmutableSet<Type> targetTypes(Computable.Targetable<?> query) {
if (query.of().isEmpty()) {
throw GraqlQueryException.statisticsAttributeTypesNotSpecified();
}
return query.of().stream()
.map(t -> {
Label label = Label.of(t);
Type type = tx.getSchemaConcept(label);
if (type == null) throw GraqlQueryException.labelNotFound(label);
if (!type.isAttributeType()) throw GraqlQueryException.mustBeAttributeType(type.label());
return type;
})
.flatMap(Type::subs)
.collect(CommonUtil.toImmutableSet());
} | java | private ImmutableSet<Type> targetTypes(Computable.Targetable<?> query) {
if (query.of().isEmpty()) {
throw GraqlQueryException.statisticsAttributeTypesNotSpecified();
}
return query.of().stream()
.map(t -> {
Label label = Label.of(t);
Type type = tx.getSchemaConcept(label);
if (type == null) throw GraqlQueryException.labelNotFound(label);
if (!type.isAttributeType()) throw GraqlQueryException.mustBeAttributeType(type.label());
return type;
})
.flatMap(Type::subs)
.collect(CommonUtil.toImmutableSet());
} | [
"private",
"ImmutableSet",
"<",
"Type",
">",
"targetTypes",
"(",
"Computable",
".",
"Targetable",
"<",
"?",
">",
"query",
")",
"{",
"if",
"(",
"query",
".",
"of",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"GraqlQueryException",
".",
"statisticsAttributeTypesNotSpecified",
"(",
")",
";",
"}",
"return",
"query",
".",
"of",
"(",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"t",
"->",
"{",
"Label",
"label",
"=",
"Label",
".",
"of",
"(",
"t",
")",
";",
"Type",
"type",
"=",
"tx",
".",
"getSchemaConcept",
"(",
"label",
")",
";",
"if",
"(",
"type",
"==",
"null",
")",
"throw",
"GraqlQueryException",
".",
"labelNotFound",
"(",
"label",
")",
";",
"if",
"(",
"!",
"type",
".",
"isAttributeType",
"(",
")",
")",
"throw",
"GraqlQueryException",
".",
"mustBeAttributeType",
"(",
"type",
".",
"label",
"(",
")",
")",
";",
"return",
"type",
";",
"}",
")",
".",
"flatMap",
"(",
"Type",
"::",
"subs",
")",
".",
"collect",
"(",
"CommonUtil",
".",
"toImmutableSet",
"(",
")",
")",
";",
"}"
] | Helper method to get the types to be included in the query target
@return a set of Types | [
"Helper",
"method",
"to",
"get",
"the",
"types",
"to",
"be",
"included",
"in",
"the",
"query",
"target"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L657-L672 |
22,896 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.targetTypeLabels | private Set<Label> targetTypeLabels(Computable.Targetable<?> query) {
return targetTypes(query).stream()
.map(SchemaConcept::label)
.collect(CommonUtil.toImmutableSet());
} | java | private Set<Label> targetTypeLabels(Computable.Targetable<?> query) {
return targetTypes(query).stream()
.map(SchemaConcept::label)
.collect(CommonUtil.toImmutableSet());
} | [
"private",
"Set",
"<",
"Label",
">",
"targetTypeLabels",
"(",
"Computable",
".",
"Targetable",
"<",
"?",
">",
"query",
")",
"{",
"return",
"targetTypes",
"(",
"query",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"SchemaConcept",
"::",
"label",
")",
".",
"collect",
"(",
"CommonUtil",
".",
"toImmutableSet",
"(",
")",
")",
";",
"}"
] | Helper method to get the labels of the type in the query target
@return a set of type Labels | [
"Helper",
"method",
"to",
"get",
"the",
"labels",
"of",
"the",
"type",
"in",
"the",
"query",
"target"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L679-L683 |
22,897 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.targetContainsInstance | private boolean targetContainsInstance(GraqlCompute.Statistics.Value query) {
for (Label attributeType : targetTypeLabels(query)) {
for (Label type : scopeTypeLabels(query)) {
Boolean patternExist = tx.stream(Graql.match(
Graql.var("x").has(attributeType.getValue(), Graql.var()),
Graql.var("x").isa(Graql.type(type.getValue()))
), false).iterator().hasNext();
if (patternExist) return true;
}
}
return false;
//TODO: should use the following ask query when ask query is even lazier
// List<Pattern> checkResourceTypes = statisticsResourceTypes.stream()
// .map(type -> var("x").has(type, var())).collect(Collectors.toList());
// List<Pattern> checkSubtypes = inTypes.stream()
// .map(type -> var("x").isa(Graql.label(type))).collect(Collectors.toList());
//
// return tx.get().graql().infer(false)
// .match(or(checkResourceTypes), or(checkSubtypes)).get().aggregate(ask()).execute();
} | java | private boolean targetContainsInstance(GraqlCompute.Statistics.Value query) {
for (Label attributeType : targetTypeLabels(query)) {
for (Label type : scopeTypeLabels(query)) {
Boolean patternExist = tx.stream(Graql.match(
Graql.var("x").has(attributeType.getValue(), Graql.var()),
Graql.var("x").isa(Graql.type(type.getValue()))
), false).iterator().hasNext();
if (patternExist) return true;
}
}
return false;
//TODO: should use the following ask query when ask query is even lazier
// List<Pattern> checkResourceTypes = statisticsResourceTypes.stream()
// .map(type -> var("x").has(type, var())).collect(Collectors.toList());
// List<Pattern> checkSubtypes = inTypes.stream()
// .map(type -> var("x").isa(Graql.label(type))).collect(Collectors.toList());
//
// return tx.get().graql().infer(false)
// .match(or(checkResourceTypes), or(checkSubtypes)).get().aggregate(ask()).execute();
} | [
"private",
"boolean",
"targetContainsInstance",
"(",
"GraqlCompute",
".",
"Statistics",
".",
"Value",
"query",
")",
"{",
"for",
"(",
"Label",
"attributeType",
":",
"targetTypeLabels",
"(",
"query",
")",
")",
"{",
"for",
"(",
"Label",
"type",
":",
"scopeTypeLabels",
"(",
"query",
")",
")",
"{",
"Boolean",
"patternExist",
"=",
"tx",
".",
"stream",
"(",
"Graql",
".",
"match",
"(",
"Graql",
".",
"var",
"(",
"\"x\"",
")",
".",
"has",
"(",
"attributeType",
".",
"getValue",
"(",
")",
",",
"Graql",
".",
"var",
"(",
")",
")",
",",
"Graql",
".",
"var",
"(",
"\"x\"",
")",
".",
"isa",
"(",
"Graql",
".",
"type",
"(",
"type",
".",
"getValue",
"(",
")",
")",
")",
")",
",",
"false",
")",
".",
"iterator",
"(",
")",
".",
"hasNext",
"(",
")",
";",
"if",
"(",
"patternExist",
")",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"//TODO: should use the following ask query when ask query is even lazier",
"// List<Pattern> checkResourceTypes = statisticsResourceTypes.stream()",
"// .map(type -> var(\"x\").has(type, var())).collect(Collectors.toList());",
"// List<Pattern> checkSubtypes = inTypes.stream()",
"// .map(type -> var(\"x\").isa(Graql.label(type))).collect(Collectors.toList());",
"//",
"// return tx.get().graql().infer(false)",
"// .match(or(checkResourceTypes), or(checkSubtypes)).get().aggregate(ask()).execute();",
"}"
] | Helper method to check whether the concept types in the target have any instances
@return true if they exist, false if they don't | [
"Helper",
"method",
"to",
"check",
"whether",
"the",
"concept",
"types",
"in",
"the",
"target",
"have",
"any",
"instances"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L690-L709 |
22,898 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.extendedScopeTypeLabels | private Set<Label> extendedScopeTypeLabels(GraqlCompute.Statistics.Value query) {
Set<Label> extendedTypeLabels = getAttributeImplicitRelationTypeLabes(targetTypes(query));
extendedTypeLabels.addAll(scopeTypeLabels(query));
extendedTypeLabels.addAll(query.of().stream().map(Label::of).collect(toSet()));
return extendedTypeLabels;
} | java | private Set<Label> extendedScopeTypeLabels(GraqlCompute.Statistics.Value query) {
Set<Label> extendedTypeLabels = getAttributeImplicitRelationTypeLabes(targetTypes(query));
extendedTypeLabels.addAll(scopeTypeLabels(query));
extendedTypeLabels.addAll(query.of().stream().map(Label::of).collect(toSet()));
return extendedTypeLabels;
} | [
"private",
"Set",
"<",
"Label",
">",
"extendedScopeTypeLabels",
"(",
"GraqlCompute",
".",
"Statistics",
".",
"Value",
"query",
")",
"{",
"Set",
"<",
"Label",
">",
"extendedTypeLabels",
"=",
"getAttributeImplicitRelationTypeLabes",
"(",
"targetTypes",
"(",
"query",
")",
")",
";",
"extendedTypeLabels",
".",
"addAll",
"(",
"scopeTypeLabels",
"(",
"query",
")",
")",
";",
"extendedTypeLabels",
".",
"addAll",
"(",
"query",
".",
"of",
"(",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"Label",
"::",
"of",
")",
".",
"collect",
"(",
"toSet",
"(",
")",
")",
")",
";",
"return",
"extendedTypeLabels",
";",
"}"
] | Helper method to get all the concept types that should scope of compute query, which includes the implicit types
between attributes and entities, if target types were provided. This is used for compute statistics queries.
@return a set of type labels | [
"Helper",
"method",
"to",
"get",
"all",
"the",
"concept",
"types",
"that",
"should",
"scope",
"of",
"compute",
"query",
"which",
"includes",
"the",
"implicit",
"types",
"between",
"attributes",
"and",
"entities",
"if",
"target",
"types",
"were",
"provided",
".",
"This",
"is",
"used",
"for",
"compute",
"statistics",
"queries",
"."
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L717-L722 |
22,899 | graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.scopeTypes | private Stream<Type> scopeTypes(GraqlCompute query) {
// Get all types if query.inTypes() is empty, else get all scoped types of each meta type.
// Only include attributes and implicit "has-xxx" relations when user specifically asked for them.
if (query.in().isEmpty()) {
ImmutableSet.Builder<Type> typeBuilder = ImmutableSet.builder();
if (scopeIncludesAttributes(query)) {
tx.getMetaConcept().subs().forEach(typeBuilder::add);
} else {
tx.getMetaEntityType().subs().forEach(typeBuilder::add);
tx.getMetaRelationType().subs()
.filter(relationType -> !relationType.isImplicit()).forEach(typeBuilder::add);
}
return typeBuilder.build().stream();
} else {
Stream<Type> subTypes = query.in().stream().map(t -> {
Label label = Label.of(t);
Type type = tx.getType(label);
if (type == null) throw GraqlQueryException.labelNotFound(label);
return type;
}).flatMap(Type::subs);
if (!scopeIncludesAttributes(query)) {
subTypes = subTypes.filter(relationType -> !relationType.isImplicit());
}
return subTypes;
}
} | java | private Stream<Type> scopeTypes(GraqlCompute query) {
// Get all types if query.inTypes() is empty, else get all scoped types of each meta type.
// Only include attributes and implicit "has-xxx" relations when user specifically asked for them.
if (query.in().isEmpty()) {
ImmutableSet.Builder<Type> typeBuilder = ImmutableSet.builder();
if (scopeIncludesAttributes(query)) {
tx.getMetaConcept().subs().forEach(typeBuilder::add);
} else {
tx.getMetaEntityType().subs().forEach(typeBuilder::add);
tx.getMetaRelationType().subs()
.filter(relationType -> !relationType.isImplicit()).forEach(typeBuilder::add);
}
return typeBuilder.build().stream();
} else {
Stream<Type> subTypes = query.in().stream().map(t -> {
Label label = Label.of(t);
Type type = tx.getType(label);
if (type == null) throw GraqlQueryException.labelNotFound(label);
return type;
}).flatMap(Type::subs);
if (!scopeIncludesAttributes(query)) {
subTypes = subTypes.filter(relationType -> !relationType.isImplicit());
}
return subTypes;
}
} | [
"private",
"Stream",
"<",
"Type",
">",
"scopeTypes",
"(",
"GraqlCompute",
"query",
")",
"{",
"// Get all types if query.inTypes() is empty, else get all scoped types of each meta type.",
"// Only include attributes and implicit \"has-xxx\" relations when user specifically asked for them.",
"if",
"(",
"query",
".",
"in",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"ImmutableSet",
".",
"Builder",
"<",
"Type",
">",
"typeBuilder",
"=",
"ImmutableSet",
".",
"builder",
"(",
")",
";",
"if",
"(",
"scopeIncludesAttributes",
"(",
"query",
")",
")",
"{",
"tx",
".",
"getMetaConcept",
"(",
")",
".",
"subs",
"(",
")",
".",
"forEach",
"(",
"typeBuilder",
"::",
"add",
")",
";",
"}",
"else",
"{",
"tx",
".",
"getMetaEntityType",
"(",
")",
".",
"subs",
"(",
")",
".",
"forEach",
"(",
"typeBuilder",
"::",
"add",
")",
";",
"tx",
".",
"getMetaRelationType",
"(",
")",
".",
"subs",
"(",
")",
".",
"filter",
"(",
"relationType",
"->",
"!",
"relationType",
".",
"isImplicit",
"(",
")",
")",
".",
"forEach",
"(",
"typeBuilder",
"::",
"add",
")",
";",
"}",
"return",
"typeBuilder",
".",
"build",
"(",
")",
".",
"stream",
"(",
")",
";",
"}",
"else",
"{",
"Stream",
"<",
"Type",
">",
"subTypes",
"=",
"query",
".",
"in",
"(",
")",
".",
"stream",
"(",
")",
".",
"map",
"(",
"t",
"->",
"{",
"Label",
"label",
"=",
"Label",
".",
"of",
"(",
"t",
")",
";",
"Type",
"type",
"=",
"tx",
".",
"getType",
"(",
"label",
")",
";",
"if",
"(",
"type",
"==",
"null",
")",
"throw",
"GraqlQueryException",
".",
"labelNotFound",
"(",
"label",
")",
";",
"return",
"type",
";",
"}",
")",
".",
"flatMap",
"(",
"Type",
"::",
"subs",
")",
";",
"if",
"(",
"!",
"scopeIncludesAttributes",
"(",
"query",
")",
")",
"{",
"subTypes",
"=",
"subTypes",
".",
"filter",
"(",
"relationType",
"->",
"!",
"relationType",
".",
"isImplicit",
"(",
")",
")",
";",
"}",
"return",
"subTypes",
";",
"}",
"}"
] | Helper method to get the types to be included in the query scope
@return stream of Concept Types | [
"Helper",
"method",
"to",
"get",
"the",
"types",
"to",
"be",
"included",
"in",
"the",
"query",
"scope"
] | 6aaee75ea846202474d591f8809d62028262fac5 | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L729-L758 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.