Unnamed: 0
int64 0
9.45k
| cwe_id
stringclasses 1
value | source
stringlengths 37
2.53k
| target
stringlengths 19
2.4k
|
---|---|---|---|
9,400 | public StudentEnrolment getOne(){
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the student id");
Student student = studentList.get(scanner.nextLine());
System.out.println("Please enter the course id");
Course course = courseList.get(scanner.nextLine());
System.out.println("Please enter the semester");
String semester = scanner.nextLine();
for (StudentEnrolment se : studentEnrolmentList) {
if (se.getStudent().getStudentId().equals(student.getStudentId()) && se.getCourse().getCourseId().equals(course.getCourseId()) && se.getSemester().equals(semester)) {
System.out.println(se);
return se;
}
}
System.out.println("No such enrolment found");
return null;
} | public StudentEnrolment getOne(){
Student student = studentList.getStudent();
Course course = courseList.getCourse();
String semester = Menu.getSemester();
for (StudentEnrolment se : studentEnrolmentList) {
if (se.getStudent().getStudentId().equals(student.getStudentId()) && se.getCourse().getCourseId().equals(course.getCourseId()) && se.getSemester().equals(semester)) {
System.out.println(se);
return se;
}
}
System.out.println("No such enrolment found");
return null;
} |
|
9,401 | public File buildGeoJSONFile(Graph<Node, GraphEdge> graph, String filePath) throws IOException{
File file = new File(filePath);
try {
FileWriter writer = new FileWriter(file, false);
writer.write(buildGeoJSONString(graph));
writer.close();
logger.debug("GeoJSON has been written into file successfully");
} catch (IOException e) {
logger.error(e.getMessage());
}
return file;
} | public File buildGeoJSONFile(Graph<Node, GraphEdge> graph, File file) throws IOException{
try {
FileWriter writer = new FileWriter(file, false);
writer.write(buildGeoJSONString(graph));
writer.close();
logger.debug("GeoJSON has been written into file successfully");
} catch (IOException e) {
logger.error(e.getMessage());
}
return file;
} |
|
9,402 | public void run(){
InputStreamReader isr_ = null;
BufferedReader in_ = null;
try {
isr_ = new InputStreamReader(getSocket().getInputStream());
in_ = new BufferedReader(isr_);
String input_;
while (true) {
input_ = in_.readLine();
if (input_ == null) {
break;
}
Object readObject_ = net.getObject(input_);
if (readObject_ == null) {
continue;
}
loopServer(input_, readObject_);
}
close(in_);
close(isr_);
close(getSocket());
} catch (Throwable _0) {
close(in_);
close(isr_);
close(getSocket());
}
} | public void run(){
InputStreamReader isr_;
BufferedReader in_;
try {
isr_ = new InputStreamReader(getSocket().getInputStream());
in_ = new BufferedReader(isr_);
String input_;
while (true) {
input_ = in_.readLine();
if (input_ == null) {
break;
}
Object readObject_ = net.getObject(input_);
if (readObject_ == null) {
continue;
}
loopServer(input_, readObject_);
}
} catch (IOException _0) {
} finally {
close(getSocket());
}
} |
|
9,403 | private static BigInteger decodeBinary(ByteBuf value, FieldInformation info){
boolean isUnsigned = (info.getDefinitions() & ColumnDefinitions.UNSIGNED) != 0;
switch(info.getType()) {
case DataTypes.BIGINT:
long v = value.readLongLE();
if (isUnsigned && v < 0) {
return unsignedBigInteger(v);
}
return BigInteger.valueOf(v);
case DataTypes.INT:
if (isUnsigned) {
return BigInteger.valueOf(value.readUnsignedIntLE());
}
return BigInteger.valueOf(value.readIntLE());
case DataTypes.MEDIUMINT:
return BigInteger.valueOf(value.readIntLE());
case DataTypes.SMALLINT:
if (isUnsigned) {
return BigInteger.valueOf(value.readUnsignedShortLE());
}
return BigInteger.valueOf(value.readShortLE());
case DataTypes.YEAR:
return BigInteger.valueOf(value.readShortLE());
default:
if (isUnsigned) {
return BigInteger.valueOf(value.readUnsignedByte());
}
return BigInteger.valueOf(value.readByte());
}
} | private static BigInteger decodeBinary(ByteBuf value, MySqlColumnMetadata metadata){
switch(metadata.getType()) {
case BIGINT_UNSIGNED:
long v = value.readLongLE();
if (v < 0) {
return unsignedBigInteger(v);
}
return BigInteger.valueOf(v);
case BIGINT:
return BigInteger.valueOf(value.readLongLE());
case INT_UNSIGNED:
return BigInteger.valueOf(value.readUnsignedIntLE());
case INT:
case MEDIUMINT_UNSIGNED:
case MEDIUMINT:
return BigInteger.valueOf(value.readIntLE());
case SMALLINT_UNSIGNED:
return BigInteger.valueOf(value.readUnsignedShortLE());
case SMALLINT:
case YEAR:
return BigInteger.valueOf(value.readShortLE());
case TINYINT_UNSIGNED:
return BigInteger.valueOf(value.readUnsignedByte());
case TINYINT:
return BigInteger.valueOf(value.readByte());
}
throw new IllegalStateException("Cannot decode type " + metadata.getType() + " as a BigInteger");
} |
|
9,404 | public Map<String, String> getTags(){
Map<String, String> tagsMap = null;
if (tags != null && !tags.isEmpty()) {
tagsMap = new HashMap<String, String>();
Collection<?> servicesCollection = tags.values();
Iterator<?> iter = servicesCollection.iterator();
while (iter.hasNext()) {
HashMap<String, String> services = (HashMap<String, String>) iter.next();
String key = services.get("key");
String value = services.get("value");
if (value == null) {
throw new InvalidParameterValueException("No value is passed in for key " + key);
}
tagsMap.put(key, value);
}
}
return tagsMap;
} | public Map<String, String> getTags(){
return TaggedResources.parseKeyValueMap(tags, false);
} |
|
9,405 | public void removeAll(CharID id, Object source){
Map<T, Set<Object>> componentMap = getCachedMap(id);
if (componentMap != null) {
List<T> removedKeys = new ArrayList<>();
for (Iterator<Map.Entry<T, Set<Object>>> it = componentMap.entrySet().iterator(); it.hasNext(); ) {
Entry<T, Set<Object>> me = it.next();
Set<Object> set = me.getValue();
if (set.remove(source) && set.isEmpty()) {
T obj = me.getKey();
it.remove();
removedKeys.add(obj);
}
}
if (componentMap.isEmpty()) {
removeCache(id);
}
for (T obj : removedKeys) {
fireDataFacetChangeEvent(id, obj, DataFacetChangeEvent.DATA_REMOVED);
}
}
} | public void removeAll(CharID id, Object source){
Map<T, Set<Object>> componentMap = getCachedMap(id);
if (componentMap != null) {
Collection<T> removedKeys = new ArrayList<>();
for (Iterator<Map.Entry<T, Set<Object>>> it = componentMap.entrySet().iterator(); it.hasNext(); ) {
Entry<T, Set<Object>> me = it.next();
Set<Object> set = me.getValue();
if (set.remove(source) && set.isEmpty()) {
T obj = me.getKey();
it.remove();
removedKeys.add(obj);
}
}
if (componentMap.isEmpty()) {
removeCache(id);
}
removedKeys.forEach(obj -> fireDataFacetChangeEvent(id, obj, DataFacetChangeEvent.DATA_REMOVED));
}
} |
|
9,406 | public Flux<GitLabIssue> getIssues(Principal principal, @PathVariable("projectId") Long projectId, @RequestParam("startDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime startDateTime, @RequestParam("endDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime endDateTime){
var project = projectService.getProjectById(projectId);
if (!hasPermission(principal, projectId)) {
throw new AccessDeniedException("User has no permission to see this project.");
}
var gitLabService = new GitLabService(serverUrl, accessToken);
return gitLabService.getIssues(project.getGitLabProjectId(), startDateTime, endDateTime);
} | public Flux<GitLabIssue> getIssues(Principal principal, @PathVariable("projectId") Long projectId, @RequestParam("startDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime startDateTime, @RequestParam("endDateTime") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime endDateTime){
var project = projectService.getProjectById(projectId);
validatePermission(principal, projectId);
var gitLabService = new GitLabService(serverUrl, accessToken);
return gitLabService.getIssues(project.getGitLabProjectId(), startDateTime, endDateTime);
} |
|
9,407 | public void onCreate(Bundle savedInstanceState){
setTheme(R.style.Theme_MLand_Splash);
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.BLUE);
}
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent mainIntent = new Intent(Splash.this, Home.class);
Splash.this.startActivity(mainIntent);
Splash.this.finish();
}
}, SPLASH_DISPLAY_LENGTH);
} | public void onCreate(Bundle savedInstanceState){
setTheme(R.style.Theme_MLand_Splash);
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.BLUE);
}
new Handler().postDelayed(() -> {
Intent mainIntent = new Intent(Splash.this, Home.class);
Splash.this.startActivity(mainIntent);
Splash.this.finish();
}, SPLASH_DISPLAY_LENGTH);
} |
|
9,408 | public boolean equals(Object o){
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
RoleEntity that = (RoleEntity) o;
if (id != that.id)
return false;
if (name != null ? !name.equals(that.name) : that.name != null)
return false;
return true;
} | public boolean equals(Object o){
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
RoleEntity that = (RoleEntity) o;
if (id != that.id)
return false;
return name != null ? name.equals(that.name) : that.name == null;
} |
|
9,409 | public ResourceId getTargetMatchId(int sourceKeyIndex){
int row = getTargetMatchRow(sourceKeyIndex);
ResourceId id = graph.getTargetForm().getRowId(row);
return id;
} | public ResourceId getTargetMatchId(int sourceKeyIndex){
int row = getTargetMatchRow(sourceKeyIndex);
return graph.getTargetForm().getRowId(row);
} |
|
9,410 | private String sendMailToResetPass(@ModelAttribute("login") Login login, ModelMap model){
Registration registration = registrationService.getLoggedInUserInfo(login.getEmail());
boolean status = false;
try {
login.setRegistration_Id(registration.getRegistrationId());
status = registrationService.sendMailToResetPass(login);
} catch (Exception e) {
e.printStackTrace();
}
if (status) {
model.addAttribute("message", IConstant.MAIL_SUCCESS_MESSAGE);
} else {
model.addAttribute("message", IConstant.MAIL_FAILURE_MESSAGE);
}
return "redirect:/forgotPassword";
} | private String sendMailToResetPass(@ModelAttribute("login") Login login, ModelMap model){
Registration registration = registrationService.getLoggedInUserInfo(login.getEmail());
boolean status = false;
try {
login.setRegistration_Id(registration.getRegistrationId());
status = registrationService.sendMailToResetPass(login);
} catch (Exception e) {
e.printStackTrace();
}
if (status)
model.addAttribute("message", IConstant.MAIL_SUCCESS_MESSAGE);
else
model.addAttribute("message", IConstant.MAIL_FAILURE_MESSAGE);
return "redirect:/forgotPassword";
} |
|
9,411 | private Direction[] getDirections(BoardCell cell){
if (cell.isKingPiece()) {
return kingDirections;
}
if (cell.getCondition() == BoardCell.WHITE_PIECE) {
return whiteDirections;
}
if (cell.getCondition() == BoardCell.BLACK_PIECE) {
return blackDirections;
}
return null;
} | private Direction[] getDirections(BoardCell cell){
if (cell.isKingPiece()) {
return kingDirections;
} else if (cell.getCondition() == BoardCell.WHITE_PIECE) {
return whiteDirections;
} else {
return blackDirections;
}
} |
|
9,412 | public void testAllocateResourceMultipleAllocations1(){
System.out.println("testAllocateResourceMultipleAllocations1");
final Ram instance = createResource();
long allocation = 0, totalAllocation = 0;
assertEquals(allocation, instance.getAllocatedResource());
allocation = THREE_QUARTERS_OF_CAPACITY;
totalAllocation += allocation;
boolean result = instance.allocateResource(allocation);
assertTrue(result);
assertEquals(totalAllocation, instance.getAllocatedResource());
assertEquals(CAPACITY, instance.getCapacity());
allocation = THREE_QUARTERS_OF_CAPACITY;
result = instance.allocateResource(allocation);
assertFalse(result);
assertEquals(totalAllocation, instance.getAllocatedResource());
allocation = QUARTER_OF_CAPACITY;
totalAllocation += allocation;
result = instance.allocateResource(allocation);
assertTrue(result);
assertEquals(totalAllocation, instance.getAllocatedResource());
allocation = QUARTER_OF_CAPACITY;
result = instance.allocateResource(allocation);
assertFalse(result);
assertEquals(totalAllocation, instance.getAllocatedResource());
} | public void testAllocateResourceMultipleAllocations1(){
final Ram instance = createResource();
long allocation = 0, totalAllocation = 0;
assertEquals(allocation, instance.getAllocatedResource());
allocation = THREE_QUARTERS_OF_CAPACITY;
totalAllocation += allocation;
boolean result = instance.allocateResource(allocation);
assertTrue(result);
assertEquals(totalAllocation, instance.getAllocatedResource());
assertEquals(CAPACITY, instance.getCapacity());
allocation = THREE_QUARTERS_OF_CAPACITY;
result = instance.allocateResource(allocation);
assertFalse(result);
assertEquals(totalAllocation, instance.getAllocatedResource());
allocation = QUARTER_OF_CAPACITY;
totalAllocation += allocation;
result = instance.allocateResource(allocation);
assertTrue(result);
assertEquals(totalAllocation, instance.getAllocatedResource());
allocation = QUARTER_OF_CAPACITY;
result = instance.allocateResource(allocation);
assertFalse(result);
assertEquals(totalAllocation, instance.getAllocatedResource());
} |
|
9,413 | public void onGlobalLayout(){
if (mStatusBar.getStatusBarWindow().getHeight() != mStatusBar.getStatusBarHeight()) {
getViewTreeObserver().removeOnGlobalLayoutListener(this);
if (animate) {
mBar.startOpeningPanel(PanelView.this);
notifyExpandingStarted();
fling(0, true);
} else {
setExpandedFraction(1f);
}
mInstantExpanding = false;
}
} | public void onGlobalLayout(){
if (mStatusBar.getStatusBarWindow().getHeight() != mStatusBar.getStatusBarHeight()) {
getViewTreeObserver().removeOnGlobalLayoutListener(this);
if (animate) {
notifyExpandingStarted();
fling(0, true);
} else {
setExpandedFraction(1f);
}
mInstantExpanding = false;
}
} |
|
9,414 | public boolean undo(){
if (!undo.isEmpty()) {
try {
writeToFile(undo.peek());
} catch (IOException e) {
e.printStackTrace();
}
currentJsonString = undo.peek();
redo.push(undo.pop());
try {
set = jsonToSet();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
return false;
} | public boolean undo(){
if (!undo.isEmpty()) {
try {
writeToFile(undo.peek());
} catch (IOException e) {
e.printStackTrace();
}
currentJsonString = undo.peek();
redo.push(undo.pop());
return true;
}
return false;
} |
|
9,415 | public void loadFile(Context context) throws SQLDataException{
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String email;
if ((email = sharedPreferences.getString("email", null)) != null) {
ExplorerDAO dataBase = new ExplorerDAO(context);
Explorer explorer = dataBase.findExplorer(email);
dataBase.close();
this.explorer = new Explorer(explorer.getEmail(), explorer.getNickname(), explorer.getPassword());
} else {
throw new SQLDataException();
}
} | public void loadFile(Context context) throws SQLDataException{
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String email;
if ((email = sharedPreferences.getString("email", null)) != null) {
ExplorerDAO dataBase = new ExplorerDAO(context);
Explorer explorer = dataBase.findExplorer(email);
dataBase.close();
this.explorer = new Explorer(explorer.getEmail(), explorer.getNickname(), explorer.getPassword());
}
} |
|
9,416 | public DocumentResult parse(String _input){
DocumentResult res_ = new DocumentResult();
FullDocument doc_ = new FullDocument(getTabWidth());
int firstPrint_ = StringUtil.getFirstPrintableCharIndex(_input);
if (firstPrint_ < 0) {
res_.setLocation(new RowCol());
return res_;
}
String input_ = _input.substring(firstPrint_);
int len_ = input_.length();
int indexFoot_ = 0;
ReadingState state_ = ReadingState.HEADER;
boolean addChild_ = true;
char delimiterAttr_ = 0;
StringBuilder attributeName_ = new StringBuilder();
StringBuilder tagName_ = new StringBuilder();
StringList stack_ = new StringList();
StringBuilder currentText_ = new StringBuilder();
FullElement currentElement_ = (FullElement) doc_.createElement(tagName_.toString());
boolean finished_ = false;
StringBuilder attributeValue_ = new StringBuilder();
CustList<Attr> attrs_ = new CustList<Attr>();
int i_ = IndexConstants.FIRST_INDEX;
if (input_.charAt(i_) != LT) {
RowCol rc_ = new RowCol();
rc_.setRow(1);
rc_.setCol(1);
res_.setLocation(rc_);
return res_;
}
i_++;
ParseFullTextState st_ = new ParseFullTextState(doc_, currentElement_, input_, i_);
while (st_.getIndex() < len_) {
if (!st_.keep()) {
break;
}
}
if (!st_.isFinished()) {
return processErr(res_, input_, len_, st_.getIndex(), doc_.getTabWidth());
}
res_.setDocument(doc_);
return res_;
} | public DocumentResult parse(String _input){
DocumentResult res_ = new DocumentResult();
FullDocument doc_ = new FullDocument(getTabWidth());
int firstPrint_ = StringUtil.getFirstPrintableCharIndex(_input);
if (firstPrint_ < 0) {
res_.setLocation(new RowCol());
return res_;
}
String input_ = _input.substring(firstPrint_);
int len_ = input_.length();
FullElement currentElement_ = (FullElement) doc_.createElement("");
int i_ = IndexConstants.FIRST_INDEX;
if (input_.charAt(i_) != LT) {
RowCol rc_ = new RowCol();
rc_.setRow(1);
rc_.setCol(1);
res_.setLocation(rc_);
return res_;
}
i_++;
ParseFullTextState st_ = new ParseFullTextState(doc_, currentElement_, input_, i_);
while (st_.getIndex() < len_) {
if (!st_.keep()) {
break;
}
}
if (!st_.isFinished()) {
return processErr(res_, input_, len_, st_.getIndex(), doc_.getTabWidth());
}
res_.setDocument(doc_);
return res_;
} |
|
9,417 | public static Direction of(boolean left, boolean right){
if (left == true && right == true) {
throw new IllegalStateException("direction can't be (true, true)");
}
return new Direction(left, right);
} | public static Direction of(boolean left, boolean right){
return new Direction(left, right);
} |
|
9,418 | static List<DbUnitConfigInterceptor> readConfig(DbUnitConfig annotation){
if (annotation == null) {
return emptyList();
}
List<DbUnitConfigInterceptor> defaultInterceptors = asList((DbUnitConfigInterceptor) new DbUnitAllowEmptyFieldsInterceptor(annotation.allowEmptyFields()), new DbUnitQualifiedTableNamesInterceptor(annotation.qualifiedTableNames()), new DbUnitCaseSensitiveTableNamesInterceptor(annotation.allowEmptyFields()), new DbUnitBatchedStatementsInterceptor(annotation.allowEmptyFields()), new DbUnitDatatypeWarningInterceptor(annotation.allowEmptyFields()), new DbUnitDatatypeFactoryInterceptor(annotation.datatypeFactory()), new DbUnitFetchSizeInterceptor(annotation.fetchSize()), new DbUnitBatchSizeInterceptor(annotation.batchSize()), new DbUnitMetadataHandlerInterceptor(annotation.metadataHandler()));
Class<? extends DbUnitConfigInterceptor>[] interceptorClasses = annotation.value();
if (interceptorClasses.length == 0) {
return defaultInterceptors;
}
List<DbUnitConfigInterceptor> customInterceptors = map(interceptorClasses, new Mapper<Class<? extends DbUnitConfigInterceptor>, DbUnitConfigInterceptor>() {
@Override
public DbUnitConfigInterceptor apply(Class<? extends DbUnitConfigInterceptor> input) {
return ClassUtils.instantiate(input);
}
});
List<DbUnitConfigInterceptor> interceptors = new ArrayList<>(customInterceptors.size() + defaultInterceptors.size());
interceptors.addAll(defaultInterceptors);
interceptors.addAll(customInterceptors);
return interceptors;
} | static List<DbUnitConfigInterceptor> readConfig(DbUnitConfig annotation){
if (annotation == null) {
return emptyList();
}
List<DbUnitConfigInterceptor> defaultInterceptors = asList(new DbUnitAllowEmptyFieldsInterceptor(annotation.allowEmptyFields()), new DbUnitQualifiedTableNamesInterceptor(annotation.qualifiedTableNames()), new DbUnitCaseSensitiveTableNamesInterceptor(annotation.allowEmptyFields()), new DbUnitBatchedStatementsInterceptor(annotation.allowEmptyFields()), new DbUnitDatatypeWarningInterceptor(annotation.allowEmptyFields()), new DbUnitDatatypeFactoryInterceptor(annotation.datatypeFactory()), new DbUnitFetchSizeInterceptor(annotation.fetchSize()), new DbUnitBatchSizeInterceptor(annotation.batchSize()), new DbUnitMetadataHandlerInterceptor(annotation.metadataHandler()));
Class<? extends DbUnitConfigInterceptor>[] interceptorClasses = annotation.value();
if (interceptorClasses.length == 0) {
return defaultInterceptors;
}
List<DbUnitConfigInterceptor> customInterceptors = Arrays.stream(interceptorClasses).map(ClassUtils::instantiate).collect(Collectors.toList());
List<DbUnitConfigInterceptor> interceptors = new ArrayList<>(customInterceptors.size() + defaultInterceptors.size());
interceptors.addAll(defaultInterceptors);
interceptors.addAll(customInterceptors);
return interceptors;
} |
|
9,419 | public PreparedLayer call() throws IOException, CacheCorruptedException, RegistryException{
DescriptorDigest layerDigest = layer.getBlobDescriptor().getDigest();
try (ProgressEventDispatcher progressEventDispatcher = progressEventDispatcherFactory.create("checking base image layer " + layerDigest, 1);
TimerEventDispatcher ignored = new TimerEventDispatcher(buildConfiguration.getEventHandlers(), String.format(DESCRIPTION, layerDigest))) {
Cache cache = buildConfiguration.getBaseImageLayersCache();
Optional<CachedLayer> optionalCachedLayer = cache.retrieve(layerDigest);
boolean checkBlob = registryPush && !Boolean.getBoolean("jib.forceDownload");
if (checkBlob) {
Verify.verify(!buildConfiguration.isOffline());
RegistryClient targetRegistryClient = buildConfiguration.newTargetImageRegistryClientFactory().setAuthorization(pushAuthorization).newRegistryClient();
if (targetRegistryClient.checkBlob(layerDigest) != null) {
return new PreparedLayer.Builder(layer).existsInTarget().build();
}
}
if (optionalCachedLayer.isPresent()) {
return new PreparedLayer.Builder(optionalCachedLayer.get()).doesNotExistInTarget().build();
} else if (buildConfiguration.isOffline()) {
throw new IOException("Cannot run Jib in offline mode; local Jib cache for base image is missing image layer " + layerDigest + ". Rerun Jib in online mode with \"-Djib.forceDownload=true\" to re-download the " + "base image layers.");
}
RegistryClient registryClient = buildConfiguration.newBaseImageRegistryClientFactory().setAuthorization(pullAuthorization).newRegistryClient();
try (ThrottledProgressEventDispatcherWrapper progressEventDispatcherWrapper = new ThrottledProgressEventDispatcherWrapper(progressEventDispatcher.newChildProducer(), "pulling base image layer " + layerDigest)) {
CachedLayer cachedLayer = cache.writeCompressedLayer(registryClient.pullBlob(layerDigest, progressEventDispatcherWrapper::setProgressTarget, progressEventDispatcherWrapper::dispatchProgress));
return new PreparedLayer.Builder(cachedLayer).build();
}
}
} | public PreparedLayer call() throws IOException, CacheCorruptedException, RegistryException{
DescriptorDigest layerDigest = layer.getBlobDescriptor().getDigest();
try (ProgressEventDispatcher progressEventDispatcher = progressEventDispatcherFactory.create("checking base image layer " + layerDigest, 1);
TimerEventDispatcher ignored = new TimerEventDispatcher(buildConfiguration.getEventHandlers(), String.format(DESCRIPTION, layerDigest))) {
Optional<Boolean> layerExists = layerChecker.exists(layer);
if (layerExists.orElse(false)) {
return new PreparedLayer.Builder(layer).setStateInTarget(layerExists).build();
}
Cache cache = buildConfiguration.getBaseImageLayersCache();
Optional<CachedLayer> optionalCachedLayer = cache.retrieve(layerDigest);
if (optionalCachedLayer.isPresent()) {
CachedLayer cachedLayer = optionalCachedLayer.get();
return new PreparedLayer.Builder(cachedLayer).setStateInTarget(layerExists).build();
} else if (buildConfiguration.isOffline()) {
throw new IOException("Cannot run Jib in offline mode; local Jib cache for base image is missing image layer " + layerDigest + ". Rerun Jib in online mode with \"-Djib.forceDownload=true\" to re-download the " + "base image layers.");
}
RegistryClient registryClient = buildConfiguration.newBaseImageRegistryClientFactory().setAuthorization(pullAuthorization).newRegistryClient();
try (ThrottledProgressEventDispatcherWrapper progressEventDispatcherWrapper = new ThrottledProgressEventDispatcherWrapper(progressEventDispatcher.newChildProducer(), "pulling base image layer " + layerDigest)) {
CachedLayer cachedLayer = cache.writeCompressedLayer(registryClient.pullBlob(layerDigest, progressEventDispatcherWrapper::setProgressTarget, progressEventDispatcherWrapper::dispatchProgress));
return new PreparedLayer.Builder(cachedLayer).setStateInTarget(layerExists).build();
}
}
} |
|
9,420 | public void init(){
display.startGLFW();
display.startScreen();
pauseButtons = new ArrayList<>();
models = new ArrayList<>();
modelsOldRenderMethod = new ArrayList<>();
cam = new CameraLWJGL(this, null, null, null, new Vector(new float[] { 0, 7, 5 }), 90, 0.001f, 100, display.getWidth(), display.getHeight());
renderingEngine.resetBuffers();
initModels();
initPauseScreen();
initInputControls();
renderingEngine.setProjectionMode(ProjectionMode.PERSPECTIVE);
renderingEngine.setRenderPipeline(RenderPipeline.Matrix);
cam.updateValues();
cam.lookAtModel(models.get(lookAtIndex));
} | public void init(){
display.startScreen();
pauseButtons = new ArrayList<>();
models = new ArrayList<>();
modelsOldRenderMethod = new ArrayList<>();
cam = new CameraLWJGL(this, null, null, null, new Vector(new float[] { 0, 7, 5 }), 90, 0.001f, 100, display.getWidth(), display.getHeight());
renderingEngine.resetBuffers();
initModels();
initPauseScreen();
initInputControls();
renderingEngine.setProjectionMode(ProjectionMode.PERSPECTIVE);
renderingEngine.setRenderPipeline(RenderPipeline.Matrix);
cam.updateValues();
cam.lookAtModel(models.get(lookAtIndex));
} |
|
9,421 | public void setPCAttribute(final NumericPCAttribute attr, final int value){
boolean didChange = false;
switch(attr) {
case WEIGHT:
didChange = weightFacet.setWeight(id, value);
break;
case AGE:
didChange = ageFacet.set(id, value);
break;
default:
break;
}
if (didChange) {
setDirty(true);
if (attr.shouldRecalcActiveBonuses()) {
calcActiveBonuses();
}
}
} | public void setPCAttribute(final NumericPCAttribute attr, final int value){
boolean didChange = false;
switch(attr) {
case WEIGHT:
didChange = weightFacet.set(id, value);
break;
case AGE:
didChange = ageFacet.set(id, value);
break;
}
if (didChange) {
setDirty(true);
calcActiveBonuses();
}
} |
|
9,422 | public void process11Test(){
String folder_ = "messages";
String relative_ = "sample/file";
String html_ = "<html><body><c:try><c:throw value='1/0'/></c:try><c:catch className='java.lang.Object' var='ex'>Exc</c:catch></body></html>";
Configuration conf_ = contextElThird();
conf_.setMessagesFolder(folder_);
conf_.setProperties(new StringMap<String>());
conf_.getProperties().put("msg_example", relative_);
Document doc_ = DocumentBuilder.parseSax(html_);
RendDocumentBlock rendDocumentBlock_ = RendBlock.newRendDocumentBlock(conf_, "c:", doc_, html_);
conf_.getRenders().put("page1.html", rendDocumentBlock_);
conf_.getAnalyzing().setEnabledInternVars(false);
rendDocumentBlock_.buildFctInstructions(conf_);
assertTrue(conf_.isEmptyErrors());
assertEq("<html><body>Exc</body></html>", RendBlock.getRes(rendDocumentBlock_, conf_));
assertNull(getException(conf_));
} | public void process11Test(){
String folder_ = "messages";
String relative_ = "sample/file";
String html_ = "<html><body><c:try><c:throw value='1/0'/></c:try><c:catch className='java.lang.Object' var='ex'>Exc</c:catch></body></html>";
Configuration conf_ = contextElThird();
conf_.setMessagesFolder(folder_);
conf_.setProperties(new StringMap<String>());
conf_.getProperties().put("msg_example", relative_);
RendDocumentBlock rendDocumentBlock_ = buildRendWithoutBean(html_, conf_);
assertTrue(conf_.isEmptyErrors());
assertEq("<html><body>Exc</body></html>", RendBlock.getRes(rendDocumentBlock_, conf_));
assertNull(getException(conf_));
} |
|
9,423 | public Collection<IOffscreenRenderer> getOffscreenRenderersByFormat(final String format){
if (formatOffscreenRendererMapping == null) {
formatOffscreenRendererMapping = ArrayListMultimap.create();
final IConfigurationElement[] extensions = Platform.getExtensionRegistry().getConfigurationElementsFor(EXTP_ID_EXTENSIONS);
for (final IConfigurationElement element : extensions) {
try {
if (ELEMENT_OFFSCREEN_RENDERER.equals(element.getName())) {
final IOffscreenRenderer renderer = (IOffscreenRenderer) element.createExecutableExtension(ATTRIBUTE_CLASS);
if (renderer != null) {
final String id = element.getAttribute(ATTRIBUTE_ID);
if (id == null || id.length() == 0) {
reportError(EXTP_ID_EXTENSIONS, element, ATTRIBUTE_ID, null);
} else {
for (final String f : element.getAttribute(ATTRIBUTE_SUPPORTED_FORMATS).split("[,\\s]")) {
formatOffscreenRendererMapping.put(f, renderer);
}
}
}
}
} catch (final CoreException exception) {
Klighd.handle(exception, Klighd.PLUGIN_ID);
}
}
}
return Collections.unmodifiableCollection(formatOffscreenRendererMapping.get(format));
} | public Collection<OffscreenRendererDescriptor> getOffscreenRenderersByFormat(final String format){
return Collections.unmodifiableCollection(Collections2.filter(idOffscreenRendererMapping.values(), descr -> descr.supportedFormats.contains(format)));
} |
|
9,424 | public static Statement[] generateCallParameters(final Context context, final Object... parameters){
final Statement[] statements = new Statement[parameters.length];
int i = 0;
for (final Object parameter : parameters) {
statements[i++] = generate(context, parameter);
}
return statements;
} | public static Statement[] generateCallParameters(final Context context, final Object... parameters){
return Arrays.stream(parameters).map(p -> generate(context, p)).toArray(s -> new Statement[s]);
} |
|
9,425 | public PetType parse(String text, Locale locale) throws ParseException{
Collection<PetType> findPetTypes = this.pets.findPetTypes();
for (PetType type : findPetTypes) {
if (type.getName().equals(text)) {
return type;
}
}
throw new ParseException("type not found: " + text, 0);
} | public PetType parse(String text, Locale locale) throws ParseException{
return this.pets.findPetTypes().stream().filter(petType -> petType.getName().equals(text)).findAny().orElseThrow(() -> new ParseException("type not found: " + text, 0));
} |
|
9,426 | private void setupView(){
setContentView(R.layout.activity_main);
mainCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
tabLayout = (TabLayout) findViewById(R.id.tabs);
toolbar = (Toolbar) findViewById(R.id.toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
fab = (FloatingActionButton) findViewById(R.id.fab);
circleMenuLayout = (RelativeLayout) findViewById(R.id.circle_menu_layout);
boardItemActionSheetLayout = getLayoutInflater().inflate(R.layout.bottom_sheet_board_items, null);
broadcastLocationSheetLayout = getLayoutInflater().inflate(R.layout.bottom_sheet_broadcast_location, null);
setSupportActionBar(toolbar);
fab.hide();
} | private void setupView(){
setContentView(R.layout.activity_main);
mainCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
tabLayout = (TabLayout) findViewById(R.id.tabs);
toolbar = (Toolbar) findViewById(R.id.toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
fab = (FloatingActionButton) findViewById(R.id.fab);
circleMenuLayout = (RelativeLayout) findViewById(R.id.circle_menu_layout);
setSupportActionBar(toolbar);
fab.hide();
} |
|
9,427 | public void getTables(boolean isOnline){
if (isOnline && mDb.tableDao().getCount() == 0) {
Log.d(TAG, "getTables fetching data from server");
RestaurantService service = HttpServiceFactory.createRetrofitService(RestaurantService.class, RestaurantAPI.API_BASE_URL);
service.getTables().subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<List<Boolean>>() {
@Override
public void onSubscribe(Disposable d) {
Log.d(TAG, "onSubscribe: " + d.toString());
}
@Override
public void onNext(List<Boolean> booleans) {
Log.d(TAG, "onNext: " + booleans.toString());
List<Table> tables = new ArrayList<>();
for (int i = 0; i < booleans.size(); i++) {
tables.add(new Table(i + 1, booleans.get(i)));
}
insertTables(tables);
}
@Override
public void onError(Throwable e) {
Log.d(TAG, "onError: " + e.getMessage());
}
@Override
public void onComplete() {
}
});
} else {
Log.d(TAG, "getTables fetching data from cache");
getAllTables();
}
} | public void getTables(boolean isOnline){
if (isOnline && mDb.tableDao().getCount() == 0) {
RestaurantService service = HttpServiceFactory.createRetrofitService(RestaurantService.class, RestaurantAPI.API_BASE_URL);
service.getTables().subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<List<Boolean>>() {
@Override
public void onSubscribe(Disposable d) {
Log.d(TAG, "onSubscribe: " + d.toString());
}
@Override
public void onNext(List<Boolean> booleans) {
List<Table> tables = new ArrayList<>();
for (int i = 0; i < booleans.size(); i++) {
tables.add(new Table(i + 1, booleans.get(i)));
}
insertTables(tables);
}
@Override
public void onError(Throwable e) {
Log.d(TAG, "onError: " + e.getMessage());
}
@Override
public void onComplete() {
}
});
} else {
getAllTables();
}
} |
|
9,428 | public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
boolean dozeEnabled = Utils.isDozeEnabled(getActivity());
mTextView = (TextView) view.findViewById(R.id.switch_text);
mTextView.setText(getString(dozeEnabled ? R.string.switch_bar_on : R.string.switch_bar_off));
View switchBar = view.findViewById(R.id.switch_bar);
Switch switchWidget = (Switch) switchBar.findViewById(android.R.id.switch_widget);
switchWidget.setChecked(dozeEnabled);
switchWidget.setOnCheckedChangeListener(this);
switchBar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switchWidget.setChecked(!switchWidget.isChecked());
}
});
} | public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
boolean dozeEnabled = Utils.isDozeEnabled(getActivity());
mTextView = view.findViewById(R.id.switch_text);
mTextView.setText(getString(dozeEnabled ? R.string.switch_bar_on : R.string.switch_bar_off));
View switchBar = view.findViewById(R.id.switch_bar);
Switch switchWidget = switchBar.findViewById(android.R.id.switch_widget);
switchWidget.setChecked(dozeEnabled);
switchWidget.setOnCheckedChangeListener(this);
switchBar.setOnClickListener(v -> switchWidget.setChecked(!switchWidget.isChecked()));
} |
|
9,429 | public RegisterResponse handicap_register(@RequestBody HandicapRegisterRequest registerRequest){
logger.info("handicap register API: {}", registerRequest.getHandicap_level());
String user_id = tokenService.getUserId(registerRequest.getToken());
HandicapInfoDto handicapInfo = HandicapInfoDto.builder().handicapped_id(user_id).reliability_th(registerRequest.getReliability_th()).severity(registerRequest.getSeverity()).handicap_type(registerRequest.getHandicap_type()).handicap_level(registerRequest.getHandicap_level()).comment(registerRequest.getComment()).build();
usersService.registerHandicappedInfo(handicapInfo);
return RegisterResponse.builder().result("OK").build();
} | public HandicapRegisterResponse handicap_register(@RequestBody HandicapRegisterRequest registerRequest){
logger.info("handicap register API: {}", registerRequest.getHandicap_level());
String user_id = tokenService.getUserId(registerRequest.getToken());
usersService.registerHandicappedInfo(user_id, registerRequest);
return HandicapRegisterResponse.builder().result("OK").build();
} |
|
9,430 | protected void addVmInterfaceStatisticsToList(List<VmNetworkInterface> list){
if (list.isEmpty()) {
return;
}
vmInterfaceStatisticsToSave.add(list);
} | protected void addVmInterfaceStatisticsToList(List<VmNetworkInterface> nics){
vmInterfaceStatisticsToSave.addAll(nics.stream().map(VmNetworkInterface::getStatistics).collect(Collectors.toList()));
} |
|
9,431 | public static TeamsFragment newInstance(int columnCount){
TeamsFragment fragment = new TeamsFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
} | public static TeamsFragment newInstance(){
return new TeamsFragment();
} |
|
9,432 | public Result<ProcessDefinition> queryProcessDefinitionByName(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @ApiParam(name = "projectName", value = "PROJECT_NAME", required = true) @PathVariable String projectName, @RequestParam("processDefinitionName") String processDefinitionName){
Map<String, Object> result = processDefinitionService.queryProcessDefinitionByName(loginUser, projectName, processDefinitionName);
return returnDataList(result);
} | public Result<ProcessDefinition> queryProcessDefinitionByName(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @ApiParam(name = "projectName", value = "PROJECT_NAME", required = true) @PathVariable String projectName, @RequestParam("processDefinitionName") String processDefinitionName){
return processDefinitionService.queryProcessDefinitionByName(loginUser, projectName, processDefinitionName);
} |
|
9,433 | protected void addFieldView(Field field, int position){
int layoutId;
if (customLayoutIds.containsKey(field.getName())) {
layoutId = getCustomFieldLayoutId(field.getName());
} else {
layoutId = getFieldLayoutId(field.getEditorType());
}
View view = LayoutInflater.from(getContext()).inflate(layoutId, this, false);
DDLFieldViewModel viewModel = (DDLFieldViewModel) view;
viewModel.setField(field);
viewModel.setParentView(this);
viewModel.setPositionInParent(position);
fieldsContainerView.addView(view);
} | protected void addFieldView(Field field, int position){
boolean containsKey = customLayoutIds.containsKey(field.getName());
int layoutId = containsKey ? getCustomFieldLayoutId(field.getName()) : getFieldLayoutId(field.getEditorType());
View view = LayoutInflater.from(getContext()).inflate(layoutId, this, false);
DDLFieldViewModel viewModel = (DDLFieldViewModel) view;
viewModel.setField(field);
viewModel.setParentView(this);
viewModel.setPositionInParent(position);
fieldsContainerView.addView(view);
} |
|
9,434 | private ExponentialRetryAlgorithm createRetryAlgorithm(ApiClock clock){
long timeoutMs = retryOptions.getMaxElapsedBackoffMillis();
Deadline deadline = getOperationCallOptions().getDeadline();
if (deadline != null) {
timeoutMs = deadline.timeRemaining(TimeUnit.MILLISECONDS);
}
RetrySettings retrySettings = RetrySettings.newBuilder().setJittered(true).setInitialRetryDelay(toDuration(retryOptions.getInitialBackoffMillis())).setRetryDelayMultiplier(retryOptions.getBackoffMultiplier()).setMaxRetryDelay(Duration.of(1, ChronoUnit.MINUTES)).setTotalTimeout(toDuration(timeoutMs)).build();
return new ExponentialRetryAlgorithm(retrySettings, clock);
} | private ExponentialRetryAlgorithm createRetryAlgorithm(ApiClock clock){
Optional<Long> operationTimeoutMs = requestCallOptions.getOperationTimeoutMs();
long timeoutMs = operationTimeoutMs.or((long) retryOptions.getMaxElapsedBackoffMillis());
RetrySettings retrySettings = RetrySettings.newBuilder().setJittered(true).setInitialRetryDelay(toDuration(retryOptions.getInitialBackoffMillis())).setRetryDelayMultiplier(retryOptions.getBackoffMultiplier()).setMaxRetryDelay(Duration.of(1, ChronoUnit.MINUTES)).setTotalTimeout(toDuration(timeoutMs)).build();
return new ExponentialRetryAlgorithm(retrySettings, clock);
} |
|
9,435 | public void testQueryTaskListPaging(){
Map<String, Object> result = new HashMap<>();
Integer pageNo = 1;
Integer pageSize = 20;
PageInfo pageInfo = new PageInfo<TaskInstance>(pageNo, pageSize);
result.put(Constants.DATA_LIST, pageInfo);
result.put(Constants.STATUS, Status.SUCCESS);
when(taskInstanceService.queryTaskListPaging(any(), eq(""), eq(1), eq(""), eq(""), eq(""), any(), any(), eq(""), Mockito.any(), eq("192.168.xx.xx"), any(), any())).thenReturn(result);
Result taskResult = taskInstanceController.queryTaskListPaging(null, "", 1, "", "", "", "", ExecutionStatus.SUCCESS, "192.168.xx.xx", "2020-01-01 00:00:00", "2020-01-02 00:00:00", pageNo, pageSize);
Assert.assertEquals(Integer.valueOf(Status.SUCCESS.getCode()), taskResult.getCode());
} | public void testQueryTaskListPaging(){
Integer pageNo = 1;
Integer pageSize = 20;
PageInfo<TaskInstance> pageInfo = new PageInfo<>(pageNo, pageSize);
Result<PageListVO<TaskInstance>> result = Result.success(new PageListVO<>(pageInfo));
when(taskInstanceService.queryTaskListPaging(any(), eq(""), eq(1), eq(""), eq(""), eq(""), any(), any(), eq(""), Mockito.any(), eq("192.168.xx.xx"), any(), any())).thenReturn(result);
result = taskInstanceController.queryTaskListPaging(null, "", 1, "", "", "", "", ExecutionStatus.SUCCESS, "192.168.xx.xx", "2020-01-01 00:00:00", "2020-01-02 00:00:00", pageNo, pageSize);
Assert.assertEquals(Integer.valueOf(Status.SUCCESS.getCode()), result.getCode());
} |
|
9,436 | private void runPreviousStoppedModules(String fileName){
if (fileName.contains("dnscrypt-proxy")) {
boolean dnsCryptRunning = new PrefManager(getApplicationContext()).getBoolPref("DNSCrypt Running");
SharedPreferences shPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean runDNSCryptWithRoot = shPref.getBoolean("swUseModulesRoot", false);
if (dnsCryptRunning) {
makeDelay(3);
runDNSCrypt();
makeDelay(10);
currentModuleStatus.setDnsCryptState(UPDATED);
}
} else if (fileName.contains("tor")) {
SharedPreferences shPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean rnTorWithRoot = shPref.getBoolean("swUseModulesRoot", false);
boolean torRunning = new PrefManager(getApplicationContext()).getBoolPref("Tor Running");
if (torRunning) {
makeDelay(3);
runTor();
makeDelay(10);
currentModuleStatus.setTorState(UPDATED);
}
} else if (fileName.contains("i2pd")) {
SharedPreferences shPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean rnI2PDWithRoot = shPref.getBoolean("swUseModulesRoot", false);
boolean itpdRunning = new PrefManager(getApplicationContext()).getBoolPref("I2PD Running");
if (itpdRunning) {
makeDelay(3);
runITPD();
makeDelay(10);
currentModuleStatus.setItpdState(UPDATED);
}
}
} | private void runPreviousStoppedModules(String fileName){
if (fileName.contains("dnscrypt-proxy")) {
boolean dnsCryptRunning = new PrefManager(getApplicationContext()).getBoolPref("DNSCrypt Running");
if (dnsCryptRunning) {
makeDelay(3);
runDNSCrypt();
makeDelay(10);
currentModuleStatus.setDnsCryptState(RESTARTED);
}
} else if (fileName.contains("tor")) {
boolean torRunning = new PrefManager(getApplicationContext()).getBoolPref("Tor Running");
if (torRunning) {
makeDelay(3);
runTor();
makeDelay(10);
currentModuleStatus.setTorState(RESTARTED);
}
} else if (fileName.contains("i2pd")) {
boolean itpdRunning = new PrefManager(getApplicationContext()).getBoolPref("I2PD Running");
if (itpdRunning) {
makeDelay(3);
runITPD();
makeDelay(10);
currentModuleStatus.setItpdState(RESTARTED);
}
}
} |
|
9,437 | public List<Pair<String, TableType>> getTableNamesAndTypes(boolean bulkLoad, int bulkSize){
final List<Pair<String, TableType>> tableNamesAndTypes = Lists.newArrayList();
if (!tables.isEmpty()) {
for (Map.Entry<TableInstance, DrillTable> tableEntry : tables.entrySet()) {
tableNamesAndTypes.add(Pair.of(tableEntry.getKey().sig.name, tableEntry.getValue().getJdbcTableType()));
}
}
List<DotDrillFile> files = Collections.emptyList();
try {
files = DotDrillUtil.getDotDrills(getFS(), new Path(config.getLocation()), DotDrillType.VIEW);
} catch (AccessControlException e) {
if (!schemaConfig.getIgnoreAuthErrors()) {
logger.debug(e.getMessage());
throw UserException.permissionError(e).message("Not authorized to list or query tables in schema [%s]", getFullSchemaName()).build(logger);
}
} catch (IOException e) {
logger.warn("Failure while trying to list view tables in workspace [{}]", getFullSchemaName(), e);
} catch (UnsupportedOperationException e) {
logger.debug("Failure while trying to list view tables in workspace [{}]", getFullSchemaName(), e);
}
try {
for (DotDrillFile f : files) {
if (f.getType() == DotDrillType.VIEW) {
tableNamesAndTypes.add(Pair.of(f.getBaseName(), TableType.VIEW));
}
}
} catch (UnsupportedOperationException e) {
logger.debug("The filesystem for this workspace does not support this operation.", e);
}
return tableNamesAndTypes;
} | public List<Map.Entry<String, TableType>> getTableNamesAndTypes(){
return Stream.concat(tables.entrySet().stream().map(kv -> Pair.of(kv.getKey().sig.name, kv.getValue().getJdbcTableType())), getViews().stream().map(viewName -> Pair.of(viewName, TableType.VIEW))).collect(Collectors.toList());
} |
|
9,438 | public List<String> searchTableNamesbyLen(String dbname, int len) throws Exception{
connect();
String sql = "select table_name from information_schema.tables where table_schema='" + dbname + "'";
List<String> list = new ArrayList<>();
stmt = conn.prepareStatement(sql);
ResultSet result = stmt.executeQuery(sql);
while (result.next()) {
String tbname = result.getString("TABLE_NAME");
if (tbname.length() == len)
list.add(tbname);
}
stmt.close();
return list;
} | public List<String> searchTableNamesbyLen(String dbname, int len) throws Exception{
connect();
String sql = "select table_name from information_schema.tables where table_schema='" + dbname + "'";
List<String> list = new ArrayList<>();
ResultSet result = selectReturnSet(sql);
while (result.next()) {
String tbname = result.getString("TABLE_NAME");
if (tbname.length() == len)
list.add(tbname);
}
stmt.close();
return list;
} |
|
9,439 | public List<PartitionDto> getPartitions(final String catalogName, final String databaseName, final String tableName, final String filter, final String sortBy, final SortOrder sortOrder, final Integer offset, final Integer limit, final Boolean includeUserMetadata){
final QualifiedName name = RequestWrapper.qualifyName(() -> QualifiedName.ofTable(catalogName, databaseName, tableName));
return RequestWrapper.requestWrapper(name, "getPartitions", () -> {
com.facebook.presto.spi.SortOrder order = null;
if (sortOrder != null) {
order = com.facebook.presto.spi.SortOrder.valueOf(sortOrder.name());
}
return partitionService.list(name, filter, null, new Sort(sortBy, order), new Pageable(limit, offset), includeUserMetadata, includeUserMetadata, false);
});
} | public List<PartitionDto> getPartitions(final String catalogName, final String databaseName, final String tableName, final String filter, final String sortBy, final SortOrder sortOrder, final Integer offset, final Integer limit, final Boolean includeUserMetadata){
final QualifiedName name = RequestWrapper.qualifyName(() -> QualifiedName.ofTable(catalogName, databaseName, tableName));
return RequestWrapper.requestWrapper(name, "getPartitions", () -> partitionService.list(name, filter, null, new Sort(sortBy, sortOrder), new Pageable(limit, offset), includeUserMetadata, includeUserMetadata, false));
} |
|
9,440 | private BaseController loadModule(File moduleFile) throws LoadException{
try {
JarClassLoader loader = new JarClassLoader();
loader.add(new FileInputStream(moduleFile));
InputStream infoStream = loader.getResourceAsStream("module.json");
InputStreamReader isr = new InputStreamReader(infoStream);
JsonObject info = Json.parse(isr).asObject();
JsonObject load = info.get("load").asObject();
String packageName = load.get("package").asString() + ".";
Class mainCls = loader.loadClass(packageName + load.get("main").asString());
Class viewCls = loader.loadClass(packageName + load.get("view").asString());
JsonController module = (JsonController) mainCls.newInstance();
try {
JsonValue res = info.get("res");
if (res != null && res.asObject().size() > 0)
module.loadResources(loadResources(res.asObject(), loader));
} catch (Exception e) {
System.out.println("Error loading resources for " + load.get("main").asString());
e.printStackTrace();
System.out.println();
}
BaseView view = (BaseView) viewCls.getConstructor(mainCls).newInstance(module);
Image banner = new Image(loader.getResourceAsStream(info.get("banner").asString()));
module.init(info, banner, view);
infoStream.close();
isr.close();
return module;
} catch (Exception e) {
throw new LoadException(e);
}
} | private BaseController loadModule(File moduleFile) throws LoadException{
try {
JarClassLoader loader = new JarClassLoader();
loader.add(new FileInputStream(moduleFile));
InputStream infoStream = loader.getResourceAsStream("module.json");
InputStreamReader isr = new InputStreamReader(infoStream);
JsonObject info = Json.parse(isr).asObject();
JsonObject load = info.get("load").asObject();
String packageName = load.get("package").asString() + ".";
Class mainCls = loader.loadClass(packageName + load.get("main").asString());
JsonController module = (JsonController) mainCls.newInstance();
try {
JsonValue res = info.get("res");
if (res != null && res.asObject().size() > 0)
module.loadResources(loadResources(res.asObject(), loader));
} catch (Exception e) {
System.out.println("Error loading resources for " + load.get("main").asString());
e.printStackTrace();
System.out.println();
}
Image banner = new Image(loader.getResourceAsStream(info.get("banner").asString()));
module.init(info, banner);
infoStream.close();
isr.close();
return module;
} catch (Exception e) {
throw new LoadException(e);
}
} |
|
9,441 | public void testInvalidDateInput_String() throws Exception{
DateConverter dc = new DateConverter(DateFormat.getDateInstance(DateFormat.LONG));
dc = new DateConverter(null);
dc.convert(String.class, "123");
} | public void testInvalidDateInput_String() throws Exception{
DateConverter dc = new DateConverter(null);
dc.convert(String.class, "123");
} |
|
9,442 | public double calculate(double firstValue, char operation, double secondValue){
switch(operation) {
case ADDITION_SIGN:
return firstValue + secondValue;
case SUBTRACTION_SIGN:
return firstValue - secondValue;
case MULTIPLICATION_SIGN:
return firstValue * secondValue;
case DIVISION_SIGN:
if (secondValue == 0) {
throw new ArithmeticException("Can't divide by zero");
}
return firstValue / secondValue;
case RAISING_TO_THE_POWER_SIGN:
return Math.pow(firstValue, secondValue);
default:
throw new UnsupportedOperationException("Unsupported operation");
}
} | public double calculate(double firstValue, char operation, double secondValue){
switch(operation) {
case ADDITION_SIGN:
return firstValue + secondValue;
case SUBTRACTION_SIGN:
return firstValue - secondValue;
case MULTIPLICATION_SIGN:
return firstValue * secondValue;
case DIVISION_SIGN:
return firstValue / secondValue;
case RAISING_TO_THE_POWER_SIGN:
return Math.pow(firstValue, secondValue);
default:
throw new UnsupportedOperationException("Unsupported operation");
}
} |
|
9,443 | public void clockForceSync(double clockTime){
logger.info("Forced sync");
for (StreamViewer streamViewer : streamViewers) {
streamViewer.setCurrentTime((long) clockTime);
}
updateCurrentTimeLabelAndNeedle((long) clockTime);
} | public void clockForceSync(double clockTime){
logger.info("Forced sync");
updateCurrentTimeLabelAndNeedle((long) clockTime);
} |
|
9,444 | private JScrollPane getVpListScr(){
if (vpListScr == null) {
vpListScr = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
vpListScr.getVerticalScrollBar().setUnitIncrement(8);
vpListScr.getViewport().addChangeListener(new ChangeListener() {
@Override
public void stateChanged(final ChangeEvent e) {
for (final VisualPropertySheetItem<?> item : getItems()) item.fitToWidth(vpListScr.getViewport().getWidth());
}
});
}
return vpListScr;
} | private JScrollPane getVpListScr(){
if (vpListScr == null) {
vpListScr = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
vpListScr.getVerticalScrollBar().setUnitIncrement(8);
vpListScr.getViewport().addChangeListener(evt -> {
for (final VisualPropertySheetItem<?> item : getItems()) item.fitToWidth(vpListScr.getViewport().getWidth());
});
}
return vpListScr;
} |
|
9,445 | public void errorRaised(final String errorMessage){
ParallelTaskExecutor.executeTask(new Runnable() {
@Override
public void run() {
peerClient.stop();
if (errorHandler != null) {
errorHandler.errorRaised(errorMessage);
} else {
System.err.println(errorMessage);
}
}
});
} | public void errorRaised(final String errorMessage){
new Thread(() -> {
peerClient.stop();
if (errorHandler != null) {
errorHandler.errorRaised(errorMessage);
} else {
System.err.println(errorMessage);
}
}).start();
} |
|
9,446 | public void should_return_empty_onboarding_list_given_a_list_with_one_person() throws Exception{
List<Person> personListWithOnePerson = new ArrayList<>();
Person person = new Woman("Ornela", 123);
personListWithOnePerson.add(person);
List<Person> persons = OnBoardingService.computeEligiblePassengers(personListWithOnePerson);
assertThat(persons).isEmpty();
} | public void should_return_empty_onboarding_list_given_a_list_with_one_person() throws Exception{
List<Person> personListWithOnePerson = new ArrayList<>();
personListWithOnePerson.add(personTestData.get(ORNELA));
List<Person> persons = sut.computeEligiblePassengers(personListWithOnePerson);
assertThat(persons).isEmpty();
} |
|
9,447 | public void onEventMainThread(OnParseDataSucceeded event){
Log.d(TAG, "OnParseDataSucceeded called");
response = event.getResponse();
updateList();
} | public void onEventMainThread(OnParseDataSucceeded event){
response = event.getResponse();
updateList();
} |
|
9,448 | public String getUsersByCredentialGroup(Long userGroupId){
String result = "<group id=\"" + userGroupId + "\"><users>";
final List<CredentialGroupMembers> userGroupList = credentialGroupMembersDao.getByGroup(userGroupId);
final Iterator<CredentialGroupMembers> it = userGroupList.iterator();
while (it.hasNext()) {
result += "<user ";
result += DomUtils.getXmlAttributeOutput("id", "" + it.next().getCredential().getId()) + " ";
result += ">";
result += "</user>";
}
result += "</users></group>";
return result;
} | public String getUsersByCredentialGroup(Long userGroupId){
String result = "<group id=\"" + userGroupId + "\"><users>";
final List<CredentialGroupMembers> userGroupList = credentialGroupMembersRepository.findByGroup(userGroupId);
for (CredentialGroupMembers cgm : userGroupList) {
result += "<user ";
result += DomUtils.getXmlAttributeOutput("id", "" + cgm.getCredential().getId()) + " ";
result += ">";
result += "</user>";
}
result += "</users></group>";
return result;
} |
|
9,449 | public void onBindViewHolder(MessageHolder holder, int position){
MessageModel message = messageList.get(position);
this.position = position;
Bitmap photo = occupantsPhotos.get(message.getSenderId().longValue());
holder.userName.setText(userNames.get(message.getSenderId().longValue()));
holder.messageText.setText(message.getMessage());
holder.time.setText(Converter.longToTime(message.getDateSent() * 1000));
if (message.getSenderId().longValue() == currentUserId) {
holder.userName.setText(context.getString(R.string.me));
switch(message.getRead()) {
case MessageState.DELIVERED:
holder.deliveryStatus.setImageDrawable(context.getResources().getDrawable(R.drawable.single_check_mark));
break;
case MessageState.READ:
holder.deliveryStatus.setImageDrawable(context.getResources().getDrawable(R.drawable.double_check_mark));
break;
case MessageState.DEFAULT:
holder.deliveryStatus.setVisibility(View.INVISIBLE);
break;
}
}
if (photo != null) {
holder.userPhoto.setImageBitmap(occupantsPhotos.get(message.getSenderId().longValue()));
} else {
holder.userPhoto.setImageDrawable(context.getResources().getDrawable(R.drawable.user_icon));
}
if (position > 0) {
setTimeTextVisibility(message.getDateSent(), messageList.get(position - 1).getDateSent(), holder.timeText);
} else {
setTimeTextVisibility(message.getDateSent(), 0, holder.timeText);
}
} | public void onBindViewHolder(MessageHolder holder, int position){
MessageModel message = messageList.get(position);
Bitmap photo = occupantsPhotos.get(message.getSenderId().longValue());
holder.userName.setText(userNames.get(message.getSenderId().longValue()));
holder.messageText.setText(message.getMessage());
holder.time.setText(Converter.longToTime(message.getDateSent() * 1000));
if (message.getSenderId().longValue() == currentUserId) {
holder.userName.setText(context.getString(R.string.me));
switch(message.getRead()) {
case MessageState.DELIVERED:
holder.deliveryStatus.setImageDrawable(context.getResources().getDrawable(R.drawable.single_check_mark));
break;
case MessageState.READ:
holder.deliveryStatus.setImageDrawable(context.getResources().getDrawable(R.drawable.double_check_mark));
break;
case MessageState.DEFAULT:
holder.deliveryStatus.setVisibility(View.INVISIBLE);
break;
}
}
if (photo != null) {
holder.userPhoto.setImageBitmap(occupantsPhotos.get(message.getSenderId().longValue()));
} else {
holder.userPhoto.setImageDrawable(context.getResources().getDrawable(R.drawable.user_icon));
}
if (position > 0) {
setTimeTextVisibility(message.getDateSent(), messageList.get(position - 1).getDateSent(), holder.timeText);
} else {
setTimeTextVisibility(message.getDateSent(), 0, holder.timeText);
}
} |
|
9,450 | public HandlerResult handle(ProcessState state, ProcessInstance process){
Service service = (Service) state.getResource();
if (process.getName().equalsIgnoreCase(ServiceDiscoveryConstants.PROCESS_SERVICE_UPDATE) && service.getState().equalsIgnoreCase(CommonStatesConstants.UPDATING_INACTIVE)) {
return null;
}
int scale = DataAccessor.field(service, ServiceDiscoveryConstants.FIELD_SCALE, jsonMapper, Integer.class);
if (scale == 0) {
return null;
}
List<Integer> consumedServiceIds = new ArrayList<>();
boolean activateConsumedServices = DataAccessor.fromMap(state.getData()).withScope(ServiceUpdateActivate.class).withKey(ServiceDiscoveryConstants.FIELD_ACTIVATE_CONSUMED_SERVICES).withDefault(false).as(Boolean.class);
if (activateConsumedServices) {
List<? extends Integer> services = (List<? extends Integer>) DataUtils.getFields(service).get(ServiceDiscoveryConfigItem.VOLUMESFROMSERVICE.getRancherName());
if (services != null) {
consumedServiceIds.addAll(services);
}
}
progress.init(state, sdServer.getWeights(scale + consumedServiceIds.size(), 100));
if (activateConsumedServices) {
activateConsumedServices(consumedServiceIds, state.getData());
}
if (service.getKind().equalsIgnoreCase(KIND.SERVICE.name())) {
sdServer.activateService(service, scale);
} else if (service.getKind().equalsIgnoreCase(KIND.LOADBALANCERSERVICE.name())) {
sdServer.activateLoadBalancerService(service, scale);
}
return null;
} | public HandlerResult handle(ProcessState state, ProcessInstance process){
Service service = (Service) state.getResource();
if (process.getName().equalsIgnoreCase(ServiceDiscoveryConstants.PROCESS_SERVICE_UPDATE) && service.getState().equalsIgnoreCase(CommonStatesConstants.UPDATING_INACTIVE)) {
return null;
}
deploymentMgr.activate(service, state.getData());
return null;
} |