hexsha
stringlengths 40
40
| size
int64 3
1.05M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 5
1.02k
| max_stars_repo_name
stringlengths 4
126
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
list | max_stars_count
float64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 5
1.02k
| max_issues_repo_name
stringlengths 4
114
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
list | max_issues_count
float64 1
92.2k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 5
1.02k
| max_forks_repo_name
stringlengths 4
136
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
list | max_forks_count
float64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2.55
99.9
| max_line_length
int64 3
1k
| alphanum_fraction
float64 0.25
1
| index
int64 0
1M
| content
stringlengths 3
1.05M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
923ef0454340a140c8f09ab1145876a671d02d57
| 7,823 |
java
|
Java
|
src/main/java/pokefenn/totemic/client/gui/GuiLexicon.java
|
ACGaming/TotemicTFC
|
3f38d489d2cd636224944d33b39578616295c2f3
|
[
"MIT"
] | null | null | null |
src/main/java/pokefenn/totemic/client/gui/GuiLexicon.java
|
ACGaming/TotemicTFC
|
3f38d489d2cd636224944d33b39578616295c2f3
|
[
"MIT"
] | null | null | null |
src/main/java/pokefenn/totemic/client/gui/GuiLexicon.java
|
ACGaming/TotemicTFC
|
3f38d489d2cd636224944d33b39578616295c2f3
|
[
"MIT"
] | null | null | null | 30.799213 | 163 | 0.584686 | 1,000,972 |
/**
* This class was created by <Vazkii>. It's distributed as
* part of the Totemic Mod. Get the Source Code in github:
* https://github.com/Vazkii/Botania
*
* Botania is Open Source and distributed under a
* Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License
* (http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_GB)
*/
package pokefenn.totemic.client.gui;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.I18n;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import pokefenn.totemic.api.TotemicAPI;
import pokefenn.totemic.api.lexicon.LexiconCategory;
import pokefenn.totemic.client.gui.button.GuiButtonBookmark;
import pokefenn.totemic.client.gui.button.GuiButtonInvisible;
public class GuiLexicon extends GuiScreen
{
public static final int BOOKMARK_START = 1337;
public static final ResourceLocation texture = new ResourceLocation("totemic:textures/gui/totempedia.png");
public static GuiLexicon currentOpenLexicon = new GuiLexicon();
public static ItemStack stackUsed = ItemStack.EMPTY;
public static List<GuiLexicon> bookmarks = new ArrayList<>();
boolean bookmarksNeedPopulation = false;
String title;
int guiWidth = 146;
int guiHeight = 180;
int left, top;
@Override
public void drawScreen(int par1, int par2, float par3)
{
GlStateManager.color(1F, 1F, 1F, 1F);
mc.renderEngine.bindTexture(texture);
drawTexturedModalRect(left, top, 0, 0, guiWidth, guiHeight);
drawBookmark(left + guiWidth / 2, top - getTitleHeight(), getTitle(), true);
String subtitle = getSubtitle();
if (subtitle != null)
{
GlStateManager.pushMatrix();
GlStateManager.scale(0.5F, 0.5F, 1F);
drawCenteredString(fontRenderer, subtitle, left * 2 + guiWidth, (top - getTitleHeight() + 11) * 2, 0x00FF00);
GlStateManager.popMatrix();
}
drawHeader();
if (bookmarksNeedPopulation)
{
populateBookmarks();
bookmarksNeedPopulation = false;
}
super.drawScreen(par1, par2, par3);
}
@Override
protected void actionPerformed(GuiButton par1GuiButton)
{
if (par1GuiButton.id >= BOOKMARK_START)
handleBookmark(par1GuiButton);
else
{
int i = par1GuiButton.id - 3;
if (i < 0)
return;
List<LexiconCategory> categoryList = TotemicAPI.get().lexicon().getCategories();
LexiconCategory category = i >= categoryList.size() ? null : categoryList.get(i);
if (category != null)
{
mc.displayGuiScreen(new GuiLexiconIndex(category));
}
}
}
@Override
public void initGui()
{
super.initGui();
title = stackUsed.getDisplayName();
currentOpenLexicon = this;
left = width / 2 - guiWidth / 2;
top = height / 2 - guiHeight / 2;
buttonList.clear();
if (isIndex())
{
int x = 18;
for (int i = 0; i < 12; i++)
{
int y = 16 + i * 12;
buttonList.add(new GuiButtonInvisible(i, left + x, top + y, 110, 10, ""));
}
populateIndex();
}
populateBookmarks();
}
@Override
public boolean doesGuiPauseGame()
{
return false;
}
public void drawBookmark(int x, int y, String s, boolean drawLeft)
{
// This function is called from the buttons so I can't use fontRenderer
FontRenderer font = Minecraft.getMinecraft().fontRenderer;
boolean unicode = font.getUnicodeFlag();
font.setUnicodeFlag(true);
int l = font.getStringWidth(s.trim());
int fontOff = 0;
if (!drawLeft)
{
x += l / 2;
fontOff = 2;
}
Minecraft.getMinecraft().renderEngine.bindTexture(texture);
GlStateManager.color(1F, 1F, 1F, 1F);
drawTexturedModalRect(x + l / 2 + 3, y - 1, 54, 180, 6, 11);
if (drawLeft)
drawTexturedModalRect(x - l / 2 - 9, y - 1, 61, 180, 6, 11);
for (int i = 0; i < l + 6; i++)
drawTexturedModalRect(x - l / 2 - 3 + i, y - 1, 60, 180, 1, 11);
font.drawString(s, x - l / 2 + fontOff, y, 0x111111, false);
font.setUnicodeFlag(unicode);
}
public void handleBookmark(GuiButton par1GuiButton)
{
int i = par1GuiButton.id - BOOKMARK_START;
if (i == bookmarks.size())
{
if (!bookmarks.contains(this))
bookmarks.add(this);
}
else
{
if (isShiftKeyDown())
bookmarks.remove(i);
else
{
GuiLexicon bookmark = bookmarks.get(i);
Minecraft.getMinecraft().displayGuiScreen(bookmark);
if (!bookmark.getTitle().equals(getTitle()))
{
if (bookmark instanceof IParented)
((IParented) bookmark).setParent(this);
}
}
}
bookmarksNeedPopulation = true;
}
public int bookmarkWidth(String b)
{
boolean unicode = fontRenderer.getUnicodeFlag();
fontRenderer.setUnicodeFlag(true);
int width = fontRenderer.getStringWidth(b) + 15;
fontRenderer.setUnicodeFlag(unicode);
return width;
}
void drawHeader()
{
boolean unicode = fontRenderer.getUnicodeFlag();
fontRenderer.setUnicodeFlag(true);
fontRenderer.drawSplitString(I18n.format("totemic.gui.lexicon.header"), left + 18, top + 14, 110, 0);
fontRenderer.setUnicodeFlag(unicode);
}
String getTitle()
{
return title;
}
String getSubtitle()
{
return null;
}
int getTitleHeight()
{
return getSubtitle() == null ? 12 : 16;
}
boolean isIndex()
{
return true;
}
void populateIndex()
{
List<LexiconCategory> categoryList = TotemicAPI.get().lexicon().getCategories();
for (int i = 3; i < 12; i++)
{
int i_ = i - 3;
GuiButtonInvisible button = (GuiButtonInvisible) buttonList.get(i);
LexiconCategory category = i_ >= categoryList.size() ? null : categoryList.get(i_);
if (category != null)
button.displayString = I18n.format(category.getUnlocalizedName());
else
button.displayString = "";
}
}
void populateBookmarks()
{
List<GuiButton> remove = new ArrayList<>();
List<GuiButton> buttons = buttonList;
for (GuiButton button : buttons)
if (button.id >= BOOKMARK_START)
remove.add(button);
buttonList.removeAll(remove);
int len = bookmarks.size();
boolean thisExists = false;
for (GuiLexicon lex : bookmarks)
if (lex.getTitle().equals(getTitle()))
thisExists = true;
boolean addEnabled = len < 10 && this instanceof IParented && !thisExists;
for (int i = 0; i < len + (addEnabled ? 1 : 0); i++)
{
boolean isAdd = i == bookmarks.size();
GuiLexicon gui = isAdd ? null : bookmarks.get(i);
buttonList.add(new GuiButtonBookmark(BOOKMARK_START + i, left + 138, top + 18 + 14 * i, gui == null ? this : gui, gui == null ? "+" : gui.getTitle()));
}
}
}
|
923ef0ac0132a1885a4cf7cf3bc9caee0f14f086
| 1,312 |
java
|
Java
|
src/com/eova/common/utils/io/NetUtil.java
|
littleMarkZ/oss-nt
|
f38046bc3cf3986e3d56c61e4eddaf51e26049e5
|
[
"MIT"
] | null | null | null |
src/com/eova/common/utils/io/NetUtil.java
|
littleMarkZ/oss-nt
|
f38046bc3cf3986e3d56c61e4eddaf51e26049e5
|
[
"MIT"
] | null | null | null |
src/com/eova/common/utils/io/NetUtil.java
|
littleMarkZ/oss-nt
|
f38046bc3cf3986e3d56c61e4eddaf51e26049e5
|
[
"MIT"
] | null | null | null | 20.5 | 77 | 0.660061 | 1,000,973 |
package com.eova.common.utils.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
/**
* 网络文件操作工具类
*
* @author Jieven
*
*/
public class NetUtil {
/**
* 异步从URL下载文件
*
* @param url 目标URL
* @param file 输出文件
* @throws IOException
*/
public static void downloadAsync(String url, File file) throws IOException {
InputStream inputStream = new URL(url).openStream();
ReadableByteChannel rbc = Channels.newChannel(inputStream);
FileOutputStream fos = new FileOutputStream(file);
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
}
/**
* 从URL下载文件
*
* @param url 目标URL
* @param file 输出文件
* @throws IOException
*/
public static void download(String url, String path) {
InputStream is = null;
OutputStream os = null;
try {
is = new URL(url).openStream();
byte[] bs = new byte[1024];
int len;
os = new FileOutputStream(path);
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
os.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
|
923ef23574a51d231bbf9bc512e1b37515cabf67
| 3,835 |
java
|
Java
|
src/main/java/eu/uqasar/web/pages/qmtree/qmodels/panels/QModelViewPanel.java
|
U-QASAR/u-qasar.platform
|
2f186ea71538dea0b97192fb0c955c2f2520c485
|
[
"Apache-2.0"
] | 5 |
2015-10-09T10:14:30.000Z
|
2015-12-17T23:24:46.000Z
|
src/main/java/eu/uqasar/web/pages/qmtree/qmodels/panels/QModelViewPanel.java
|
U-QASAR/u-qasar.platform
|
2f186ea71538dea0b97192fb0c955c2f2520c485
|
[
"Apache-2.0"
] | 3 |
2015-11-26T11:52:08.000Z
|
2016-02-04T16:43:32.000Z
|
src/main/java/eu/uqasar/web/pages/qmtree/qmodels/panels/QModelViewPanel.java
|
U-QASAR/u-qasar.platform
|
2f186ea71538dea0b97192fb0c955c2f2520c485
|
[
"Apache-2.0"
] | 9 |
2015-10-09T09:56:20.000Z
|
2018-03-26T08:29:36.000Z
| 33.938053 | 87 | 0.700652 | 1,000,974 |
package eu.uqasar.web.pages.qmtree.qmodels.panels;
/*
* #%L
* U-QASAR
* %%
* Copyright (C) 2012 - 2015 U-QASAR Consortium
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.wicket.Session;
import org.apache.wicket.datetime.PatternDateConverter;
import org.apache.wicket.datetime.markup.html.basic.DateLabel;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.jboss.solder.logging.Logger;
import de.agilecoders.wicket.core.markup.html.bootstrap.behavior.CssClassNameAppender;
import eu.uqasar.model.qmtree.QModel;
import eu.uqasar.model.qmtree.QModelStatus;
import eu.uqasar.web.pages.qmtree.QMBaseTreePage;
import eu.uqasar.web.pages.qmtree.panels.QMBaseTreePanel;
import eu.uqasar.web.pages.qmtree.qmodels.QModelEditPage;
public class QModelViewPanel extends QMBaseTreePanel<QModel> {
/**
*
*/
private static final long serialVersionUID = 1088435851924101698L;
private static final Logger logger = Logger.getLogger(QModelViewPanel.class);
public QModelViewPanel(String id, IModel<QModel> model) {
super(id, model);
final QModel qmodel = model.getObject();
logger.info("QModelViewPanel::QModelViewPanel" + qmodel.getName());
add(new Label("name", new PropertyModel<>(qmodel, "name")));
add(new Label("icon").add(new CssClassNameAppender(qmodel
.getIconType().cssClassName())));
// TODO only show if authorized to edit
BookmarkablePageLink<QModelEditPage> editLink = new BookmarkablePageLink<>(
"link.edit", QModelEditPage.class,
QMBaseTreePage.forQModel(qmodel));
add(editLink);
add(new Label("nodeKey", new PropertyModel<>(model, "nodeKey")));
add(new Label("edition", new PropertyModel<>(qmodel, "edition")));
add(new Label("company", new PropertyModel<>(qmodel, "company")));
SimpleDateFormat df = (SimpleDateFormat) DateFormat.getDateInstance(
DateFormat.MEDIUM, Session.get().getLocale());
PatternDateConverter pdc = new PatternDateConverter(df.toPattern(),
true);
add(new DateLabel("updateDate", new PropertyModel<Date>(model,
"updateDate"), pdc));
add(new Label("description", new PropertyModel<String>(model,
"description")).setEscapeModelStrings(false));
//isActive
Image img = new Image("isActive") {
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
if (qmodel.getIsActive().equals(QModelStatus.Active)){
tag.getAttributes().put("src", "/uqasar/assets/img/imgv.gif");
tag.getAttributes().put("alt", "active");
} else {
tag.getAttributes().put("src", "/uqasar/assets/img/imgx.gif");
tag.getAttributes().put("alt", "inactive");
}
tag.getAttributes().put("style", "max-width:10%");
}
};
add(img);
}
@Override
protected void onConfigure() {
super.onConfigure();
}
}
|
923ef2c96c3c42521fbb2b5dc8eefdffdf480983
| 1,940 |
java
|
Java
|
clbs/src/main/java/com/zw/platform/domain/statistic/TravelBaseInfoOriginator.java
|
youyouqiu/hybrid-development
|
784c5227a73d1e6609b701a42ef4cdfd6400d2b7
|
[
"MIT"
] | 1 |
2021-09-29T02:13:49.000Z
|
2021-09-29T02:13:49.000Z
|
clbs/src/main/java/com/zw/platform/domain/statistic/TravelBaseInfoOriginator.java
|
youyouqiu/hybrid-development
|
784c5227a73d1e6609b701a42ef4cdfd6400d2b7
|
[
"MIT"
] | null | null | null |
clbs/src/main/java/com/zw/platform/domain/statistic/TravelBaseInfoOriginator.java
|
youyouqiu/hybrid-development
|
784c5227a73d1e6609b701a42ef4cdfd6400d2b7
|
[
"MIT"
] | null | null | null | 37.307692 | 92 | 0.739691 | 1,000,975 |
package com.zw.platform.domain.statistic;
/**
* 备忘录: 状态存储
*
* @author zhouzongbo on 2019/1/4 9:55
*/
public class TravelBaseInfoOriginator {
private TravelBaseInfo travelBaseInfo;
/**
* 创建备忘录对象
* 由于计算上一个状态的时间和里程 = 这个状态的第一条位置数据 - 上一个状态的第一条位置数据
* (所以travelBaseInfo中的countPosition - 1 等于某个状态实际连续行驶or停止次数)
* @return TravelBaseInfoCaretaker
*/
public TravelBaseInfo createTravelBaseInfo() {
TravelBaseInfo travelBaseInfo = new TravelBaseInfo();
travelBaseInfo.setCountPosition(this.travelBaseInfo.getCountPosition() - 1);
travelBaseInfo.setFirstVTime(this.travelBaseInfo.getFirstVTime());
travelBaseInfo.setLastVTime(this.travelBaseInfo.getLastVTime());
travelBaseInfo.setLastGpsMile(this.travelBaseInfo.getLastGpsMile());
travelBaseInfo.setPreTravelMile(this.travelBaseInfo.getPreTravelMile());
travelBaseInfo.setMinTotalOilWearOne(this.travelBaseInfo.getMinTotalOilWearOne());
travelBaseInfo.setMaxTotalOilWearOne(this.travelBaseInfo.getMaxTotalOilWearOne());
travelBaseInfo.setTravelCountTimes(this.travelBaseInfo.getTravelCountTimes());
travelBaseInfo.setStopCountTimes(this.travelBaseInfo.getStopCountTimes());
travelBaseInfo.setStatus(this.travelBaseInfo.getStatus());
travelBaseInfo.setSpeed(this.travelBaseInfo.getSpeed());
travelBaseInfo.setFirstPositionStatus(this.travelBaseInfo.getFirstPositionStatus());
travelBaseInfo.setEndLocation(this.travelBaseInfo.getEndLocation());
return travelBaseInfo;
}
/**
* 恢复之前存储的对象
*/
public void restoreTravelBaseInfo(TravelBaseInfo travelBaseInfo) {
this.travelBaseInfo = travelBaseInfo;
}
public void setTravelBaseInfo(TravelBaseInfo travelBaseInfo) {
this.travelBaseInfo = travelBaseInfo;
}
public TravelBaseInfo getTravelBaseInfo() {
return travelBaseInfo;
}
}
|
923ef30c1e19234a99a25cf4ddc0e6ecab19e15b
| 806 |
java
|
Java
|
tethys-backend/src/main/java/ninja/harmless/tethys/configuration/MongoDBNotPresentCondition.java
|
fridayy/tethys
|
c2da5073f60f8b6e368644a77d69f959287dc680
|
[
"Apache-2.0"
] | null | null | null |
tethys-backend/src/main/java/ninja/harmless/tethys/configuration/MongoDBNotPresentCondition.java
|
fridayy/tethys
|
c2da5073f60f8b6e368644a77d69f959287dc680
|
[
"Apache-2.0"
] | null | null | null |
tethys-backend/src/main/java/ninja/harmless/tethys/configuration/MongoDBNotPresentCondition.java
|
fridayy/tethys
|
c2da5073f60f8b6e368644a77d69f959287dc680
|
[
"Apache-2.0"
] | null | null | null | 36.727273 | 92 | 0.788366 | 1,000,976 |
package ninja.harmless.tethys.configuration;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
/**
* Checks if the spring data mongo property is set in order to
* determine if fongo should be used or not.
*
* @author [email protected] - 12/9/16.
*/
public class MongoDBNotPresentCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
return !StringUtils.isNotEmpty(environment.getProperty("spring.data.mongodb.host"));
}
}
|
923ef45431d78c36d14618a73cf268ea9a0742fe
| 5,757 |
java
|
Java
|
src/hospelhornbg_genomeBuild/Contig.java
|
bhospelhorn/SeeSNP
|
a049382ca7efa1e7115ea8e2921ba14e8f74bee9
|
[
"MIT"
] | null | null | null |
src/hospelhornbg_genomeBuild/Contig.java
|
bhospelhorn/SeeSNP
|
a049382ca7efa1e7115ea8e2921ba14e8f74bee9
|
[
"MIT"
] | null | null | null |
src/hospelhornbg_genomeBuild/Contig.java
|
bhospelhorn/SeeSNP
|
a049382ca7efa1e7115ea8e2921ba14e8f74bee9
|
[
"MIT"
] | null | null | null | 22.227799 | 86 | 0.644085 | 1,000,977 |
package hospelhornbg_genomeBuild;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import waffleoRai_Utils.FileBuffer;
public class Contig implements Comparable<Contig>{
public static final int SORTCLASS_AUTOSOME = 0;
public static final int SORTCLASS_SEXCHROM = 1;
public static final int SORTCLASS_MITO = 2;
public static final int SORTCLASS_CONTIG = 3;
public static final int SORTCLASS_COMPOUND = 4;
public static final int SORTCLASS_UNKNOWN = 5;
private Set<String> names;
private String UCSC_name;
private String UDP_name;
private int sortClass;
private long length;
public Contig()
{
names = new HashSet<String>();
length = -1;
UCSC_name = null;
UDP_name = null;
sortClass = SORTCLASS_UNKNOWN;
}
public Collection<String> getAllNames()
{
Collection<String> copy = new HashSet<String>();
copy.addAll(names);
copy.add(UCSC_name);
copy.add(UDP_name);
return copy;
}
public String getUDPName()
{
return UDP_name;
}
public String getUCSCName()
{
return UCSC_name;
}
public long getLength()
{
return length;
}
public int getType()
{
return sortClass;
}
public void addName(String name)
{
if (name == null) return;
names.add(name);
}
public void removeName(String name)
{
names.remove(name);
}
public void setUDPName(String name)
{
UDP_name = name;
}
public void setUCSCName(String name)
{
UCSC_name = name;
}
public void setLength(long len)
{
length = len;
}
public void setType(int type)
{
if (type > 3) return;
sortClass = type;
}
public FileBuffer serialize()
{
FileBuffer altNames = new FileBuffer(names.size() * 32, true);
for (String n : names)
{
short len = (short)n.length();
altNames.addToFile(len);
altNames.printASCIIToFile(n);
if (len % 2 != 0) altNames.addToFile((byte)0x00);
}
int namesSize = (int)altNames.getFileSize();
FileBuffer myContig = new FileBuffer(100 + namesSize, true);
myContig.addToFile(96 + namesSize); //Contig block size excluding actual size record
myContig.addToFile(length); //Contig length
myContig.addToFile(sortClass); //Type
String name = UCSC_name;
if (name != null)
{
if (name.length() > 64) name = name.substring(0, 63);
myContig.printASCIIToFile(name);
if (name.length() < 64)
{
for (int i = name.length(); i < 64; i++) myContig.addToFile((byte)0x00);
}
}
else
{
for (int i = 0; i < 64; i++) myContig.addToFile((byte)0x00);
}
name = UDP_name;
if (name != null)
{
if (name.length() > 16) name = name.substring(0, 15);
myContig.printASCIIToFile(name);
if (name.length() < 16)
{
for (int i = name.length(); i < 16; i++) myContig.addToFile((byte)0x00);
}
}
else
{
for (int i = 0; i < 16; i++) myContig.addToFile((byte)0x00);
}
myContig.addToFile(names.size());
for (int i = 0; i < namesSize; i++){
myContig.addToFile(altNames.getByte(i));
}
return myContig;
}
public boolean equals(Object o)
{
if (o == null) return false;
if (this == o) return true;
if (!(o instanceof Contig)) return false;
Contig c = (Contig)o;
if (this.length != c.length) return false;
if (this.sortClass != c.sortClass) return false;
if (this.UCSC_name == null)
{
System.err.println("Contig.equals || UCSC name field is null!!");
System.err.println("Contig.equals || Contig info:");
printInfo();
throw new NullPointerException();
}
if (!(this.UCSC_name.equals(c.UCSC_name))) return false;
if (!(this.UDP_name.equals(c.UDP_name))) return false;
if (this.names.size() != c.names.size()) return false;
if (!this.names.containsAll(c.names)) return false;
if (!c.names.containsAll(this.names)) return false;
return true;
}
public int hashCode()
{
return UCSC_name.hashCode();
}
public int compareTo(Contig o)
{
if (o == null) return 1;
//First, compare sort type
if (this.sortClass != o.sortClass) return this.sortClass - o.sortClass;
if (this.sortClass == SORTCLASS_AUTOSOME)
{
//Try to parse it as a number first
int num1 = -1;
try {num1 = Integer.parseInt(this.UDP_name);}
catch (NumberFormatException e){num1 = -1;}
int num2 = -1;
try {num2 = Integer.parseInt(o.UDP_name);}
catch (NumberFormatException e){num2 = -1;}
if (num1 >= 0 && num2 >= 0) return num1 - num2;
if (num1 < 0 && num2 >= 0) return 1;
if (num1 >= 0 && num2 < 0) return -1;
return this.UDP_name.compareTo(o.UDP_name);
}
if (this.UDP_name == null)
{
System.err.println("Contig.compareTo || [this] UDP name field is null!!");
System.err.println("Contig.compareTo || Contig info:");
printInfo();
throw new NullPointerException();
}
if (o.UDP_name == null)
{
System.err.println("Contig.compareTo || [o] UDP name field is null!!");
System.err.println("Contig.compareTo || Contig info:");
o.printInfo();
throw new NullPointerException();
}
return this.UDP_name.compareTo(o.UDP_name); //Just keep it alphabetical
}
public String toString()
{
return this.UDP_name;
}
public String printInfo()
{
String s = "";
s += this.getUDPName() + "\t";
s += this.getUCSCName() + "\t";
switch (this.sortClass)
{
case SORTCLASS_AUTOSOME: s += "AUTOSOME\t"; break;
case SORTCLASS_SEXCHROM: s += "SEXCHROM\t"; break;
case SORTCLASS_MITO: s += "MITO\t"; break;
case SORTCLASS_CONTIG: s += "CONTIG\t"; break;
case SORTCLASS_COMPOUND: s += "COMPOUND\t"; break;
case SORTCLASS_UNKNOWN: s += "UNK\t"; break;
}
s += this.getLength() + "\t";
s += "[";
int nNames = names.size();
int i = 0;
for (String n : names)
{
s += n;
if (i < nNames-1) s += ",";
i++;
}
s += "]";
return s;
}
}
|
923ef521f7d9ba3a6081ffdf0d61e339e851acee
| 613 |
java
|
Java
|
src/pojo/Ftp.java
|
JuncalHong/HomeworkUpload
|
da9e7127b2ced7caec86b5d20ad0efc66484863e
|
[
"MIT"
] | 2 |
2018-03-17T12:03:38.000Z
|
2019-11-12T14:13:51.000Z
|
src/pojo/Ftp.java
|
JuncalHong/HomeworkUpload
|
da9e7127b2ced7caec86b5d20ad0efc66484863e
|
[
"MIT"
] | null | null | null |
src/pojo/Ftp.java
|
JuncalHong/HomeworkUpload
|
da9e7127b2ced7caec86b5d20ad0efc66484863e
|
[
"MIT"
] | null | null | null | 18.575758 | 43 | 0.694943 | 1,000,978 |
package pojo;
public class Ftp {
private String server;
private int port;
private String username;
private String password;
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
923ef63d208424350da1439f1de273a96d180382
| 2,952 |
java
|
Java
|
pow/src/main/java/tech/pegasys/artemis/pow/Web3jEth1Provider.java
|
saltiniroberto/teku
|
6fc48e3bd7e27199468e3320baa17afd0aa1374f
|
[
"Apache-2.0"
] | null | null | null |
pow/src/main/java/tech/pegasys/artemis/pow/Web3jEth1Provider.java
|
saltiniroberto/teku
|
6fc48e3bd7e27199468e3320baa17afd0aa1374f
|
[
"Apache-2.0"
] | null | null | null |
pow/src/main/java/tech/pegasys/artemis/pow/Web3jEth1Provider.java
|
saltiniroberto/teku
|
6fc48e3bd7e27199468e3320baa17afd0aa1374f
|
[
"Apache-2.0"
] | null | null | null | 36.9 | 118 | 0.75813 | 1,000,979 |
/*
* Copyright 2020 ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package tech.pegasys.artemis.pow;
import com.google.common.primitives.UnsignedLong;
import io.reactivex.Flowable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameter;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.request.Transaction;
import org.web3j.protocol.core.methods.response.EthBlock;
import org.web3j.protocol.core.methods.response.EthCall;
import tech.pegasys.artemis.util.async.SafeFuture;
public class Web3jEth1Provider implements Eth1Provider {
private static final Logger LOG = LogManager.getLogger();
private final Web3j web3j;
public Web3jEth1Provider(Web3j web3j) {
this.web3j = web3j;
}
@Override
public Flowable<EthBlock.Block> getLatestBlockFlowable() {
LOG.trace("Subscribing to new block events");
return web3j.blockFlowable(false).map(EthBlock::getBlock);
}
@Override
public SafeFuture<EthBlock.Block> getEth1BlockFuture(UnsignedLong blockNumber) {
LOG.trace("Getting eth1 block {}", blockNumber);
DefaultBlockParameter blockParameter =
DefaultBlockParameter.valueOf(blockNumber.bigIntegerValue());
return getEth1BlockFuture(blockParameter);
}
@Override
public SafeFuture<EthBlock.Block> getEth1BlockFuture(String blockHash) {
LOG.trace("Getting eth1 block {}", blockHash);
return SafeFuture.of(web3j.ethGetBlockByHash(blockHash, false).sendAsync())
.thenApply(EthBlock::getBlock);
}
private SafeFuture<EthBlock.Block> getEth1BlockFuture(DefaultBlockParameter blockParameter) {
return SafeFuture.of(web3j.ethGetBlockByNumber(blockParameter, false).sendAsync())
.thenApply(EthBlock::getBlock);
}
@Override
public SafeFuture<EthBlock.Block> getLatestEth1BlockFuture() {
DefaultBlockParameter blockParameter = DefaultBlockParameterName.LATEST;
return getEth1BlockFuture(blockParameter);
}
@Override
public SafeFuture<EthCall> ethCall(
final String from, String to, String data, final UnsignedLong blockNumber) {
return SafeFuture.of(
web3j
.ethCall(
Transaction.createEthCallTransaction(from, to, data),
DefaultBlockParameter.valueOf(blockNumber.bigIntegerValue()))
.sendAsync());
}
}
|
923ef6998f9210ca6c3ce163b6c3631cd4be5e13
| 287 |
java
|
Java
|
src/main/java/org/brapi/test/BrAPITestServer/repository/germ/SeedLotRepository.java
|
agus-setiawan-desu/brapi-Java-TestServer
|
1b509a9cea74ef40f94a1eb8bebca69e9f767ac4
|
[
"MIT"
] | 4 |
2020-06-30T16:21:23.000Z
|
2021-11-18T18:37:05.000Z
|
src/main/java/org/brapi/test/BrAPITestServer/repository/germ/SeedLotRepository.java
|
agus-setiawan-desu/brapi-Java-TestServer
|
1b509a9cea74ef40f94a1eb8bebca69e9f767ac4
|
[
"MIT"
] | 52 |
2018-03-27T16:37:22.000Z
|
2022-02-16T07:18:46.000Z
|
src/main/java/org/brapi/test/BrAPITestServer/repository/germ/SeedLotRepository.java
|
agus-setiawan-desu/brapi-Java-TestServer
|
1b509a9cea74ef40f94a1eb8bebca69e9f767ac4
|
[
"MIT"
] | 7 |
2019-03-07T08:47:05.000Z
|
2020-12-09T13:01:57.000Z
| 31.888889 | 83 | 0.850174 | 1,000,980 |
package org.brapi.test.BrAPITestServer.repository.germ;
import org.brapi.test.BrAPITestServer.model.entity.germ.SeedLotEntity;
import org.brapi.test.BrAPITestServer.repository.core.BrAPIRepository;
public interface SeedLotRepository extends BrAPIRepository<SeedLotEntity, String> {
}
|
923ef73a6dc3ee944618d9b5a9500a70bce82d05
| 38,087 |
java
|
Java
|
core/core-test/src/test/java/org/visallo/core/EntityHighlighterTest.java
|
pborawski/visallo
|
6b01150e46f31baf03c33b9e1bd499b4f9c75d73
|
[
"Apache-2.0"
] | 6 |
2018-02-22T01:48:02.000Z
|
2019-01-09T22:33:25.000Z
|
core/core-test/src/test/java/org/visallo/core/EntityHighlighterTest.java
|
pborawski/visallo
|
6b01150e46f31baf03c33b9e1bd499b4f9c75d73
|
[
"Apache-2.0"
] | null | null | null |
core/core-test/src/test/java/org/visallo/core/EntityHighlighterTest.java
|
pborawski/visallo
|
6b01150e46f31baf03c33b9e1bd499b4f9c75d73
|
[
"Apache-2.0"
] | 7 |
2018-03-05T16:19:13.000Z
|
2020-04-21T18:40:48.000Z
| 68.0125 | 678 | 0.631764 | 1,000,981 |
package org.visallo.core;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.vertexium.*;
import org.vertexium.inmemory.InMemoryAuthorizations;
import org.vertexium.inmemory.InMemoryGraph;
import org.visallo.core.model.properties.VisalloProperties;
import org.visallo.core.model.termMention.TermMentionBuilder;
import org.visallo.core.model.termMention.TermMentionRepository;
import org.visallo.core.model.textHighlighting.OffsetItem;
import org.visallo.core.model.textHighlighting.VertexOffsetItem;
import org.visallo.core.security.DirectVisibilityTranslator;
import org.visallo.core.security.VisibilityTranslator;
import org.visallo.core.user.User;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class EntityHighlighterTest {
private static final String PROPERTY_KEY = "";
private static final String PERSON_IRI = "http://visallo.org/test/person";
private static final String LOCATION_IRI = "http://visallo.org/test/location";
InMemoryGraph graph;
@Mock
private User user;
private Authorizations authorizations;
private Visibility visibility;
private VisibilityTranslator visibilityTranslator = new DirectVisibilityTranslator();
@Before
public void setUp() {
visibility = new Visibility("");
graph = InMemoryGraph.create();
authorizations = new InMemoryAuthorizations(TermMentionRepository.VISIBILITY_STRING);
when(user.getUserId()).thenReturn("USER123");
}
@Test
public void testReplaceNonBreakingSpaces() throws Exception {
EnumSet<EntityHighlighter.Options> none = EnumSet.noneOf(EntityHighlighter.Options.class);
assertEquals(" ", EntityHighlighter.getHighlightedText(" ", Arrays.asList(), none));
assertEquals(" ", EntityHighlighter.getHighlightedText(" ", Arrays.asList(), none));
assertEquals(" ", EntityHighlighter.getHighlightedText(" ", Arrays.asList(), none));
}
@Test
public void testWithUTF8() throws Exception {
String actual = EntityHighlighter.getHighlightedText(" 😎💃🏿", Arrays.asList(), EnumSet.noneOf(EntityHighlighter.Options.class));
assertEquals(" 😎💃🏿", actual);
}
@Test
public void testReplaceNonBreakingSpacesAcrossBuffer() throws Exception {
String space = " ";
int spaceStart = Math.max(0, EntityHighlighter.BUFFER_SIZE - 2);
int spaceEnd = spaceStart + space.length();
StringBuilder longText = new StringBuilder();
StringBuilder expected = new StringBuilder();
for (int i = 0; i < spaceEnd; i++) {
if (i < spaceStart) {
longText.append("_");
expected.append("_");
} else {
longText.append(space);
expected.append(" ");
break;
}
}
assertEquals(expected.toString(), EntityHighlighter.getHighlightedText(longText.toString(), Arrays.asList(), EnumSet.noneOf(EntityHighlighter.Options.class)));
}
@Test
public void testSpanAcrossBuffer() throws Exception {
Vertex outVertex = graph.addVertex("1", visibility, authorizations);
ArrayList<Vertex> terms = new ArrayList<>();
String before = "joe";
String after = " ferner";
String sign = before + after;
int start = Math.max(0, EntityHighlighter.BUFFER_SIZE - before.length());
int end = start + sign.length();
terms.add(createTermMention(outVertex, sign, PERSON_IRI, start, end));
List<OffsetItem> termAndTermMetadata = new EntityHighlighter().convertTermMentionsToOffsetItems(terms, "", authorizations);
StringBuilder expected = new StringBuilder();
StringBuilder str = new StringBuilder();
boolean doneWithExpected = false;
for (int i = 0; i < end; i++) {
if (i < start) {
expected.append("_");
str.append("_");
} else {
str.append(sign.substring(i - start, (i - start) + 1));
if (!doneWithExpected) {
expected.append("<span class=\"resolvable res " + termAndTermMetadata.get(0).getClassIdentifier() + "\" " +
"title=\"joe ferner\" " +
"data-info=\"{"process":"EntityHighlighterTest","conceptType":"http://visallo.org/test/person","start":" + start + ","end":" + end + ","id":"TM_" + start + "-" + end + "-5e180bf84df5539ac1e6762812dcd29e2b5b4374","outVertexId":"1","title":"joe ferner","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(0).getClassIdentifier() + "\">" +
"joe ferner" +
"</span>" +
"<style>.text .res{border-image-outset: 0 0 0px 0;border-bottom: 1px solid black;border-image-source: linear-gradient(to right, black, black);border-image-slice: 0 0 1 0;border-image-width: 0 0 1px 0;border-image-repeat: repeat;}.text .res.resolvable{border-image-source: repeating-linear-gradient(to right, transparent, transparent 1px, rgb(0,0,0) 1px, rgb(0,0,0) 3px);}</style>");
doneWithExpected = true;
}
}
}
String highlightedText = EntityHighlighter.getHighlightedText(str.toString(), termAndTermMetadata);
assertEquals(expected.toString(), highlightedText);
}
@Test
public void testGetHighlightedText() throws Exception {
Vertex outVertex = graph.addVertex("1", visibility, authorizations);
ArrayList<Vertex> terms = new ArrayList<>();
terms.add(createTermMention(outVertex, "joe ferner", PERSON_IRI, 18, 28));
terms.add(createTermMention(outVertex, "jeff kunkle", PERSON_IRI, 33, 44, "uniq1"));
List<OffsetItem> termAndTermMetadata = new EntityHighlighter().convertTermMentionsToOffsetItems(terms, "", authorizations);
String highlightedText = EntityHighlighter.getHighlightedText("Test highlight of Joe Ferner and Jeff Kunkle.", termAndTermMetadata);
String joeDataInfo = "data-info=\"{"process":"EntityHighlighterTest","conceptType":"http://visallo.org/test/person","start":18,"end":28,"id":"TM_18-28-5e180bf84df5539ac1e6762812dcd29e2b5b4374","outVertexId":"1","title":"joe ferner","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(0).getClassIdentifier() + "\"";
String jeffDataInfo = "data-info=\"{"process":"uniq1","conceptType":"http://visallo.org/test/person","start":33,"end":44,"id":"TM_33-44-ed6f44225a01778932642e3c8a1bc65ef5967432","outVertexId":"1","title":"jeff kunkle","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(1).getClassIdentifier() + "\"";
String expectedText = "Test highlight of " +
"<span class=\"resolvable res " + termAndTermMetadata.get(0).getClassIdentifier() + "\" title=\"joe ferner\" " + joeDataInfo + ">Joe Ferner</span>" +
" and <span class=\"resolvable res " + termAndTermMetadata.get(1).getClassIdentifier() + "\" title=\"jeff kunkle\" " + jeffDataInfo + ">Jeff Kunkle</span>.";
assertMatchStyleAndMeta(expectedText, highlightedText, 1);
}
@Test
public void testLineBreaksOffsetsCorrect() throws Exception {
Vertex outVertex = graph.addVertex("1", visibility, authorizations);
ArrayList<Vertex> terms = new ArrayList<>();
terms.add(createTermMention(outVertex, "joe", PERSON_IRI, 23, 29));
List<OffsetItem> termAndTermMetadata = new EntityHighlighter().convertTermMentionsToOffsetItems(terms, "", authorizations);
/*
Test highlight of: Joe
Ferner
and Jeff Kunkle.
*/
String highlightedText = EntityHighlighter.getHighlightedText("Test highlight of: Joe\nFerner\n\tand Jeff Kunkle.", termAndTermMetadata);
String joe = "<span class=\"resolvable res " + termAndTermMetadata.get(0).getClassIdentifier() + "\" " +
"title=\"joe\" " +
"data-info=\"{"process":"EntityHighlighterTest","conceptType":"http://visallo.org/test/person","start":23,"end":29,"id":"TM_23-29-f804acaaa829703b2de338ef485d68577e2bade6","outVertexId":"1","title":"joe","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(0).getClassIdentifier() + "\">";
String expectedText = "Test highlight of: Joe\n<br>" +
joe + "Ferner</span>\n<br>" +
"\tand Jeff Kunkle.";
assertMatchStyleAndMeta(expectedText, highlightedText, 1);
}
@Test
public void testLineBreaksSplitSpansOnlyWhenNotEmpty() throws Exception {
Vertex outVertex = graph.addVertex("1", visibility, authorizations);
ArrayList<Vertex> terms = new ArrayList<>();
terms.add(createTermMention(outVertex, "joe", PERSON_IRI, 19, 30));
List<OffsetItem> termAndTermMetadata = new EntityHighlighter().convertTermMentionsToOffsetItems(terms, "", authorizations);
String highlightedText = EntityHighlighter.getHighlightedText("Test highlight of: first\n\nlast", termAndTermMetadata);
String expectedText =
"Test highlight of: " +
"<span class=\"resolvable res " + termAndTermMetadata.get(0).getClassIdentifier() + "\" " +
"title=\"joe\" " +
"data-info=\"{"process":"EntityHighlighterTest","conceptType":"http://visallo.org/test/person","start":19,"end":30,"id":"TM_19-30-f804acaaa829703b2de338ef485d68577e2bade6","outVertexId":"1","title":"joe","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(0).getClassIdentifier() + "\">" +
"first\n<br>\n<br>last" +
"</span>";
assertMatchStyleAndMeta(expectedText, highlightedText, 1);
}
@Test
public void testGetOverlappingHighlightedText() throws Exception {
Vertex outVertex = graph.addVertex("1", visibility, authorizations);
ArrayList<Vertex> terms = new ArrayList<>();
terms.add(createTermMention(outVertex, "first", PERSON_IRI, 0, 5));
terms.add(createTermMention(outVertex, "t se", PERSON_IRI, 4, 8));
terms.add(createTermMention(outVertex, "third", PERSON_IRI, 13, 18));
List<OffsetItem> termAndTermMetadata = new EntityHighlighter().convertTermMentionsToOffsetItems(terms, "", authorizations);
String highlightedText = EntityHighlighter.getHighlightedText("first second third", termAndTermMetadata);
String expectedText =
"<span class=\"resolvable res " + termAndTermMetadata.get(0).getClassIdentifier() + "\" " +
"title=\"first\" " +
"data-info=\"{"process":"EntityHighlighterTest","conceptType":"http://visallo.org/test/person","start":0,"end":5,"id":"TM_0-5-e2cf06e792f9edf5f29a3737044ce1934bf0c08e","outVertexId":"1","title":"first","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(0).getClassIdentifier() + "\">" +
"firs" +
"<span class=\"resolvable res " + termAndTermMetadata.get(1).getClassIdentifier() + "\" " +
"title=\"t se\" " +
"data-info=\"{"process":"EntityHighlighterTest","conceptType":"http://visallo.org/test/person","start":4,"end":8,"id":"TM_4-8-61ade973cf8381c3e77b307be4c7314703a03b27","outVertexId":"1","title":"t se","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(1).getClassIdentifier() + "\">" +
"t" +
"</span>" +
"</span>" +
"<span class=\"resolvable res " + termAndTermMetadata.get(1).getClassIdentifier() + "\" " +
"title=\"t se\" " +
"data-ref=\"" + termAndTermMetadata.get(1).getClassIdentifier() + "\"> " +
"se" +
"</span>" +
"cond " +
"<span class=\"resolvable res " + termAndTermMetadata.get(2).getClassIdentifier() + "\" " +
"title=\"third\" " +
"data-info=\"{"process":"EntityHighlighterTest","conceptType":"http://visallo.org/test/person","start":13,"end":18,"id":"TM_13-18-864b9b57177a5dd86de4dc29e8925cf0836c03c7","outVertexId":"1","title":"third","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(2).getClassIdentifier() + "\">" +
"third" +
"</span>";
assertMatchStyleAndMeta(expectedText, highlightedText, 2);
}
@Test
public void testCrazyOverlappingHighlightedText() throws Exception {
Vertex outVertex = graph.addVertex("1", visibility, authorizations);
ArrayList<Vertex> terms = new ArrayList<>();
terms.add(createTermMention(outVertex, "first", PERSON_IRI, 0, 5));
terms.add(createTermMention(outVertex, "firs", PERSON_IRI, 0, 4));
terms.add(createTermMention(outVertex, "nd third", PERSON_IRI, 10, 18));
terms.add(createTermMention(outVertex, "t se", PERSON_IRI, 4, 8));
terms.add(createTermMention(outVertex, "irst sec", PERSON_IRI, 1, 9));
terms.add(createTermMention(outVertex, "nd ", PERSON_IRI, 10, 13));
terms.add(createTermMention(outVertex, "first second third", PERSON_IRI, 0, 18));
List<OffsetItem> termAndTermMetadata = new EntityHighlighter().convertTermMentionsToOffsetItems(terms, "", authorizations);
String highlightedText = EntityHighlighter.getHighlightedText("first second third", termAndTermMetadata);
String expectedText =
"<span class=\"resolvable res " + termAndTermMetadata.get(6).getClassIdentifier() + "\" " +
"title=\"first second third\" " +
"data-info=\"{"process":"EntityHighlighterTest","conceptType":"http://visallo.org/test/person","start":0,"end":18,"id":"TM_0-18-797c665056c681010dad6fb6a7f09f49a71605b2","outVertexId":"1","title":"first second third","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(6).getClassIdentifier() + "\">" +
"<span class=\"resolvable res " + termAndTermMetadata.get(0).getClassIdentifier() + "\" " +
"title=\"first\" " +
"data-info=\"{"process":"EntityHighlighterTest","conceptType":"http://visallo.org/test/person","start":0,"end":5,"id":"TM_0-5-e2cf06e792f9edf5f29a3737044ce1934bf0c08e","outVertexId":"1","title":"first","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(0).getClassIdentifier() + "\">" +
"<span class=\"resolvable res " + termAndTermMetadata.get(1).getClassIdentifier() + "\" " +
"title=\"firs\" " +
"data-info=\"{"process":"EntityHighlighterTest","conceptType":"http://visallo.org/test/person","start":0,"end":4,"id":"TM_0-4-c4781cfb3f0ea21db9d28c44486e65439eedeb07","outVertexId":"1","title":"firs","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(1).getClassIdentifier() + "\">" +
"f" +
"<span class=\"resolvable res " + termAndTermMetadata.get(4).getClassIdentifier() + "\" " +
"title=\"irst sec\" " +
"data-info=\"{"process":"EntityHighlighterTest","conceptType":"http://visallo.org/test/person","start":1,"end":9,"id":"TM_1-9-e9c080fef2bcd729b0634c9d9e5bd562b3b1c1a4","outVertexId":"1","title":"irst sec","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(4).getClassIdentifier() + "\">" +
"irs" +
"<span class=\"resolvable res " + termAndTermMetadata.get(3).getClassIdentifier() + "\" " +
"title=\"t se\" " +
"data-info=\"{"process":"EntityHighlighterTest","conceptType":"http://visallo.org/test/person","start":4,"end":8,"id":"TM_4-8-61ade973cf8381c3e77b307be4c7314703a03b27","outVertexId":"1","title":"t se","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(3).getClassIdentifier() + "\">" +
"</span>" +
"</span>" +
"</span>" +
"<span class=\"resolvable res " + termAndTermMetadata.get(3).getClassIdentifier() + "\" " +
"title=\"t se\" " +
"data-ref=\"" + termAndTermMetadata.get(3).getClassIdentifier() + "\">" +
"<span class=\"resolvable res " + termAndTermMetadata.get(4).getClassIdentifier() + "\" " +
"title=\"irst sec\" " +
"data-ref=\"" + termAndTermMetadata.get(4).getClassIdentifier() + "\">t</span>" +
"</span>" +
"</span>" +
"<span class=\"resolvable res " + termAndTermMetadata.get(3).getClassIdentifier() + "\" " +
"title=\"t se\" " +
"data-ref=\"" + termAndTermMetadata.get(3).getClassIdentifier() + "\">" +
"<span class=\"resolvable res " + termAndTermMetadata.get(4).getClassIdentifier() + "\" " +
"title=\"irst sec\" " +
"data-ref=\"" + termAndTermMetadata.get(4).getClassIdentifier() + "\"> se</span>" +
"c" +
"</span>" +
"o" +
"<span class=\"resolvable res " + termAndTermMetadata.get(2).getClassIdentifier() + "\" " +
"title=\"nd third\" " +
"data-info=\"{"process":"EntityHighlighterTest","conceptType":"http://visallo.org/test/person","start":10,"end":18,"id":"TM_10-18-24f7791aa39784662e0f22bd5b99c96aacba08bc","outVertexId":"1","title":"nd third","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(2).getClassIdentifier() + "\">" +
"<span class=\"resolvable res " + termAndTermMetadata.get(5).getClassIdentifier() + "\" " +
"title=\"nd \" " +
"data-info=\"{"process":"EntityHighlighterTest","conceptType":"http://visallo.org/test/person","start":10,"end":13,"id":"TM_10-13-7e00646a2ce55eec5a5c69725980b4cdf8678558","outVertexId":"1","title":"nd ","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(5).getClassIdentifier() + "\">" +
"nd " +
"</span>" +
"third" +
"</span>" +
"</span>";
assertMatchStyleAndMeta(expectedText, highlightedText, 5);
}
private void assertMatchStyleAndMeta(String expected, String actual, int expectedDepth) throws Exception {
Pattern pattern = Pattern.compile("^(.*)<style>(.*)</style>$", Pattern.DOTALL);
Matcher matcher = pattern.matcher(actual);
if (matcher.matches() && matcher.groupCount() == 2) {
assertEquals(expected, matcher.group(1));
String style = matcher.group(2);
StringBuilder selector = new StringBuilder(".text");
for (int i = 0; i < expectedDepth; i++) {
selector.append(" .res");
String depthSelector = selector.toString() + "{";
assertTrue("Style contains: " + depthSelector, style.contains(depthSelector));
}
} else {
throw new Exception("Actual didn't match regex");
}
}
private Vertex createTermMention(Vertex outVertex, String sign, String conceptIri, int start, int end) {
return createTermMention(outVertex, sign, conceptIri, start, end, null, null);
}
private Vertex createTermMention(Vertex outVertex, String sign, String conceptIri, int start, int end, Vertex resolvedToVertex, Edge resolvedEdge) {
TermMentionBuilder tmb = new TermMentionBuilder()
.outVertex(outVertex)
.propertyKey(PROPERTY_KEY)
.propertyName(VisalloProperties.TEXT.getPropertyName())
.conceptIri(conceptIri)
.start(start)
.end(end)
.title(sign)
.visibilityJson("")
.process(getClass().getSimpleName());
if (resolvedToVertex != null || resolvedEdge != null) {
tmb.resolvedTo(resolvedToVertex, resolvedEdge);
}
return tmb.save(graph, visibilityTranslator, user, authorizations);
}
private Vertex createTermMention(Vertex outVertex, String sign, String conceptIri, int start, int end, String process) {
return new TermMentionBuilder()
.outVertex(outVertex)
.propertyKey(PROPERTY_KEY)
.propertyName(VisalloProperties.TEXT.getPropertyName())
.conceptIri(conceptIri)
.start(start)
.end(end)
.title(sign)
.visibilityJson("")
.process(process)
.save(graph, visibilityTranslator, user, authorizations);
}
@Test
public void testGetHighlightedTextOverlaps() throws Exception {
Vertex outVertex = graph.addVertex("1", visibility, authorizations);
ArrayList<Vertex> terms = new ArrayList<>();
terms.add(createTermMention(outVertex, "joe ferner", PERSON_IRI, 18, 28));
terms.add(createTermMention(outVertex, "jeff kunkle", PERSON_IRI, 18, 21));
List<OffsetItem> termAndTermMetadata = new EntityHighlighter().convertTermMentionsToOffsetItems(terms, "", authorizations);
String highlightedText = EntityHighlighter.getHighlightedText("Test highlight of Joe Ferner.", termAndTermMetadata);
String expectedText =
"Test highlight of " +
"<span class=\"resolvable res " + termAndTermMetadata.get(0).getClassIdentifier() + "\" " +
"title=\"joe ferner\" " +
"data-info=\"{"process":"EntityHighlighterTest","conceptType":"http://visallo.org/test/person","start":18,"end":28,"id":"TM_18-28-5e180bf84df5539ac1e6762812dcd29e2b5b4374","outVertexId":"1","title":"joe ferner","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(0).getClassIdentifier() + "\">" +
"<span class=\"resolvable res " + termAndTermMetadata.get(1).getClassIdentifier() + "\" " +
"title=\"jeff kunkle\" " +
"data-info=\"{"process":"EntityHighlighterTest","conceptType":"http://visallo.org/test/person","start":18,"end":21,"id":"TM_18-21-573648828a7888c138cbc1d580be8d09a1f2e782","outVertexId":"1","title":"jeff kunkle","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(1).getClassIdentifier() + "\">" +
"Joe" +
"</span> " +
"Ferner" +
"</span>.";
assertMatchStyleAndMeta(expectedText, highlightedText, 2);
}
@Test
public void testGetHighlightedTextExactOverlapsTwoDocuments() throws Exception{
Authorizations tmAuths = graph.createAuthorizations(TermMentionRepository.VISIBILITY_STRING);
Vertex v1 = graph.addVertex("v1", visibility, authorizations);
Vertex v2 = graph.addVertex("v2", visibility, authorizations);
Vertex vjf = graph.addVertex("jf", visibility, authorizations);
Edge e1 = graph.addEdge("e1", v1, vjf, "has", visibility, authorizations);
Edge e2 = graph.addEdge("e2", v2, vjf, "has", visibility, authorizations);
createTermMention(v1, "joe ferner", PERSON_IRI, 18, 28, vjf, e1);
createTermMention(v2, "joe ferner", PERSON_IRI, 18, 28, vjf, e2);
graph.flush();
ArrayList<Vertex> terms = Lists.newArrayList(graph.getVertex("v1", tmAuths).getVertices(Direction.BOTH, VisalloProperties.TERM_MENTION_LABEL_HAS_TERM_MENTION, tmAuths));
List<OffsetItem> termAndTermMetadata = new EntityHighlighter().convertTermMentionsToOffsetItems(terms, "", this.authorizations);
String highlightedText = EntityHighlighter.getHighlightedText("Test highlight of Joe Ferner.", termAndTermMetadata);
String expectedText =
"Test highlight of <span class=\"resolved res " + termAndTermMetadata.get(0).getClassIdentifier() + "\" " +
"title=\"joe ferner\" " +
"data-info=\"{"process":"EntityHighlighterTest","resolvedToVertexId":"jf","resolvedToEdgeId":"e1","conceptType":"http://visallo.org/test/person","start":18,"termMentionFor":"VERTEX","termMentionForElementId":"jf","end":28,"id":"TM_18-28-47b5d3c6dc289fae21f303034649da038a7db76d","outVertexId":"v1","title":"joe ferner","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(0).getClassIdentifier() + "\">" +
"Joe Ferner</span>.";
assertMatchStyleAndMeta(expectedText, highlightedText, 1);
terms = Lists.newArrayList(graph.getVertex("v2", tmAuths).getVertices(Direction.BOTH, VisalloProperties.TERM_MENTION_LABEL_HAS_TERM_MENTION, tmAuths));
termAndTermMetadata = new EntityHighlighter().convertTermMentionsToOffsetItems(terms, "", this.authorizations);
highlightedText = EntityHighlighter.getHighlightedText("Test highlight of Joe Ferner.", termAndTermMetadata);
expectedText =
"Test highlight of <span class=\"resolved res " + termAndTermMetadata.get(0).getClassIdentifier() + "\" " +
"title=\"joe ferner\" " +
"data-info=\"{"process":"EntityHighlighterTest","resolvedToVertexId":"jf","resolvedToEdgeId":"e2","conceptType":"http://visallo.org/test/person","start":18,"termMentionFor":"VERTEX","termMentionForElementId":"jf","end":28,"id":"TM_18-28-eb6560a01113a23abf584241655b8a4c5af1bce0","outVertexId":"v2","title":"joe ferner","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(0).getClassIdentifier() + "\">" +
"Joe Ferner</span>.";
assertMatchStyleAndMeta(expectedText, highlightedText, 1);
}
@Test
public void testFilterResolvedTermMentions() throws Exception {
String str = "This is a test sentence";
List<OffsetItem> offsetItems = new ArrayList<>();
Vertex text = graph.addVertex("1", visibility, authorizations);
Vertex v1 = graph.addVertex("v1", visibility, authorizations);
Edge e1 = graph.addEdge("e1", text, v1, "has", visibility, authorizations);
List<Vertex> terms = new ArrayList<>();
Vertex resolvable = createTermMention(text, "Wrong", PERSON_IRI, 0, 4);
Vertex resolved = createTermMention(text, "This", PERSON_IRI, 0, 4, v1, e1);
graph.addEdge("e2", resolved, resolvable, VisalloProperties.TERM_MENTION_RESOLVED_FROM, visibility, authorizations);
terms.add(resolvable);
terms.add(resolved);
List<OffsetItem> termAndTermMetadata = new EntityHighlighter().convertTermMentionsToOffsetItems(terms, "", this.authorizations);
String highlightedText = EntityHighlighter.getHighlightedText(str, termAndTermMetadata);
String expectedText =
"<span " +
"class=\"resolved res " + termAndTermMetadata.get(1).getClassIdentifier() + "\" " +
"title=\"This\" " +
"data-info=\"{"process":"EntityHighlighterTest","resolvedToEdgeId":"e1","conceptType":"http://visallo.org/test/person","start":0,"title":"This","sandboxStatus":"PRIVATE","resolvedToVertexId":"v1","termMentionFor":"VERTEX","termMentionForElementId":"v1","end":4,"id":"TM_0-4-cc377e2478ec54c8e486a1a814b45e80b2d5db42","outVertexId":"1","resolvedFromTermMentionId":"TM_0-4-6e1990686375878517ed309bdc271b758164f939"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(1).getClassIdentifier() + "\"" +
">This</span> is a test sentence";
assertMatchStyleAndMeta(expectedText, highlightedText, 1);
}
@Test
public void testGetHighlightedTextNestedEntity() throws Exception {
String text = "This is a test sentence";
List<OffsetItem> offsetItems = new ArrayList<>();
OffsetItem mockEntity1 = mock(VertexOffsetItem.class);
when(mockEntity1.getStart()).thenReturn(0l);
when(mockEntity1.getEnd()).thenReturn(4l);
when(mockEntity1.getResolvedToVertexId()).thenReturn("0");
when(mockEntity1.getCssClasses()).thenReturn(asList(new String[]{"This"}));
when(mockEntity1.shouldHighlight()).thenReturn(true);
when(mockEntity1.getInfoJson()).thenReturn(new JSONObject("{\"data\":\"attribute\"}"));
offsetItems.add(mockEntity1);
OffsetItem mockEntity2 = mock(VertexOffsetItem.class);
when(mockEntity2.getStart()).thenReturn(0l);
when(mockEntity2.getEnd()).thenReturn(4l);
when(mockEntity2.getResolvedToVertexId()).thenReturn("1");
when(mockEntity2.getCssClasses()).thenReturn(asList(new String[]{"This"}));
when(mockEntity2.shouldHighlight()).thenReturn(true);
when(mockEntity2.getInfoJson()).thenReturn(new JSONObject("{\"data\":\"attribute\"}"));
offsetItems.add(mockEntity2);
OffsetItem mockEntity2x = mock(VertexOffsetItem.class);
when(mockEntity2.getStart()).thenReturn(0l);
when(mockEntity2.getEnd()).thenReturn(4l);
when(mockEntity2.getResolvedToVertexId()).thenReturn("1");
when(mockEntity2.getCssClasses()).thenReturn(asList(new String[]{"This"}));
when(mockEntity2.shouldHighlight()).thenReturn(false);
when(mockEntity2.getInfoJson()).thenReturn(new JSONObject("{\"data\":\"attribute\"}"));
offsetItems.add(mockEntity2x);
OffsetItem mockEntity3 = mock(VertexOffsetItem.class);
when(mockEntity3.getStart()).thenReturn(0l);
when(mockEntity3.getEnd()).thenReturn(7l);
when(mockEntity3.getCssClasses()).thenReturn(asList(new String[]{"This is"}));
when(mockEntity3.shouldHighlight()).thenReturn(true);
when(mockEntity3.getInfoJson()).thenReturn(new JSONObject("{\"data\":\"attribute\"}"));
offsetItems.add(mockEntity3);
OffsetItem mockEntity4 = mock(VertexOffsetItem.class);
when(mockEntity4.getStart()).thenReturn(5l);
when(mockEntity4.getEnd()).thenReturn(9l);
when(mockEntity4.getCssClasses()).thenReturn(asList(new String[]{"is a"}));
when(mockEntity4.shouldHighlight()).thenReturn(true);
when(mockEntity4.getClassIdentifier()).thenReturn("id");
when(mockEntity4.getInfoJson()).thenReturn(new JSONObject("{\"data\":\"attribute\"}"));
offsetItems.add(mockEntity4);
OffsetItem mockEntity5 = mock(VertexOffsetItem.class);
when(mockEntity5.getStart()).thenReturn(15l);
when(mockEntity5.getEnd()).thenReturn(23l);
when(mockEntity5.getCssClasses()).thenReturn(asList(new String[]{"sentence"}));
when(mockEntity5.shouldHighlight()).thenReturn(true);
when(mockEntity5.getInfoJson()).thenReturn(new JSONObject("{\"data\":\"attribute\"}"));
offsetItems.add(mockEntity5);
String highlightedText = EntityHighlighter.getHighlightedText(text, offsetItems);
String expectedText =
"<span class=\"This is\" data-info=\"{"data":"attribute"}\">" +
"<span class=\"This\" data-info=\"{"data":"attribute"}\">This</span> " +
"<span class=\"is a\" data-info=\"{"data":"attribute"}\" data-ref-id=\"id\">is</span>" +
"</span>" +
"<span class=\"is a\" data-ref=\"id\"> a</span>" +
" test " +
"<span class=\"sentence\" data-info=\"{"data":"attribute"}\">sentence</span>";
assertMatchStyleAndMeta(expectedText, highlightedText, 2);
}
@Test
public void testGetHighlightedTextWithAccentedCharacters() throws Exception {
Vertex outVertex = graph.addVertex("1", visibility, authorizations);
ArrayList<Vertex> terms = new ArrayList<>();
terms.add(createTermMention(outVertex, "US", LOCATION_IRI, 48, 50));
List<OffsetItem> termAndTermMetadata = new EntityHighlighter().convertTermMentionsToOffsetItems(terms, "", authorizations);
String highlightedText = EntityHighlighter.getHighlightedText("Ejército de Liberación Nacional® partnered with US on peace treaty", termAndTermMetadata);
String expectedText =
"Ejército de Liberación Nacional® partnered with " +
"<span class=\"resolvable res " + termAndTermMetadata.get(0).getClassIdentifier() + "\" " +
"title=\"US\" " +
"data-info=\"{"process":"EntityHighlighterTest","conceptType":"http://visallo.org/test/location","start":48,"end":50,"id":"TM_48-50-3921918b09b047c621b891f4f6ed60abb5d7f9e4","outVertexId":"1","title":"US","sandboxStatus":"PRIVATE"}\" " +
"data-ref-id=\"" + termAndTermMetadata.get(0).getClassIdentifier() + "\">" +
"US" +
"</span> on peace treaty";
assertMatchStyleAndMeta(expectedText, highlightedText, 1);
}
private List<String> asList(String[] strings) {
List<String> results = new ArrayList<>();
Collections.addAll(results, strings);
return results;
}
}
|
923ef745713303cd098724af7f4d8c34c6a3ab78
| 845 |
java
|
Java
|
src/main/java/nz/co/gregs/amhan/components/grid/renderer/DBIntegerEnumRenderer.java
|
gregorydgraham/DBvolutionVaadin7
|
d782ae9d479da33bb87dcf858507871703b22721
|
[
"Unlicense"
] | null | null | null |
src/main/java/nz/co/gregs/amhan/components/grid/renderer/DBIntegerEnumRenderer.java
|
gregorydgraham/DBvolutionVaadin7
|
d782ae9d479da33bb87dcf858507871703b22721
|
[
"Unlicense"
] | 1 |
2021-08-30T16:25:47.000Z
|
2021-08-30T16:25:47.000Z
|
src/main/java/nz/co/gregs/amhan/components/grid/renderer/DBIntegerEnumRenderer.java
|
gregorydgraham/Amhan
|
d782ae9d479da33bb87dcf858507871703b22721
|
[
"Unlicense"
] | null | null | null | 32.5 | 157 | 0.777515 | 1,000,982 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package nz.co.gregs.amhan.components.grid.renderer;
import nz.co.gregs.amhan.components.grid.labelgenerator.DBIntegerEnumLabelGenerator;
import nz.co.gregs.dbvolution.DBRow;
import nz.co.gregs.dbvolution.datatypes.DBEnumValue;
import nz.co.gregs.dbvolution.datatypes.DBIntegerEnum;
/**
*
* @author gregorygraham
* @param <R>
* @param <E>
*/
public class DBIntegerEnumRenderer<R extends DBRow, E extends Enum<E> & DBEnumValue<Long>> extends AbstractDBRowPropertyRenderer<R, DBIntegerEnum<E>, Long> {
public DBIntegerEnumRenderer(R example, DBIntegerEnum<E> fieldOfExample) {
super(new DBIntegerEnumLabelGenerator<R,E>(example,fieldOfExample));
}
}
|
923ef82706544a87f78b7921969afb7bf02ef618
| 11,603 |
java
|
Java
|
src/java/org/apache/cassandra/io/sstable/SSTable.java
|
penberg/scylla-tools-java
|
283ce3a58a2b04e60a84ce6744eee55ce09b3801
|
[
"Apache-2.0"
] | 103 |
2015-01-21T09:38:38.000Z
|
2021-11-01T13:41:47.000Z
|
src/java/org/apache/cassandra/io/sstable/SSTable.java
|
penberg/scylla-tools-java
|
283ce3a58a2b04e60a84ce6744eee55ce09b3801
|
[
"Apache-2.0"
] | 15 |
2015-12-30T16:07:36.000Z
|
2017-04-07T20:38:53.000Z
|
src/java/org/apache/cassandra/io/sstable/SSTable.java
|
penberg/scylla-tools-java
|
283ce3a58a2b04e60a84ce6744eee55ce09b3801
|
[
"Apache-2.0"
] | 65 |
2015-02-04T04:12:16.000Z
|
2021-07-04T20:51:22.000Z
| 35.922601 | 130 | 0.652762 | 1,000,983 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.io.sstable;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import com.google.common.collect.Sets;
import com.google.common.io.Files;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.db.BufferDecoratedKey;
import org.apache.cassandra.db.DecoratedKey;
import org.apache.cassandra.db.RowIndexEntry;
import org.apache.cassandra.dht.IPartitioner;
import org.apache.cassandra.io.FSWriteError;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.io.util.RandomAccessReader;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.memory.HeapAllocator;
import org.apache.cassandra.utils.Pair;
/**
* This class is built on top of the SequenceFile. It stores
* data on disk in sorted fashion. However the sorting is upto
* the application. This class expects keys to be handed to it
* in sorted order.
*
* A separate index file is maintained as well, containing the
* SSTable keys and the offset into the SSTable at which they are found.
* Every 1/indexInterval key is read into memory when the SSTable is opened.
*
* Finally, a bloom filter file is also kept for the keys in each SSTable.
*/
public abstract class SSTable
{
static final Logger logger = LoggerFactory.getLogger(SSTable.class);
public static final int TOMBSTONE_HISTOGRAM_BIN_SIZE = 100;
public final Descriptor descriptor;
protected final Set<Component> components;
public final CFMetaData metadata;
public final boolean compression;
public DecoratedKey first;
public DecoratedKey last;
protected SSTable(Descriptor descriptor, CFMetaData metadata)
{
this(descriptor, new HashSet<>(), metadata);
}
protected SSTable(Descriptor descriptor, Set<Component> components, CFMetaData metadata)
{
// In almost all cases, metadata shouldn't be null, but allowing null allows to create a mostly functional SSTable without
// full schema definition. SSTableLoader use that ability
assert descriptor != null;
assert components != null;
assert metadata != null;
this.descriptor = descriptor;
Set<Component> dataComponents = new HashSet<>(components);
this.compression = dataComponents.contains(Component.COMPRESSION_INFO);
this.components = new CopyOnWriteArraySet<>(dataComponents);
this.metadata = metadata;
}
/**
* We use a ReferenceQueue to manage deleting files that have been compacted
* and for which no more SSTable references exist. But this is not guaranteed
* to run for each such file because of the semantics of the JVM gc. So,
* we write a marker to `compactedFilename` when a file is compacted;
* if such a marker exists on startup, the file should be removed.
*
* This method will also remove SSTables that are marked as temporary.
*
* @return true if the file was deleted
*/
public static boolean delete(Descriptor desc, Set<Component> components)
{
// remove the DATA component first if it exists
if (components.contains(Component.DATA))
FileUtils.deleteWithConfirm(desc.filenameFor(Component.DATA));
for (Component component : components)
{
if (component.equals(Component.DATA) || component.equals(Component.SUMMARY))
continue;
FileUtils.deleteWithConfirm(desc.filenameFor(component));
}
if (components.contains(Component.SUMMARY))
FileUtils.delete(desc.filenameFor(Component.SUMMARY));
logger.trace("Deleted {}", desc);
return true;
}
public IPartitioner getPartitioner()
{
return metadata.partitioner;
}
public DecoratedKey decorateKey(ByteBuffer key)
{
return getPartitioner().decorateKey(key);
}
/**
* If the given @param key occupies only part of a larger buffer, allocate a new buffer that is only
* as large as necessary.
*/
public static DecoratedKey getMinimalKey(DecoratedKey key)
{
return key.getKey().position() > 0 || key.getKey().hasRemaining() || !key.getKey().hasArray()
? new BufferDecoratedKey(key.getToken(), HeapAllocator.instance.clone(key.getKey()))
: key;
}
public String getFilename()
{
return descriptor.filenameFor(Component.DATA);
}
public String getIndexFilename()
{
return descriptor.filenameFor(Component.PRIMARY_INDEX);
}
public String getColumnFamilyName()
{
return descriptor.cfname;
}
public String getKeyspaceName()
{
return descriptor.ksname;
}
public List<String> getAllFilePaths()
{
List<String> ret = new ArrayList<>();
for (Component component : components)
ret.add(descriptor.filenameFor(component));
return ret;
}
/**
* @return Descriptor and Component pair. null if given file is not acceptable as SSTable component.
* If component is of unknown type, returns CUSTOM component.
*/
public static Pair<Descriptor, Component> tryComponentFromFilename(File dir, String name)
{
try
{
return Component.fromFilename(dir, name);
}
catch (Throwable e)
{
return null;
}
}
/**
* Discovers existing components for the descriptor. Slow: only intended for use outside the critical path.
*/
public static Set<Component> componentsFor(final Descriptor desc)
{
try
{
try
{
return readTOC(desc);
}
catch (FileNotFoundException e)
{
Set<Component> components = discoverComponentsFor(desc);
if (components.isEmpty())
return components; // sstable doesn't exist yet
if (!components.contains(Component.TOC))
components.add(Component.TOC);
appendTOC(desc, components);
return components;
}
}
catch (IOException e)
{
throw new IOError(e);
}
}
public static Set<Component> discoverComponentsFor(Descriptor desc)
{
Set<Component.Type> knownTypes = Sets.difference(Component.TYPES, Collections.singleton(Component.Type.CUSTOM));
Set<Component> components = Sets.newHashSetWithExpectedSize(knownTypes.size());
for (Component.Type componentType : knownTypes)
{
if (componentType == Component.Type.DIGEST)
{
if (desc.digestComponent != null && new File(desc.filenameFor(desc.digestComponent)).exists())
components.add(desc.digestComponent);
}
else
{
Component component = new Component(componentType);
if (new File(desc.filenameFor(component)).exists())
components.add(component);
}
}
return components;
}
/** @return An estimate of the number of keys contained in the given index file. */
protected long estimateRowsFromIndex(RandomAccessReader ifile) throws IOException
{
// collect sizes for the first 10000 keys, or first 10 megabytes of data
final int SAMPLES_CAP = 10000, BYTES_CAP = (int)Math.min(10000000, ifile.length());
int keys = 0;
while (ifile.getFilePointer() < BYTES_CAP && keys < SAMPLES_CAP)
{
ByteBufferUtil.skipShortLength(ifile);
RowIndexEntry.Serializer.skip(ifile, descriptor.version);
keys++;
}
assert keys > 0 && ifile.getFilePointer() > 0 && ifile.length() > 0 : "Unexpected empty index file: " + ifile;
long estimatedRows = ifile.length() / (ifile.getFilePointer() / keys);
ifile.seek(0);
return estimatedRows;
}
public long bytesOnDisk()
{
long bytes = 0;
for (Component component : components)
{
bytes += new File(descriptor.filenameFor(component)).length();
}
return bytes;
}
@Override
public String toString()
{
return getClass().getSimpleName() + "(" +
"path='" + getFilename() + '\'' +
')';
}
/**
* Reads the list of components from the TOC component.
* @return set of components found in the TOC
*/
protected static Set<Component> readTOC(Descriptor descriptor) throws IOException
{
File tocFile = new File(descriptor.filenameFor(Component.TOC));
List<String> componentNames = Files.readLines(tocFile, Charset.defaultCharset());
Set<Component> components = Sets.newHashSetWithExpectedSize(componentNames.size());
for (String componentName : componentNames)
{
Component component = new Component(Component.Type.fromRepresentation(componentName), componentName);
if (!new File(descriptor.filenameFor(component)).exists())
logger.error("Missing component: {}", descriptor.filenameFor(component));
else
components.add(component);
}
return components;
}
/**
* Appends new component names to the TOC component.
*/
protected static void appendTOC(Descriptor descriptor, Collection<Component> components)
{
File tocFile = new File(descriptor.filenameFor(Component.TOC));
try (PrintWriter w = new PrintWriter(new FileWriter(tocFile, true)))
{
for (Component component : components)
w.println(component.name);
}
catch (IOException e)
{
throw new FSWriteError(e, tocFile);
}
}
/**
* Registers new custom components. Used by custom compaction strategies.
* Adding a component for the second time is a no-op.
* Don't remove this - this method is a part of the public API, intended for use by custom compaction strategies.
* @param newComponents collection of components to be added
*/
public synchronized void addComponents(Collection<Component> newComponents)
{
Collection<Component> componentsToAdd = Collections2.filter(newComponents, Predicates.not(Predicates.in(components)));
appendTOC(descriptor, componentsToAdd);
components.addAll(componentsToAdd);
}
}
|
923ef83b1cabad947286225b9b2915a964042503
| 1,025 |
java
|
Java
|
hazelcast-yarn/src/test/java/com/hazelcast/yarn/wordcount/FileGenerator.java
|
hazelcast-incubator/cascading-prototype
|
cbf3d60262006081fe51acd12ef4ac5c193a03fd
|
[
"Apache-2.0"
] | 1 |
2015-07-27T11:50:58.000Z
|
2015-07-27T11:50:58.000Z
|
hazelcast-yarn/src/test/java/com/hazelcast/yarn/wordcount/FileGenerator.java
|
hazelcast-incubator/cascading-prototype
|
cbf3d60262006081fe51acd12ef4ac5c193a03fd
|
[
"Apache-2.0"
] | 5 |
2020-02-28T01:19:10.000Z
|
2021-06-04T01:14:27.000Z
|
hazelcast-yarn/src/test/java/com/hazelcast/yarn/wordcount/FileGenerator.java
|
hazelcast-incubator/cascading-prototype
|
cbf3d60262006081fe51acd12ef4ac5c193a03fd
|
[
"Apache-2.0"
] | null | null | null | 28.472222 | 74 | 0.481951 | 1,000,984 |
package com.hazelcast.yarn.wordcount;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class FileGenerator {
public static void main(String[] args) throws IOException {
String dir = args[0];
int files_count = Integer.valueOf(args[1]);
int records_count = Integer.valueOf(args[2]);
for (int idx = 1; idx <= files_count; idx++) {
FileWriter fw = new FileWriter(new File(dir + "file_" + idx));
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= records_count; i++) {
sb.append(String.valueOf(i)).append(" \n");
if (i % 4096 == 0) {
fw.write(sb.toString());
fw.flush();
sb = new StringBuilder();
}
}
if (sb.length() > 0) {
fw.write(sb.toString());
fw.flush();
fw.close();
idx++;
}
}
}
}
|
923ef89f294f6dd5f505ff46e479105ed193b69c
| 1,315 |
java
|
Java
|
src/main/lee/code/code_322__Coin_Change/C322_MainClass.java
|
code543/leetcodequestions
|
44cbfe6718ada04807b6600a5d62b9f0016d4ab2
|
[
"MIT"
] | 1 |
2019-02-23T06:47:17.000Z
|
2019-02-23T06:47:17.000Z
|
src/main/lee/code/code_322__Coin_Change/C322_MainClass.java
|
code543/leetcodequestions
|
44cbfe6718ada04807b6600a5d62b9f0016d4ab2
|
[
"MIT"
] | null | null | null |
src/main/lee/code/code_322__Coin_Change/C322_MainClass.java
|
code543/leetcodequestions
|
44cbfe6718ada04807b6600a5d62b9f0016d4ab2
|
[
"MIT"
] | null | null | null | 28.586957 | 75 | 0.559696 | 1,000,985 |
package lee.code.code_322__Coin_Change;
import java.util.*;
import lee.util.*;
import java.io.*;
import com.eclipsesource.json.*;
import java.text.*;
public class C322_MainClass {
public static String testCase = "[1,2,5]\n11";
/*
public static int[] Utils.stringToIntegerArray(String input) {
input = input.trim();
input = input.substring(1, input.length() - 1);
if (input.length() == 0) {
return new int[0];
}
String[] parts = input.split(",");
int[] output = new int[parts.length];
for(int index = 0; index < parts.length; index++) {
String part = parts[index].trim();
output[index] = Integer.parseInt(part);
}
return output;
}
*/
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new StringReader(testCase));
String line;
while ((line = in.readLine()) != null) {
int[] coins = Utils.stringToIntegerArray(line);
line = in.readLine();
int amount = Integer.parseInt(line);
int ret = new Solution().coinChange(coins, amount);
String out = String.valueOf(ret);
System.out.print(out);
}
}
}
|
923ef91e2940ec1f8ba8b59e53d30ba876388f29
| 1,002 |
java
|
Java
|
api/src/main/java/ca/bc/gov/educ/penreg/api/struct/PenMatchStudent.java
|
bcgov/EDUC-PEN-REG-BATCH-API
|
0e53a679f3fd98947cd80e2dd5f3b0a4a1612eb8
|
[
"Apache-2.0"
] | 3 |
2020-07-23T17:03:23.000Z
|
2021-07-27T16:12:25.000Z
|
api/src/main/java/ca/bc/gov/educ/penreg/api/struct/PenMatchStudent.java
|
bcgov/EDUC-PEN-REG-BATCH-API
|
0e53a679f3fd98947cd80e2dd5f3b0a4a1612eb8
|
[
"Apache-2.0"
] | 4 |
2020-07-22T21:01:30.000Z
|
2021-03-23T16:06:20.000Z
|
api/src/main/java/ca/bc/gov/educ/penreg/api/struct/PenMatchStudent.java
|
bcgov/EDUC-PEN-REG-BATCH-API
|
0e53a679f3fd98947cd80e2dd5f3b0a4a1612eb8
|
[
"Apache-2.0"
] | null | null | null | 15.415385 | 41 | 0.605788 | 1,000,986 |
package ca.bc.gov.educ.penreg.api.struct;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* The type Pen match student.
*/
@Data
@NoArgsConstructor
public class PenMatchStudent {
/**
* The Pen.
*/
protected String pen;
/**
* The Dob.
*/
protected String dob;
/**
* The Sex.
*/
protected String sex;
/**
* The Enrolled grade code.
*/
protected String enrolledGradeCode;
/**
* The Surname.
*/
protected String surname;
/**
* The Given name.
*/
protected String givenName;
/**
* The Middle name.
*/
protected String middleName;
/**
* The Usual surname.
*/
protected String usualSurname;
/**
* The Usual given name.
*/
protected String usualGivenName;
/**
* The Usual middle name.
*/
protected String usualMiddleName;
/**
* The mincode.
*/
protected String mincode;
/**
* The Local id.
*/
protected String localID;
/**
* The Postal.
*/
protected String postal;
}
|
923ef9775292031d244289772e1e80b77e3f7601
| 1,050 |
java
|
Java
|
clearth-core/src/main/java/com/exactprosystems/clearth/utils/tabledata/typing/TableDataType.java
|
exactpro/clearth
|
71b6a48b6ea6eb6653f903b8010c418de70a28d5
|
[
"Apache-2.0"
] | 23 |
2019-12-18T05:32:58.000Z
|
2021-12-02T14:51:12.000Z
|
clearth-core/src/main/java/com/exactprosystems/clearth/utils/tabledata/typing/TableDataType.java
|
Exactpro/clearth
|
a22a859e94c63b54a3596eefb608d91ca79e0e6d
|
[
"Apache-2.0"
] | 1 |
2020-08-07T09:55:41.000Z
|
2020-08-11T12:18:36.000Z
|
clearth-core/src/main/java/com/exactprosystems/clearth/utils/tabledata/typing/TableDataType.java
|
Exactpro/clearth
|
a22a859e94c63b54a3596eefb608d91ca79e0e6d
|
[
"Apache-2.0"
] | 8 |
2019-12-18T05:32:59.000Z
|
2021-07-18T05:57:03.000Z
| 29.166667 | 80 | 0.635238 | 1,000,987 |
/******************************************************************************
* Copyright 2009-2019 Exactpro Systems Limited
* https://www.exactpro.com
* Build Software to Test Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.exactprosystems.clearth.utils.tabledata.typing;
public enum TableDataType
{
INTEGER,
STRING,
BOOLEAN,
BYTE,
SHORT,
LONG,
FLOAT,
DOUBLE,
BIGDECIMAL,
LOCALDATE,
LOCALTIME,
LOCALDATETIME,
OBJECT
}
|
923ef984ec1ba87f8c3fa494493933ed55312513
| 362 |
java
|
Java
|
docs/sourcecodes/OpenBridge-base/ob-framework/src/main/java/com/harmazing/framework/quartz/demo/TestJob.java
|
gavin2lee/incubator-gl
|
c95623af811195c3e89513ec30e52862d6562add
|
[
"Apache-2.0"
] | 3 |
2016-07-25T03:47:06.000Z
|
2019-11-18T08:42:00.000Z
|
docs/sourcecodes/OpenBridge-base/ob-framework/src/main/java/com/harmazing/framework/quartz/demo/TestJob.java
|
gavin2lee/incubator-gl
|
c95623af811195c3e89513ec30e52862d6562add
|
[
"Apache-2.0"
] | null | null | null |
docs/sourcecodes/OpenBridge-base/ob-framework/src/main/java/com/harmazing/framework/quartz/demo/TestJob.java
|
gavin2lee/incubator-gl
|
c95623af811195c3e89513ec30e52862d6562add
|
[
"Apache-2.0"
] | 2 |
2019-11-18T08:41:53.000Z
|
2020-09-11T08:53:18.000Z
| 21.294118 | 60 | 0.762431 | 1,000,988 |
package com.harmazing.framework.quartz.demo;
import org.springframework.stereotype.Service;
import com.harmazing.framework.quartz.IJob;
import com.harmazing.framework.quartz.IJobContext;
@Service
public class TestJob implements IJob {
@Override
public void runJob(IJobContext context) throws Exception {
System.out.println("test");
}
}
|
923ef985d51d591743225a27316f331e17d79a1e
| 2,136 |
java
|
Java
|
src/main/java/com/antoiovi/logging/OutputStandard.java
|
antoiovi/CalcolatoreTermodinamico
|
6734b0fa15deb66bc04dc29dcf01eab0ecda5af3
|
[
"MIT"
] | 2 |
2018-12-14T11:04:47.000Z
|
2018-12-14T11:04:56.000Z
|
src/main/java/com/antoiovi/logging/OutputStandard.java
|
antoiovi/CalcolatoreTermodinamico
|
6734b0fa15deb66bc04dc29dcf01eab0ecda5af3
|
[
"MIT"
] | null | null | null |
src/main/java/com/antoiovi/logging/OutputStandard.java
|
antoiovi/CalcolatoreTermodinamico
|
6734b0fa15deb66bc04dc29dcf01eab0ecda5af3
|
[
"MIT"
] | null | null | null | 13.185185 | 48 | 0.639981 | 1,000,989 |
package com.antoiovi.logging;
public class OutputStandard implements IOutput {
private boolean error;
private boolean warning;
private boolean info;
private boolean debug;
private boolean trace;
@Override
public void setLevel(Level level) {
switch (level){
case ERROR:
error=true;
warning=false;
info=false;
debug=false;
trace=false;
break;
case WARNING:
error=true;
warning=true;
info=false;
debug=false;
trace=false;
break;
case INFO:
error=true;
warning=true;
info=true;
debug=false;
trace=false;
break;
case DEBUG:
error=true;
warning=true;
info=true;
debug=true;
trace=false;
break;
case TRACE:
error=true;
warning=true;
info=true;
debug=true;
trace=true;
break;
default:
error=false;
warning=false;
info=false;
debug=false;
trace=false;
}
}
@Override
public void logError(Object msg) {
if(error)
{
System.out.println(msg);
}
}
@Override
public void logWarning(Object msg) {
if(warning)
{
System.out.println(msg);
}
}
@Override
public void logInfo(Object msg) {
if(info)
{
System.out.println(msg);
}
}
@Override
public void logDebug(Object msg) {
if(debug)
{
System.out.println(msg);
}
}
@Override
public void logTrace(Object msg) {
if(trace)
{
System.out.println(msg);
}
}
@Override
public void clear() {
}
@Override
public void setMessage(Object msg) {
}
@Override
public void appendMessage(Object msg) {
}
public boolean isError() {
return error;
}
public void setError(boolean error) {
this.error = error;
}
public boolean isWarning() {
return warning;
}
public void setWarning(boolean warning) {
this.warning = warning;
}
public boolean isInfo() {
return info;
}
public void setInfo(boolean info) {
this.info = info;
}
public boolean isDebug() {
return debug;
}
public void setDebug(boolean debug) {
this.debug = debug;
}
public boolean isTrace() {
return trace;
}
public void setTrace(boolean trace) {
this.trace = trace;
}
}
|
923efd6bdb4f2b9846fa0e1de6fd1c62e94e6d2f
| 1,564 |
java
|
Java
|
doma/src/test/java/org/seasar/doma/internal/util/ResourceUtilTest.java
|
seasarorg/doma
|
385b00bf0d098bf3e37855565c14933e325b2f83
|
[
"Apache-1.1"
] | 12 |
2015-01-19T02:43:05.000Z
|
2021-03-31T09:00:08.000Z
|
doma/src/test/java/org/seasar/doma/internal/util/ResourceUtilTest.java
|
seasarorg/doma
|
385b00bf0d098bf3e37855565c14933e325b2f83
|
[
"Apache-1.1"
] | 9 |
2015-07-21T05:18:18.000Z
|
2022-01-21T23:19:45.000Z
|
doma/src/test/java/org/seasar/doma/internal/util/ResourceUtilTest.java
|
seasarorg/doma
|
385b00bf0d098bf3e37855565c14933e325b2f83
|
[
"Apache-1.1"
] | 6 |
2015-07-21T03:35:03.000Z
|
2020-01-30T04:37:16.000Z
| 34 | 77 | 0.682864 | 1,000,990 |
/*
* Copyright 2004-2010 the Seasar Foundation and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.seasar.doma.internal.util;
import java.io.InputStream;
import junit.framework.TestCase;
/**
* @author taedium
*
*/
public class ResourceUtilTest extends TestCase {
public void testGetResourceAsStream() throws Exception {
String path = getClass().getName().replace(".", "/") + ".txt";
InputStream inputStream = ResourceUtil.getResourceAsStream(path);
assertNotNull(inputStream);
}
public void testGetResourceAsStream_nonexistentPath() throws Exception {
InputStream inputStream = ResourceUtil
.getResourceAsStream("nonexistentPath");
assertNull(inputStream);
}
public void testGetResourceAsString() throws Exception {
String path = getClass().getName().replace(".", "/") + ".txt";
String value = ResourceUtil.getResourceAsString(path);
assertEquals("aaa", value);
}
}
|
923efe23116ac76054148164826860d1407e59bb
| 1,903 |
java
|
Java
|
plugin-infra/go-plugin-access/test/com/thoughtworks/go/plugin/access/configrepo/JsonMessageHandler1_0Test.java
|
alexschwartz/gocd
|
834496abd7f6c8596d3e91fa508a8444aaa0c731
|
[
"Apache-2.0"
] | 1 |
2021-08-14T13:50:46.000Z
|
2021-08-14T13:50:46.000Z
|
plugin-infra/go-plugin-access/test/com/thoughtworks/go/plugin/access/configrepo/JsonMessageHandler1_0Test.java
|
denza/gocd
|
d87f6242bb52541cf20b01226c0a5fc994474a2e
|
[
"Apache-2.0"
] | null | null | null |
plugin-infra/go-plugin-access/test/com/thoughtworks/go/plugin/access/configrepo/JsonMessageHandler1_0Test.java
|
denza/gocd
|
d87f6242bb52541cf20b01226c0a5fc994474a2e
|
[
"Apache-2.0"
] | null | null | null | 31.716667 | 118 | 0.600105 | 1,000,991 |
package com.thoughtworks.go.plugin.access.configrepo;
import com.thoughtworks.go.plugin.access.configrepo.contract.CRParseResult;
import org.junit.Test;
import static com.thoughtworks.go.util.TestUtils.contains;
import static junit.framework.TestCase.assertFalse;
import static junit.framework.TestCase.assertTrue;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class JsonMessageHandler1_0Test {
private final JsonMessageHandler1_0 handler;
public JsonMessageHandler1_0Test()
{
handler = new JsonMessageHandler1_0();
}
@Test
public void shouldErrorWhenMissingTargetVersionInResponse()
{
String json = "{\n" +
" \"environments\" : [],\n" +
" \"pipelines\" : [],\n" +
" \"errors\" : []\n" +
"}";
CRParseResult result = handler.responseMessageForParseDirectory(json);
assertThat(result.getErrors().getErrorsAsText(),contains("missing 'target_version' field"));
}
@Test
public void shouldNotErrorWhenTargetVersionInResponse()
{
String json = "{\n" +
" \"target_version\" : 1,\n" +
" \"pipelines\" : [],\n" +
" \"errors\" : []\n" +
"}";
CRParseResult result = handler.responseMessageForParseDirectory(json);
assertFalse(result.hasErrors());
}
@Test
public void shouldAppendPluginErrorsToAllErrors()
{
String json = "{\n" +
" \"target_version\" : 1,\n" +
" \"pipelines\" : [],\n" +
" \"errors\" : [{\"location\" : \"somewhere\", \"message\" : \"failed to parse pipeline.json\"}]\n" +
"}";
CRParseResult result = handler.responseMessageForParseDirectory(json);
assertTrue(result.hasErrors());
}
}
|
923efeaf2ab3d180824833100a328e73696175e4
| 7,203 |
java
|
Java
|
JCudaVec/src/test/java/jcuda/vec/TestVecFloatMath2.java
|
jcuda/jcuda-vec
|
4f71d31fcaecdc7fce800e6509eb93d823d4d9d2
|
[
"MIT"
] | 4 |
2019-03-28T07:54:52.000Z
|
2021-11-06T23:35:52.000Z
|
JCudaVec/src/test/java/jcuda/vec/TestVecFloatMath2.java
|
jcuda/jcuda-vec
|
4f71d31fcaecdc7fce800e6509eb93d823d4d9d2
|
[
"MIT"
] | 1 |
2016-06-13T14:49:04.000Z
|
2016-06-13T14:49:04.000Z
|
JCudaVec/src/test/java/jcuda/vec/TestVecFloatMath2.java
|
jcuda/jcuda-vec
|
4f71d31fcaecdc7fce800e6509eb93d823d4d9d2
|
[
"MIT"
] | 2 |
2017-03-16T03:32:23.000Z
|
2022-01-29T17:13:50.000Z
| 28.583333 | 70 | 0.49646 | 1,000,992 |
/*
* JCudaVec - Vector operations for JCuda
* http://www.jcuda.org
*
* Copyright (c) 2013-2015 Marco Hutter - http://www.jcuda.org
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package jcuda.vec;
import org.junit.Test;
import jcuda.driver.CUdeviceptr;
/**
* Tests for the 2-argument vector math methods
*/
public class TestVecFloatMath2 extends AbstractTestVecFloat
{
@Test
public void testCopysign()
{
runTest(new AbstractCoreFloat("copysign")
{
@Override
protected float computeHostElement(
float x, float y, float scalar)
{
return y<0?-Math.abs(x):Math.abs(x);
}
@Override
protected void computeDevice(long n, CUdeviceptr result,
CUdeviceptr x, CUdeviceptr y, float scalar)
{
VecFloat.copysign(n, result, x, y);
}
});
}
@Test
public void testFdim()
{
runTest(new AbstractCoreFloat("fdim")
{
@Override
protected float computeHostElement(
float x, float y, float scalar)
{
return x-y<0?0:x-y;
}
@Override
protected void computeDevice(long n, CUdeviceptr result,
CUdeviceptr x, CUdeviceptr y, float scalar)
{
VecFloat.fdim(n, result, x, y);
}
});
}
@Test
public void testFdivide()
{
runTest(new AbstractCoreFloat("fdivide")
{
@Override
protected float computeHostElement(
float x, float y, float scalar)
{
return x/y;
}
@Override
protected void computeDevice(long n, CUdeviceptr result,
CUdeviceptr x, CUdeviceptr y, float scalar)
{
VecFloat.fdivide(n, result, x, y);
}
});
}
@Test
public void testFmax()
{
runTest(new AbstractCoreFloat("fmax")
{
@Override
protected float computeHostElement(
float x, float y, float scalar)
{
return Math.max(x, y);
}
@Override
protected void computeDevice(long n, CUdeviceptr result,
CUdeviceptr x, CUdeviceptr y, float scalar)
{
VecFloat.fmax(n, result, x, y);
}
});
}
@Test
public void testFmin()
{
runTest(new AbstractCoreFloat("fmin")
{
@Override
protected float computeHostElement(
float x, float y, float scalar)
{
return Math.min(x, y);
}
@Override
protected void computeDevice(long n, CUdeviceptr result,
CUdeviceptr x, CUdeviceptr y, float scalar)
{
VecFloat.fmin(n, result, x, y);
}
});
}
@Test
public void testFmod()
{
runTest(new AbstractCoreFloat("fmod")
{
@Override
protected float computeHostElement(
float x, float y, float scalar)
{
return x % y;
}
@Override
protected void computeDevice(long n, CUdeviceptr result,
CUdeviceptr x, CUdeviceptr y, float scalar)
{
VecFloat.fmod(n, result, x, y);
}
});
}
@Test
public void testHypot()
{
runTest(new AbstractCoreFloat("hypot")
{
@Override
protected float computeHostElement(
float x, float y, float scalar)
{
return (float)Math.hypot(x, y);
}
@Override
protected void computeDevice(long n, CUdeviceptr result,
CUdeviceptr x, CUdeviceptr y, float scalar)
{
VecFloat.hypot(n, result, x, y);
}
});
}
@Test
public void testNextafter()
{
runTest(new AbstractCoreFloat("nextafter")
{
@Override
protected float computeHostElement(
float x, float y, float scalar)
{
return Math.nextAfter(x, y);
}
@Override
protected void computeDevice(long n, CUdeviceptr result,
CUdeviceptr x, CUdeviceptr y, float scalar)
{
VecFloat.nextafter(n, result, x, y);
}
});
}
@Test
public void testPow()
{
runTest(new AbstractCoreFloat("pow")
{
@Override
protected float computeHostElement(
float x, float y, float scalar)
{
return (float)Math.pow(x, y);
}
@Override
protected void computeDevice(long n, CUdeviceptr result,
CUdeviceptr x, CUdeviceptr y, float scalar)
{
VecFloat.pow(n, result, x, y);
}
});
}
@Test
public void testRemainder()
{
runTest(new AbstractCoreFloat("remainder")
{
@Override
protected float computeHostElement(
float x, float y, float scalar)
{
return (float)Math.IEEEremainder(x, y);
}
@Override
protected void computeDevice(long n, CUdeviceptr result,
CUdeviceptr x, CUdeviceptr y, float scalar)
{
VecFloat.remainder(n, result, x, y);
}
});
}
}
|
923efef44adf5366541abb9814dce5fdb6037572
| 2,416 |
java
|
Java
|
src/main/java/uk/me/richardcook/sinatra/generator/service/SessionSongService.java
|
Cook879/Sessionography-Book-Creator
|
f25a6e5ac146e1cfe4c435e086f2610b28582558
|
[
"CC-BY-4.0"
] | null | null | null |
src/main/java/uk/me/richardcook/sinatra/generator/service/SessionSongService.java
|
Cook879/Sessionography-Book-Creator
|
f25a6e5ac146e1cfe4c435e086f2610b28582558
|
[
"CC-BY-4.0"
] | null | null | null |
src/main/java/uk/me/richardcook/sinatra/generator/service/SessionSongService.java
|
Cook879/Sessionography-Book-Creator
|
f25a6e5ac146e1cfe4c435e086f2610b28582558
|
[
"CC-BY-4.0"
] | null | null | null | 31.789474 | 121 | 0.748758 | 1,000,993 |
package uk.me.richardcook.sinatra.generator.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import uk.me.richardcook.sinatra.generator.dao.SessionSongDao;
import uk.me.richardcook.sinatra.generator.model.SessionSong;
import java.util.List;
@Service
public class SessionSongService {
@Autowired
private SessionSongDao sessionSongDao;
@Autowired
private SessionService sessionService;
public List<SessionSong> findAll() {
return sessionSongDao.findAll();
}
public SessionSong find( int id ) {
return sessionSongDao.find( id );
}
public void save( SessionSong sessionSong ) {
sessionSongDao.save( sessionSong );
}
public void update( SessionSong sessionSong ) {
sessionSongDao.update( sessionSong );
}
public ResponseEntity validate( SessionSong sessionSong ) {
// The following can be null
if ( sessionSong.getMaster() != null && sessionSong.getMaster().equals( "" ) )
sessionSong.setMaster( null );
if ( sessionSong.getNotes() != null && sessionSong.getNotes().equals( "" ) )
sessionSong.setNotes( null );
// SessionView can't be null
if ( sessionSong.getSession() == null )
return new ResponseEntity( "You must provide a session", HttpStatus.BAD_REQUEST );
// Position can't be null
if ( sessionSong.getPosition() == null )
return new ResponseEntity( "You must provide a position", HttpStatus.BAD_REQUEST );
// SessionView must be a legit session id
if ( sessionService.find( sessionSong.getSession() ) == null )
return new ResponseEntity( "The session you provided is not valid", HttpStatus.BAD_REQUEST );
// SessionView and position combo must be unique
// TODO check this
SessionSong sessionSong1 = sessionSongDao.findBySessionPosition( sessionSong.getSession(), sessionSong.getPosition() );
if ( sessionSong1 != null && sessionSong.getId() != sessionSong1.getId() )
return new ResponseEntity( "The combination of position and session must be unique", HttpStatus.BAD_REQUEST );
return null;
}
public List<SessionSong> findForSession( int id ) {
return sessionSongDao.findForSession( id );
}
public List<Integer> getIdsForSession( int id ) {
return sessionSongDao.getIdsForSession( id );
}
public void delete( int id ) {
sessionSongDao.delete( id );
}
}
|
923eff01e92e7790c6c3eb71aeb336c711ed0e90
| 9,970 |
java
|
Java
|
kaypher-common/src/test/java/com/treutec/kaypher/schema/ksql/SqlTypeWalkerTest.java
|
uurl/kaypher
|
fc80931ab622de3d8642647949e488d8b265fdc1
|
[
"Apache-2.0"
] | 3 |
2019-08-05T14:04:51.000Z
|
2019-11-11T09:36:39.000Z
|
kaypher-common/src/test/java/com/treutec/kaypher/schema/ksql/SqlTypeWalkerTest.java
|
uurl/kaypher
|
fc80931ab622de3d8642647949e488d8b265fdc1
|
[
"Apache-2.0"
] | null | null | null |
kaypher-common/src/test/java/com/treutec/kaypher/schema/ksql/SqlTypeWalkerTest.java
|
uurl/kaypher
|
fc80931ab622de3d8642647949e488d8b265fdc1
|
[
"Apache-2.0"
] | 1 |
2022-01-21T04:19:31.000Z
|
2022-01-21T04:19:31.000Z
| 27.771588 | 79 | 0.672116 | 1,000,994 |
/*
* Copyright 2019 Treu Techologies
*
* See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.treutec.kaypher.schema.kaypher;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.same;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Streams;
import com.treutec.kaypher.schema.kaypher.SqlTypeWalker.Visitor;
import com.treutec.kaypher.schema.kaypher.types.Field;
import com.treutec.kaypher.schema.kaypher.types.SqlArray;
import com.treutec.kaypher.schema.kaypher.types.SqlDecimal;
import com.treutec.kaypher.schema.kaypher.types.SqlMap;
import com.treutec.kaypher.schema.kaypher.types.SqlPrimitiveType;
import com.treutec.kaypher.schema.kaypher.types.SqlStruct;
import com.treutec.kaypher.schema.kaypher.types.SqlType;
import com.treutec.kaypher.schema.kaypher.types.SqlTypes;
import java.util.stream.Stream;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class SqlTypeWalkerTest {
@Rule
public final ExpectedException expectedException = ExpectedException.none();
@Mock
private SqlTypeWalker.Visitor<String, Integer> visitor;
@Test
public void shouldVisitBoolean() {
// Given:
final SqlPrimitiveType type = SqlTypes.BOOLEAN;
when(visitor.visitBoolean(any())).thenReturn("Expected");
// When:
final String result = SqlTypeWalker.visit(type, visitor);
// Then:
verify(visitor).visitBoolean(same(type));
assertThat(result, is("Expected"));
}
@Test
public void shouldVisitInt() {
// Given:
final SqlPrimitiveType type = SqlTypes.INTEGER;
when(visitor.visitInt(any())).thenReturn("Expected");
// When:
final String result = SqlTypeWalker.visit(type, visitor);
// Then:
verify(visitor).visitInt(same(type));
assertThat(result, is("Expected"));
}
@Test
public void shouldVisitBigInt() {
// Given:
final SqlPrimitiveType type = SqlTypes.BIGINT;
when(visitor.visitBigInt(any())).thenReturn("Expected");
// When:
final String result = SqlTypeWalker.visit(type, visitor);
// Then:
verify(visitor).visitBigInt(same(type));
assertThat(result, is("Expected"));
}
@Test
public void shouldVisitDouble() {
// Given:
final SqlPrimitiveType type = SqlTypes.DOUBLE;
when(visitor.visitDouble(any())).thenReturn("Expected");
// When:
final String result = SqlTypeWalker.visit(type, visitor);
// Then:
verify(visitor).visitDouble(same(type));
assertThat(result, is("Expected"));
}
@Test
public void shouldVisitString() {
// Given:
final SqlPrimitiveType type = SqlTypes.STRING;
when(visitor.visitString(any())).thenReturn("Expected");
// When:
final String result = SqlTypeWalker.visit(type, visitor);
// Then:
verify(visitor).visitString(same(type));
assertThat(result, is("Expected"));
}
@Test
public void shouldVisitDecimal() {
// Given:
final SqlDecimal type = SqlTypes.decimal(10, 2);
when(visitor.visitDecimal(any())).thenReturn("Expected");
// When:
final String result = SqlTypeWalker.visit(type, visitor);
// Then:
verify(visitor).visitDecimal(same(type));
assertThat(result, is("Expected"));
}
@Test
public void shouldVisitArray() {
// Given:
final SqlArray type = SqlTypes.array(SqlTypes.BIGINT);
when(visitor.visitBigInt(any())).thenReturn("Expected-element");
when(visitor.visitArray(any(), any())).thenReturn("Expected");
// When:
final String result = SqlTypeWalker.visit(type, visitor);
// Then:
verify(visitor).visitBigInt(same(SqlTypes.BIGINT));
verify(visitor).visitArray(same(type), eq("Expected-element"));
assertThat(result, is("Expected"));
}
@Test
public void shouldVisitMap() {
// Given:
final SqlMap type = SqlTypes.map(SqlTypes.INTEGER);
when(visitor.visitInt(any())).thenReturn("Expected-value");
when(visitor.visitMap(any(), any())).thenReturn("Expected");
// When:
final String result = SqlTypeWalker.visit(type, visitor);
// Then:
verify(visitor).visitInt(same(SqlTypes.INTEGER));
verify(visitor).visitMap(same(type), eq("Expected-value"));
assertThat(result, is("Expected"));
}
@Test
public void shouldVisitStruct() {
// Given:
final SqlStruct type = SqlTypes
.struct()
.field("0", SqlTypes.DOUBLE)
.field("1", SqlTypes.INTEGER)
.build();
when(visitor.visitDouble(any())).thenReturn("0");
when(visitor.visitInt(any())).thenReturn("1");
when(visitor.visitField(any(), any())).thenAnswer(inv -> {
final int fieldName = Integer.parseInt(inv.<Field>getArgument(0).name());
final int expectedArg = Integer.parseInt(inv.getArgument(1));
assertThat(fieldName, is(expectedArg));
return fieldName;
});
when(visitor.visitStruct(any(), any())).thenReturn("Expected");
// When:
final String result = SqlTypeWalker.visit(type, visitor);
// Then:
verify(visitor).visitDouble(same(SqlTypes.DOUBLE));
verify(visitor).visitInt(same(SqlTypes.INTEGER));
verify(visitor).visitStruct(same(type), eq(ImmutableList.of(0, 1)));
assertThat(result, is("Expected"));
}
@Test
public void shouldVisitPrimitives() {
// Given:
visitor = new Visitor<String, Integer>() {
@Override
public String visitPrimitive(final SqlPrimitiveType type) {
return "Expected";
}
};
primitiveTypes().forEach(type -> {
// When:
final String result = SqlTypeWalker.visit(type, visitor);
// Then:
assertThat(result, is("Expected"));
});
}
@Test
public void shouldVisitAll() {
// Given:
visitor = new Visitor<String, Integer>() {
@Override
public String visitType(final SqlType type) {
return "Expected";
}
};
allTypes().forEach(type -> {
// When:
final String result = SqlTypeWalker.visit(type, visitor);
// Then:
assertThat(result, is("Expected"));
});
}
@Test
public void shouldThrowByDefaultFromNonStructured() {
// Given:
visitor = new Visitor<String, Integer>() {
};
nonStructuredTypes().forEach(type -> {
try {
// When:
SqlTypeWalker.visit(type, visitor);
fail();
} catch (final UnsupportedOperationException e) {
// Then:
assertThat(e.getMessage(), is("Unsupported sql type: " + type));
}
});
}
@Test
public void shouldThrowByDefaultFromStructured() {
// Given:
visitor = new Visitor<String, Integer>() {
@Override
public String visitPrimitive(final SqlPrimitiveType type) {
return null;
}
};
structuredTypes().forEach(type -> {
try {
// When:
SqlTypeWalker.visit(type, visitor);
fail();
} catch (final UnsupportedOperationException e) {
// Then:
assertThat(e.getMessage(), is("Unsupported sql type: " + type));
}
});
}
@Test
public void shouldThrowOnUnknownType() {
// Given:
final SqlBaseType unknownType = mock(SqlBaseType.class, "bob");
final SqlType type = mock(SqlType.class);
when(type.baseType()).thenReturn(unknownType);
// Then:
expectedException.expect(UnsupportedOperationException.class);
expectedException.expectMessage("Unsupported schema type: bob");
// When:
SqlTypeWalker.visit(type, visitor);
}
@Test
public void shouldStartWalkingFromField() {
// Given:
final SqlPrimitiveType type = SqlTypes.BOOLEAN;
final Field field = Field.of("name", type);
when(visitor.visitBoolean(any())).thenReturn("Expected");
when(visitor.visitField(any(), any())).thenReturn(22);
// When:
final Integer result = SqlTypeWalker.visit(field, visitor);
// Then:
verify(visitor).visitBoolean(same(type));
verify(visitor).visitField(same(field), eq("Expected"));
assertThat(result, is(22));
}
public static Stream<SqlType> primitiveTypes() {
return Stream.of(
SqlTypes.BOOLEAN,
SqlTypes.INTEGER,
SqlTypes.BIGINT,
SqlTypes.DOUBLE,
SqlTypes.STRING
);
}
@SuppressWarnings("UnstableApiUsage")
private static Stream<SqlType> nonStructuredTypes() {
return Streams.concat(
primitiveTypes(),
Stream.of(SqlTypes.decimal(10, 2))
);
}
private static Stream<SqlType> structuredTypes() {
return Stream.of(
SqlTypes.array(SqlTypes.BIGINT),
SqlTypes.map(SqlTypes.STRING),
SqlTypes
.struct()
.field("f0", SqlTypes.BIGINT)
.build()
);
}
@SuppressWarnings("UnstableApiUsage")
private static Stream<SqlType> allTypes() {
return Streams.concat(
nonStructuredTypes(),
structuredTypes()
);
}
}
|
923eff9615547e85adeb2c3983fb025b56d56497
| 3,370 |
java
|
Java
|
cluster/midonet-cluster/src/main/java/org/midonet/cluster/rest_api/neutron/resources/PortResource.java
|
duarten/midonet
|
c7a5aa352a8038bdc6a463c68abc47bb411a1e7c
|
[
"Apache-2.0"
] | 221 |
2015-01-04T17:49:57.000Z
|
2021-12-23T16:15:35.000Z
|
cluster/midonet-cluster/src/main/java/org/midonet/cluster/rest_api/neutron/resources/PortResource.java
|
duarten/midonet
|
c7a5aa352a8038bdc6a463c68abc47bb411a1e7c
|
[
"Apache-2.0"
] | 8 |
2018-05-24T13:36:03.000Z
|
2021-02-19T16:01:43.000Z
|
midonet-cluster/src/main/java/org/midonet/cluster/rest_api/neutron/resources/PortResource.java
|
obino/midonet
|
10cd954bec1290cf0c70aecaa1e13c91f1b008a6
|
[
"Apache-2.0"
] | 95 |
2015-01-07T02:06:23.000Z
|
2022-02-23T22:23:55.000Z
| 30.917431 | 89 | 0.703858 | 1,000,995 |
/*
* Copyright 2015 Midokura SARL
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.midonet.cluster.rest_api.neutron.resources;
import java.net.URI;
import java.util.List;
import java.util.UUID;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import com.google.inject.Inject;
import org.midonet.cluster.rest_api.NotFoundHttpException;
import org.midonet.cluster.rest_api.neutron.NeutronMediaType;
import org.midonet.cluster.rest_api.neutron.NeutronUriBuilder;
import org.midonet.cluster.rest_api.neutron.models.Port;
import org.midonet.cluster.services.rest_api.neutron.plugin.NetworkApi;
import org.midonet.cluster.services.rest_api.neutron.plugin.NeutronZoomPlugin;
import static org.midonet.cluster.rest_api.validation.MessageProperty.RESOURCE_NOT_FOUND;
import static org.midonet.cluster.rest_api.validation.MessageProperty.getMessage;
public class PortResource {
private final NetworkApi api;
private final URI baseUri;
@Inject
public PortResource(UriInfo uriInfo, NeutronZoomPlugin api) {
this.api = api;
this.baseUri = uriInfo.getBaseUri();
}
@POST
@Consumes(NeutronMediaType.PORT_JSON_V1)
@Produces(NeutronMediaType.PORT_JSON_V1)
public Response create(Port port) {
Port p = api.createPort(port);
return Response.created(NeutronUriBuilder.getPort(baseUri, p.id))
.entity(p).build();
}
@POST
@Consumes(NeutronMediaType.PORTS_JSON_V1)
@Produces(NeutronMediaType.PORTS_JSON_V1)
public Response createBulk(List<Port> ports) {
List<Port> outPorts = api.createPortBulk(ports);
return Response.created(NeutronUriBuilder.getPorts(baseUri))
.entity(outPorts).build();
}
@DELETE
@Path("{id}")
public void delete(@PathParam("id") UUID id) {
api.deletePort(id);
}
@GET
@Path("{id}")
@Produces(NeutronMediaType.PORT_JSON_V1)
public Port get(@PathParam("id") UUID id) {
Port p = api.getPort(id);
if (p == null) {
throw new NotFoundHttpException(getMessage(RESOURCE_NOT_FOUND));
}
return p;
}
@GET
@Produces(NeutronMediaType.PORTS_JSON_V1)
public List<Port> list() {
return api.getPorts();
}
@PUT
@Path("{id}")
@Consumes(NeutronMediaType.PORT_JSON_V1)
@Produces(NeutronMediaType.PORT_JSON_V1)
public Response update(@PathParam("id") UUID id, Port port) {
Port p = api.updatePort(id, port);
return Response.ok(NeutronUriBuilder.getPort(baseUri, p.id))
.entity(p).build();
}
}
|
923f02425443a99c21c48df8cef4d5ee3ff51de2
| 2,081 |
java
|
Java
|
src/java/com/algocasts/sort/BubbleSort.java
|
ArchyXiao/leetcode-terminator
|
2a6751627dfc99c53d4c9ab098ba03f7aa96d397
|
[
"Apache-2.0"
] | 3 |
2020-01-13T03:44:34.000Z
|
2021-12-28T01:27:21.000Z
|
src/java/com/algocasts/sort/BubbleSort.java
|
ArchyXiao/leetcode-terminator
|
2a6751627dfc99c53d4c9ab098ba03f7aa96d397
|
[
"Apache-2.0"
] | null | null | null |
src/java/com/algocasts/sort/BubbleSort.java
|
ArchyXiao/leetcode-terminator
|
2a6751627dfc99c53d4c9ab098ba03f7aa96d397
|
[
"Apache-2.0"
] | null | null | null | 24.197674 | 65 | 0.425757 | 1,000,996 |
package java.com.algocasts.sort;
/**
* @Description:
* 冒泡排序的原理是,每一次遍历数组,都去不断地比较相邻的两个元素,如果它们的顺序不对,就交换这两个元素,比如把较大的换到后面。
* 第一次遍历可以把最大的元素确定下来,放在最后的位置。第二次遍历可以确定第二大的元素,依次类推。
* 这样遍历 N 次后,整个数组就变成递增有序。
*
* T: O(n^2)
* S: O(1)
*
* @Auther: Archy
* @Date: 2019/9/7 14:25
*/
public class BubbleSort {
public void swap(int[] array, int i, int j) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
public void bubbleSort(int[] array) {
if (array == null || array.length == 0) {
return;
}
int n = array.length;
for (int end = n - 1; end > 0; end--) {
for (int i = 0; i < end; i++) {
if (array[i] > array[i + 1]) {
swap(array, i, i + 1);
}
}
}
}
/**
* @Description: 利用一个标志位,记录上一轮排序是否存在交换元素操作;若无,则提前返回
* @param array
* @return: void
*/
public void bubbleSortEarlyReturn(int[] array) {
if (array == null || array.length == 0) {
return;
}
int n = array.length;
boolean swapped = false;
for (int end = n - 1; end > 0; end--) {
swapped = false;
for (int i = 0; i < end; i++) {
if (array[i] > array[i + 1]) {
swap(array, i, i + 1);
swapped = true;
}
}
}
if (!swapped) {
return;
}
}
/**
* @Description: 保存上一轮最后交换元素的位置,将此位置作为下一轮循环的终点
* @param array
* @return: void
*/
public void bubbleSortSkip(int[] array) {
if (array == null || array.length == 0) {
return;
}
int n = array.length;
int newEnd;
for (int end = n - 1; end > 0; end--) {
newEnd = 0;
for (int i = 0; i < end; i++) {
if (array[i] > array[i + 1]) {
swap(array, i, i + 1);
newEnd = i;
}
}
end = newEnd;
}
}
}
|
923f0303a80ceb5c01e631e60bae3d59fc9d8adc
| 263 |
java
|
Java
|
java/de/ofahrt/catfish/model/MalformedResponseException.java
|
benjaminp/catfish
|
cdebaeb890561b3a75ed7c19ce2b6dd4cd9f6096
|
[
"Apache-2.0"
] | null | null | null |
java/de/ofahrt/catfish/model/MalformedResponseException.java
|
benjaminp/catfish
|
cdebaeb890561b3a75ed7c19ce2b6dd4cd9f6096
|
[
"Apache-2.0"
] | null | null | null |
java/de/ofahrt/catfish/model/MalformedResponseException.java
|
benjaminp/catfish
|
cdebaeb890561b3a75ed7c19ce2b6dd4cd9f6096
|
[
"Apache-2.0"
] | 2 |
2021-07-27T19:58:05.000Z
|
2022-02-16T14:56:18.000Z
| 21.916667 | 67 | 0.787072 | 1,000,997 |
package de.ofahrt.catfish.model;
import java.io.IOException;
public final class MalformedResponseException extends IOException {
private static final long serialVersionUID = 1L;
public MalformedResponseException(String message) {
super(message);
}
}
|
923f033ffd23900cfea0c53534c78ddb1a76003c
| 4,231 |
java
|
Java
|
data-structure/src/main/java/com/qinfengsa/structure/leetcode/WordDictionary.java
|
qinfengsa/base-knowledge
|
fecf83b01cf47b92d03ba382b87b6410b3157b46
|
[
"MIT"
] | null | null | null |
data-structure/src/main/java/com/qinfengsa/structure/leetcode/WordDictionary.java
|
qinfengsa/base-knowledge
|
fecf83b01cf47b92d03ba382b87b6410b3157b46
|
[
"MIT"
] | 1 |
2020-10-31T15:25:18.000Z
|
2020-10-31T15:25:18.000Z
|
data-structure/src/main/java/com/qinfengsa/structure/leetcode/WordDictionary.java
|
qinfengsa/base-knowledge
|
fecf83b01cf47b92d03ba382b87b6410b3157b46
|
[
"MIT"
] | null | null | null | 26.949045 | 128 | 0.497991 | 1,000,998 |
package com.qinfengsa.structure.leetcode;
import lombok.extern.slf4j.Slf4j;
import java.util.Objects;
/**
* 211. 添加与搜索单词 - 数据结构设计
* 设计一个支持以下两种操作的数据结构:
*
* void addWord(word)
* bool search(word)
* search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。
*
* 示例:
*
* addWord("bad")
* addWord("dad")
* addWord("mad")
* search("pad") -> false
* search("bad") -> true
* search(".ad") -> true
* search("b..") -> true
* 说明:
*
* 你可以假设所有单词都是由小写字母 a-z 组成的。
* @author qinfengsa
* @date 2020/05/15 00:23
*/
@Slf4j
public class WordDictionary {
private static final int SIZE = 26;
// 根节点
private WordNode root;
/** Initialize your data structure here. */
public WordDictionary() {
root = new WordNode();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
if (word.length() == 0) {
return;
}
WordNode node = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
WordNode child = node.children[c - 'a'];
if (Objects.isNull(child)) {
child = new WordNode();
node.children[c - 'a'] = child;
}
child.num++;
if (i == word.length() - 1) {
child.isEnd = true;
}
node = child;
}
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
public boolean search(String word) {
if (word.length() == 0) {
return false;
}
WordNode node = root;
/*for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (c == '*') {
}
WordNode child = node.children[c - 'a'];
if (Objects.isNull(child)) {
child = new WordNode();
child.val = word;
} else {
child.num++;
}
if (i == word.length() - 1) {
child.isEnd = true;
}
node = child;
}*/
return search(word,0,node);
}
private boolean search(String word,int start,WordNode node) {
if (start == word.length()) {
return node.isEnd;
}
char c = word.charAt(start);
if (c == '.') {
for (int i = 0; i < SIZE; i++) {
if (Objects.isNull(node.children[i])) {
continue;
}
if (search(word,start + 1,node.children[i])) {
return true;
}
}
} else if (Objects.nonNull(node.children[c - 'a']) ) {
return search(word,start + 1,node.children[c - 'a']);
}
return false;
}
/**
* 节点
*/
static class WordNode {
// 有多少单词通过这个节点,即由根至该节点组成的字符串模式出现的次数
private int num;
// 所有的儿子节点
private WordNode[] children;
// 是不是最后一个节点
private boolean isEnd;
WordNode() {
num = 0;
children = new WordNode[SIZE];
isEnd = false;
}
}
public static void main(String[] args) {
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("at");
wordDictionary.addWord("and");
wordDictionary.addWord("an");
wordDictionary.addWord("add");
boolean val4 = wordDictionary.search("a");
log.debug("val4:{} ",val4);
boolean val5 = wordDictionary.search(".at");
log.debug("val5:{} ",val5);
wordDictionary.addWord("bat");
boolean val7 = wordDictionary.search(".at");
log.debug("val7:{} ",val7);
boolean val8 = wordDictionary.search("an.");
log.debug("val8:{} ",val8);
boolean val9 = wordDictionary.search("a.d.");
log.debug("val9:{} ",val9);
boolean val10 = wordDictionary.search("b.");
log.debug("val10:{} ",val10);
boolean val11 = wordDictionary.search("a.d");
log.debug("val11:{} ",val11);
boolean val12 = wordDictionary.search(".");
log.debug("val12:{} ",val12);
}
}
|
923f047ebdaa1689af7c8e1d16848a2b758a7232
| 396 |
java
|
Java
|
references/bcb_chosen_clones/selected#2590672#180#187.java
|
cragkhit/elasticsearch
|
05567b30c5bde08badcac1bf421454e5d995eb91
|
[
"Apache-2.0"
] | 23 |
2018-10-03T15:02:53.000Z
|
2021-09-16T11:07:36.000Z
|
references/bcb_chosen_clones/selected#2590672#180#187.java
|
cragkhit/elasticsearch
|
05567b30c5bde08badcac1bf421454e5d995eb91
|
[
"Apache-2.0"
] | 18 |
2019-02-10T04:52:54.000Z
|
2022-01-25T02:14:40.000Z
|
references/bcb_chosen_clones/selected#2590672#180#187.java
|
cragkhit/Siamese
|
05567b30c5bde08badcac1bf421454e5d995eb91
|
[
"Apache-2.0"
] | 19 |
2018-11-16T13:39:05.000Z
|
2021-09-05T23:59:30.000Z
| 44 | 112 | 0.517677 | 1,000,999 |
private static int binarySearch(int[] a, int start, int len, int key) {
int high = start + len, low = start - 1, guess;
while (high - low > 1) {
guess = (high + low) / 2;
if (a[guess] < key) low = guess; else high = guess;
}
if (high == start + len) return ~(start + len); else if (a[high] == key) return high; else return ~high;
}
|
923f04eb9f9ad752d1ce676746df8f635fe13083
| 4,357 |
java
|
Java
|
fr.esir.lsi.langage/src/exploitation/Animals.java
|
HamedKaramoko/farmingdsl
|
8f55d208f9749f703771c50de9aef6dc4f50d8e0
|
[
"MIT"
] | null | null | null |
fr.esir.lsi.langage/src/exploitation/Animals.java
|
HamedKaramoko/farmingdsl
|
8f55d208f9749f703771c50de9aef6dc4f50d8e0
|
[
"MIT"
] | null | null | null |
fr.esir.lsi.langage/src/exploitation/Animals.java
|
HamedKaramoko/farmingdsl
|
8f55d208f9749f703771c50de9aef6dc4f50d8e0
|
[
"MIT"
] | null | null | null | 20.84689 | 102 | 0.575855 | 1,001,000 |
/**
*/
package exploitation;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Animals</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see exploitation.ExploitationPackage#getAnimals()
* @model
* @generated
*/
public enum Animals implements Enumerator {
/**
* The '<em><b>OVIN</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #OVIN_VALUE
* @generated
* @ordered
*/
OVIN(0, "OVIN", "ovin"),
/**
* The '<em><b>BOVIN</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #BOVIN_VALUE
* @generated
* @ordered
*/
BOVIN(1, "BOVIN", "Bovin");
/**
* The '<em><b>OVIN</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>Ovin</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #OVIN
* @model literal="ovin"
* @generated
* @ordered
*/
public static final int OVIN_VALUE = 0;
/**
* The '<em><b>BOVIN</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>Bovin</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #BOVIN
* @model literal="Bovin"
* @generated
* @ordered
*/
public static final int BOVIN_VALUE = 1;
/**
* An array of all the '<em><b>Animals</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final Animals[] VALUES_ARRAY =
new Animals[] {
OVIN,
BOVIN,
};
/**
* A public read-only list of all the '<em><b>Animals</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<Animals> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Animals</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static Animals get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
Animals result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Animals</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static Animals getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
Animals result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Animals</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static Animals get(int value) {
switch (value) {
case OVIN_VALUE: return OVIN;
case BOVIN_VALUE: return BOVIN;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private Animals(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //Animals
|
923f07928c969d404fc138865fa747aa7cd71783
| 331 |
java
|
Java
|
src/gef/tutorial/step/model/ContentsModel.java
|
LauZyHou/GEF-Tutorial
|
59a4a2628deaeb4ef98908832af0d8f57506ac2a
|
[
"MIT"
] | 1 |
2022-01-21T10:05:41.000Z
|
2022-01-21T10:05:41.000Z
|
src/gef/tutorial/step/model/ContentsModel.java
|
LauZyHou/GEF-Tutorial
|
59a4a2628deaeb4ef98908832af0d8f57506ac2a
|
[
"MIT"
] | null | null | null |
src/gef/tutorial/step/model/ContentsModel.java
|
LauZyHou/GEF-Tutorial
|
59a4a2628deaeb4ef98908832af0d8f57506ac2a
|
[
"MIT"
] | null | null | null | 15.761905 | 41 | 0.719033 | 1,001,001 |
package gef.tutorial.step.model;
import java.util.ArrayList;
import java.util.List;
//图形集模型ContentsModel
public class ContentsModel {
// 子模型列表
private List children = new ArrayList();
// 添加子模型
public void addChild(Object obj) {
children.add(obj);
}
// 获得子模型
public List<Object> getChildren() {
return children;
}
}
|
923f07cdfa1a1d13044284d4121ff4a0ead7e6d3
| 377 |
java
|
Java
|
common/src/main/java/org/endeavourhealth/recordviewer/common/models/ChartResult.java
|
endeavourhealth-discovery/RecordViewer
|
eccf61904ee25494d93e50681f94d90a7c34ff70
|
[
"Apache-2.0"
] | null | null | null |
common/src/main/java/org/endeavourhealth/recordviewer/common/models/ChartResult.java
|
endeavourhealth-discovery/RecordViewer
|
eccf61904ee25494d93e50681f94d90a7c34ff70
|
[
"Apache-2.0"
] | 6 |
2021-09-02T03:28:37.000Z
|
2022-03-02T06:35:37.000Z
|
common/src/main/java/org/endeavourhealth/recordviewer/common/models/ChartResult.java
|
endeavourhealth-discovery/RecordViewer
|
eccf61904ee25494d93e50681f94d90a7c34ff70
|
[
"Apache-2.0"
] | 1 |
2021-01-22T17:11:43.000Z
|
2021-01-22T17:11:43.000Z
| 20.944444 | 56 | 0.679045 | 1,001,002 |
package org.endeavourhealth.recordviewer.common.models;
import java.util.ArrayList;
import java.util.List;
public class ChartResult {
private List<Chart> results = new ArrayList<>();
public List<Chart> getResults() {
return results;
}
public ChartResult setResults(List<Chart> results) {
this.results = results;
return this;
}
}
|
923f08860093942769daa2436bd93a251afd19cc
| 3,998 |
java
|
Java
|
jms/jms-1/src/main/java/jms/App.java
|
SevaSafris/sa-apps
|
0f10b5dcdd0d1f4354e76eb303a5e12d2002c779
|
[
"Apache-2.0"
] | null | null | null |
jms/jms-1/src/main/java/jms/App.java
|
SevaSafris/sa-apps
|
0f10b5dcdd0d1f4354e76eb303a5e12d2002c779
|
[
"Apache-2.0"
] | null | null | null |
jms/jms-1/src/main/java/jms/App.java
|
SevaSafris/sa-apps
|
0f10b5dcdd0d1f4354e76eb303a5e12d2002c779
|
[
"Apache-2.0"
] | null | null | null | 31.234375 | 95 | 0.672336 | 1,001,003 |
package jms;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
import util.Util;
public class App {
public static void main(String[] args) throws Exception {
final ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
"vm://localhost?broker.persistent=false");
final Connection connection = connectionFactory.createConnection();
connection.start();
jms(connection);
Util.checkSpan("java-jms", 4);
connection.close();
}
private static void jms(Connection connection) {
thread(new HelloWorldProducer(connection), false);
thread(new HelloWorldProducer(connection), false);
thread(new HelloWorldConsumer(connection), false);
thread(new HelloWorldConsumer(connection), false);
}
public static class HelloWorldProducer implements Runnable {
private final Connection connection;
public HelloWorldProducer(Connection connection) {
this.connection = connection;
}
public void run() {
try {
// Create a Session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
System.out.println("Session: " + session);
// Create the destination (Topic or Queue)
Destination destination = session.createQueue("TEST.FOO");
// Create a MessageProducer from the Session to the Topic or Queue
MessageProducer producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
System.out.println("PRODUCER: " + producer);
// Create a messages
String text =
"Hello world! From: " + Thread.currentThread().getName() + " : " + this.hashCode();
TextMessage message = session.createTextMessage(text);
// Tell the producer to send the message
System.out.println(
"Sent message: " + message.hashCode() + " : " + Thread.currentThread().getName());
producer.send(message);
// Clean up
session.close();
} catch (Exception e) {
System.out.println("Caught: " + e);
e.printStackTrace();
}
}
}
public static class HelloWorldConsumer implements Runnable, ExceptionListener {
private final Connection connection;
public HelloWorldConsumer(Connection connection) {
this.connection = connection;
}
public void run() {
try {
// Create a Session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Create the destination (Topic or Queue)
Destination destination = session.createQueue("TEST.FOO");
// Create a MessageConsumer from the Session to the Topic or Queue
MessageConsumer consumer = session.createConsumer(destination);
System.out.println("CONSUMER: " + consumer);
// Wait for a message
Message message = consumer.receive(1000);
if (message instanceof TextMessage) {
TextMessage textMessage = (TextMessage) message;
String text = textMessage.getText();
System.out.println("Received: " + text);
} else {
System.out.println("Received: " + message);
}
consumer.close();
session.close();
} catch (Exception e) {
System.out.println("Caught: " + e);
e.printStackTrace();
}
}
public synchronized void onException(JMSException ex) {
System.out.println("JMS Exception occured. Shutting down client.");
}
}
private static void thread(Runnable runnable, boolean daemon) {
Thread brokerThread = new Thread(runnable);
brokerThread.setDaemon(daemon);
brokerThread.start();
}
}
|
923f08b42572b8620213e959927c0fab52c5ed82
| 7,318 |
java
|
Java
|
src/test/java/org/folio/auth/authtokenmodule/UserServiceTest.java
|
folio-org/mod-authtoken
|
e32248d444e0e9f61b09b8b91cdbbe76210c311a
|
[
"Apache-2.0"
] | 2 |
2019-03-01T13:51:35.000Z
|
2022-02-22T20:31:22.000Z
|
src/test/java/org/folio/auth/authtokenmodule/UserServiceTest.java
|
folio-org/mod-authtoken
|
e32248d444e0e9f61b09b8b91cdbbe76210c311a
|
[
"Apache-2.0"
] | 70 |
2017-04-27T13:04:04.000Z
|
2022-03-31T17:31:11.000Z
|
src/test/java/org/folio/auth/authtokenmodule/UserServiceTest.java
|
folio-org/mod-authtoken
|
e32248d444e0e9f61b09b8b91cdbbe76210c311a
|
[
"Apache-2.0"
] | 5 |
2017-07-11T20:16:55.000Z
|
2022-02-28T08:51:10.000Z
| 33.415525 | 117 | 0.645532 | 1,001,004 |
package org.folio.auth.authtokenmodule;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import com.nimbusds.jose.JOSEException;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import org.junit.runner.RunWith;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
@RunWith(VertxUnitRunner.class)
public class UserServiceTest {
private static final String TENANT = "test-tenant";
private static final String TOKEN = "test-token";
private static final String REQ_ID = "test-req-id";
private static int mockPort;
private static int freePort;
private static String mockUrl;
private static String badMockUrl;
private static Vertx vertx;
@BeforeClass
public static void setUpClass(TestContext context) throws NoSuchAlgorithmException, JOSEException, ParseException {
Async async = context.async();
freePort = NetworkUtils.nextFreePort();
mockPort = NetworkUtils.nextFreePort();
mockUrl = "http://localhost:" + mockPort;
badMockUrl = "http://localhost:" + freePort;
vertx = Vertx.vertx();
DeploymentOptions mockOptions = new DeploymentOptions().setConfig(new JsonObject().put("port", mockPort));
vertx.deployVerticle(UsersMock.class.getName(), mockOptions, mockRes -> {
if (mockRes.failed()) {
mockRes.cause().printStackTrace();
context.fail(mockRes.cause());
}
async.complete();
});
}
@AfterClass
public static void tearDownClass(TestContext context) {
Async async = context.async();
vertx.close(x -> {
async.complete();
});
}
@Test
public void testNonExistingUser(TestContext context) {
Async async = context.async();
UserService userService = new UserService(vertx, 3, 10);
userService.isActiveUser("0", TENANT, mockUrl, TOKEN, REQ_ID).onComplete(ar -> {
if (ar.succeeded()) {
context.fail("User id 0 should fail with 404 response");
}
async.complete();
});
}
@Test
public void testInvalidResponseCode(TestContext context) {
Async async = context.async();
UserService userService = new UserService(vertx, 3, 10);
userService.isActiveUser("00", TENANT, mockUrl, TOKEN, REQ_ID).onComplete(ar -> {
if (ar.succeeded()) {
context.fail("User id 00 should fail with invalid response code");
}
context.assertTrue(ar.cause().getLocalizedMessage().contains("response code"));
async.complete();
});
}
@Test
public void testInvalidResponseJson(TestContext context) {
Async async = context.async();
UserService userService = new UserService(vertx, 3, 10);
userService.isActiveUser("000", TENANT, mockUrl, TOKEN, REQ_ID).onComplete(ar -> {
if (ar.succeeded()) {
context.fail("User id 000 should fail with invalid user response");
}
context.assertTrue(ar.cause().getLocalizedMessage().contains("Invalid user response"));
async.complete();
});
}
@Test
public void testNullActive(TestContext context) {
Async async = context.async();
UserService userService = new UserService(vertx, 3, 10);
userService.isActiveUser("1", TENANT, mockUrl, TOKEN, REQ_ID).onComplete(ar -> {
if (ar.failed() || ar.result() != null) {
context.fail("User id 1 should be null");
}
context.assertNull(ar.result());
async.complete();
});
}
@Test
public void testInactiveUser(TestContext context) {
Async async = context.async();
UserService userService = new UserService(vertx, 3, 10);
userService.isActiveUser("2", TENANT, mockUrl, TOKEN, REQ_ID).onComplete(ar -> {
if (ar.failed() || ar.result().booleanValue()) {
context.fail("User id 2 should be inactive");
}
context.assertFalse(ar.result());
async.complete();
});
}
@Test
public void testActiveUser(TestContext context) {
Async async = context.async();
UserService userService = new UserService(vertx, 3, 10);
userService.isActiveUser("3", TENANT, mockUrl, TOKEN, REQ_ID).onComplete(ar -> {
if (ar.failed() || !ar.result().booleanValue()) {
context.fail("User id 3 should be active");
}
context.assertTrue(ar.result());
async.complete();
});
}
@Test
public void testMultipleActiveUsers(TestContext context) {
Async async = context.async();
UserService userService = new UserService(vertx, 3, 10);
userService.isActiveUser("3", TENANT, mockUrl, "token", "reqId").onComplete(ar -> {
if (ar.failed() || !ar.result().booleanValue()) {
context.fail("User id 3 should be active");
}
context.assertTrue(ar.result());
});
vertx.setTimer(1000, id -> {
userService.isActiveUser("33", TENANT, mockUrl, "token", null).onComplete(ar -> {
if (ar.failed() || !ar.result().booleanValue()) {
context.fail("User id 33 should be active");
}
context.assertTrue(ar.result());
async.complete();
});
});
}
@Test
public void testCache(TestContext context) {
Async async = context.async();
UserService userService = new UserService(vertx, 3, 10);
userService.isActiveUser("4", TENANT, mockUrl, TOKEN, REQ_ID).onComplete(ar -> {
if (ar.failed() || !ar.result().booleanValue()) {
context.fail("User id 4 should be active");
}
context.assertTrue(ar.result());
});
vertx.setTimer(1000, id -> {
userService.isActiveUser("4", TENANT, badMockUrl, TOKEN, REQ_ID).onComplete(ar -> {
if (ar.failed() || !ar.result().booleanValue()) {
context.fail("User id 4 should be active");
}
context.assertTrue(ar.result());
async.complete();
});
});
}
@Test
public void testExpiredCache(TestContext context) {
Async async = context.async();
UserService userService = new UserService(vertx, 1, 10);
userService.isActiveUser("4", TENANT, mockUrl, TOKEN, REQ_ID).onComplete(ar -> {
if (ar.failed() || !ar.result().booleanValue()) {
context.fail("User id 4 should be active");
}
context.assertTrue(ar.result());
});
vertx.setTimer(2000, id -> {
userService.isActiveUser("4", TENANT, "http://localhost:" + freePort, "", "").onComplete(ar -> {
if (ar.succeeded()) {
context.fail("Expired cache should make a new request");
}
async.complete();
});
});
}
@Test
public void testPurgeCache(TestContext context) {
Async async = context.async();
UserService userService = new UserService(vertx, 10, 1);
userService.isActiveUser("4", TENANT, mockUrl, TOKEN, REQ_ID).onComplete(ar -> {
if (ar.failed() || !ar.result().booleanValue()) {
context.fail("User id 4 should be active");
}
context.assertTrue(ar.result());
});
vertx.setTimer(2000, id -> {
userService.isActiveUser("4", TENANT, "http://localhost:" + freePort, "", "").onComplete(ar -> {
if (ar.succeeded()) {
context.fail("Purged cache should make a new request");
}
async.complete();
});
});
}
}
|
923f08cb9990f8765fff61cbd4e31c98e09b0d1e
| 12,582 |
java
|
Java
|
MAME4all/trunk/Android/MAME4droid/src/com/seleuco/mame4all/Emulator.java
|
lofunz/mieme
|
4226c2960b46121ec44fa8eab9717d2d644bff04
|
[
"Unlicense"
] | 51 |
2015-11-22T14:53:28.000Z
|
2021-12-14T07:17:42.000Z
|
MAME4all/trunk/Android/MAME4droid/src/com/seleuco/mame4all/Emulator.java
|
lofunz/mieme
|
4226c2960b46121ec44fa8eab9717d2d644bff04
|
[
"Unlicense"
] | 8 |
2018-01-14T07:19:06.000Z
|
2021-08-22T15:29:59.000Z
|
Android/MAME4droid/src/com/seleuco/mame4all/Emulator.java
|
raytlin/iMameAtariArcadeDuo
|
24adc56d1a6080822a6c9d1770ddbc607814373a
|
[
"Unlicense"
] | 35 |
2017-02-15T09:39:00.000Z
|
2021-12-14T07:17:43.000Z
| 24.865613 | 113 | 0.690113 | 1,001,005 |
/*
* This file is part of MAME4droid.
*
* Copyright (C) 2011-2013 David Valdeita (Seleuco)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses>.
*
* Linking MAME4droid statically or dynamically with other modules is
* making a combined work based on MAME4droid. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* In addition, as a special exception, the copyright holders of MAME4droid
* give you permission to combine MAME4droid with free software programs
* or libraries that are released under the GNU LGPL and with code included
* in the standard release of MAME under the MAME License (or modified
* versions of such code, with unchanged license). You may copy and
* distribute such a system following the terms of the GNU GPL for MAME4droid
* and the licenses of the other code concerned, provided that you include
* the source code of that other code when and as the GNU GPL requires
* distribution of source code.
*
* Note that people who make modified versions of MAME4droid are not
* obligated to grant this special exception for their modified versions; it
* is their choice whether to do so. The GNU General Public License
* gives permission to release a modified version without this exception;
* this exception also makes it possible to release a modified version
* which carries forward this exception.
*
* MAME4droid is dual-licensed: Alternatively, you can license MAME4droid
* under a MAME license, as set out in http://mamedev.org/
*/
package com.seleuco.mame4all;
import java.nio.ByteBuffer;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Paint.Style;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.view.SurfaceHolder;
import com.seleuco.mame4all.helpers.PrefsHelper;
import com.seleuco.mame4all.views.EmulatorViewGL;
public class Emulator
{
final static public int FPS_SHOWED_KEY = 1;
final static public int EXIT_GAME_KEY = 2;
final static public int LAND_BUTTONS_KEY = 3;
final static public int HIDE_LR__KEY = 4;
final static public int BPLUSX_KEY = 5;
final static public int WAYS_STICK_KEY = 6;
final static public int ASMCORES_KEY = 7;
final static public int INFOWARN_KEY = 8;
final static public int EXIT_PAUSE = 9;
final static public int IDLE_WAIT = 10;
private static MAME4all mm = null;
private static boolean isEmulating = false;
public static boolean isEmulating() {
return isEmulating;
}
private static boolean paused = false;
private static Object lock1 = new Object();
private static Object lock2 = new Object();
private static SurfaceHolder holder = null;
private static Bitmap emuBitmap = Bitmap.createBitmap(320, 240, Bitmap.Config.RGB_565);
private static ByteBuffer screenBuff = null;
private static int []screenBuffPx = new int[640*480*3];
public static int[] getScreenBuffPx() {
return screenBuffPx;
}
private static boolean frameFiltering = false;
public static boolean isFrameFiltering() {
return frameFiltering;
}
private static Paint emuPaint = null;
private static Paint debugPaint = new Paint();
private static Matrix mtx = new Matrix();
private static int window_width = 320;
public static int getWindow_width() {
return window_width;
}
private static int window_height = 240;
public static int getWindow_height() {
return window_height;
}
private static int emu_width = 320;
private static int emu_height = 240;
private static AudioTrack audioTrack = null;
private static boolean isThreadedSound = false;
private static boolean isDebug = false;
private static int videoRenderMode = PrefsHelper.PREF_RENDER_THREADED;
private static boolean inMAME = false;
public static boolean isInMAME() {
return inMAME;
}
private static int overlayFilterType = PrefsHelper.PREF_FILTER_NONE;
public static int getOverlayFilterType() {
return overlayFilterType;
}
public static void setOverlayFilterType(int overlayFilterType) {
Emulator.overlayFilterType = overlayFilterType;
}
static long j = 0;
static int i = 0;
static int fps = 0;
static long millis;
private static SoundThread soundT = new SoundThread();
private static VideoThread videoT = new VideoThread();
static
{
try
{
System.loadLibrary("mame4all-jni");
}
catch(java.lang.Error e)
{
e.printStackTrace();
}
debugPaint.setARGB(255, 255, 255, 255);
debugPaint.setStyle(Style.STROKE);
debugPaint.setTextSize(16);
//videoT.start();
}
public static int getEmulatedWidth() {
return emu_width;
}
public static int getEmulatedHeight() {
return emu_height;
}
public static boolean isThreadedSound() {
return isThreadedSound;
}
public static void setThreadedSound(boolean isThreadedSound) {
Emulator.isThreadedSound = isThreadedSound;
}
public static boolean isDebug() {
return isDebug;
}
public static void setDebug(boolean isDebug) {
Emulator.isDebug = isDebug;
}
public static int getVideoRenderMode() {
return Emulator.videoRenderMode;
}
public static void setVideoRenderMode(int videoRenderMode) {
Emulator.videoRenderMode = videoRenderMode;
}
public static Paint getEmuPaint() {
return emuPaint;
}
public static Paint getDebugPaint() {
return debugPaint;
}
public static Matrix getMatrix() {
return mtx;
}
//synchronized
public static SurfaceHolder getHolder(){
return holder;
}
//synchronized
public static Bitmap getEmuBitmap(){
return emuBitmap;
}
//synchronized
public static ByteBuffer getScreenBuffer(){
return screenBuff;
}
public static void setHolder(SurfaceHolder value) {
//Log.d("Thread Video", "Set holder nuevo "+values+" ant "+holder);
synchronized(lock1)
{
if(value!=null)
{
holder = value;
holder.setFormat(PixelFormat.OPAQUE);
//holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
holder.setKeepScreenOn(true);
videoT.start();
//ensureScreenDrawed();
//Log.d("Thread Video", "Salgo start");
}
else
{
videoT.stop();
holder=null;
//Log.d("Thread Video", "Salgo stop");
}
}
}
public static Canvas lockCanvas(){
if(holder!=null)
{
return holder.lockCanvas();
}
else
return null;
}
public static void unlockCanvas(Canvas c){
if(holder!=null && c!=null)
{
holder.unlockCanvasAndPost(c);
}
}
public static void setMAME4all(MAME4all mm) {
Emulator.mm = mm;
videoT.setMAME4all(mm);
}
//VIDEO
public static void setWindowSize(int w, int h) {
window_width = w;
window_height = h;
if(videoRenderMode == PrefsHelper.PREF_RENDER_GL)
return;
mtx.setScale((float)(window_width / (float)emu_width), (float)(window_height / (float)emu_height));
}
public static void setFrameFiltering(boolean value) {
frameFiltering = value;
if(value)
{
emuPaint = new Paint();
emuPaint.setFilterBitmap(true);
}
else
{
emuPaint = null;
}
}
//synchronized
static void bitblt(ByteBuffer sScreenBuff, boolean inMAME) {
if(paused) //locks are expensive
{
synchronized(lock2)
{
try
{
if(paused)
lock2.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
synchronized(lock1){
//try {
screenBuff = sScreenBuff;
Emulator.inMAME = inMAME;
if(videoRenderMode == PrefsHelper.PREF_RENDER_GL){
//if(mm.getEmuView() instanceof EmulatorViewGL)
((EmulatorViewGL)mm.getEmuView()).requestRender();
}
else if(videoRenderMode == PrefsHelper.PREF_RENDER_THREADED)
{
videoT.update();
}
else if(videoRenderMode == PrefsHelper.PREF_RENDER_HW)
{
//mm.getEmuView().setWillNotDraw(false);
videoT.update();
}
else
{
if (holder==null)
return;
Canvas canvas = holder.lockCanvas();
sScreenBuff.rewind();
emuBitmap.copyPixelsFromBuffer(sScreenBuff);
i++;
canvas.concat(mtx);
canvas.drawBitmap(emuBitmap, 0, 0, emuPaint);
//canvas.drawBitmap(emuBitmap, null, frameRect, emuPaint);
if(isDebug)
{
canvas.drawText("Normal fps:"+fps+ " "+inMAME, 5, 40, debugPaint);
if(System.currentTimeMillis() - millis >= 1000) {fps = i; i=0;millis = System.currentTimeMillis();}
}
holder.unlockCanvasAndPost(canvas);
}
/*
} catch (Throwable t) {
Log.getStackTraceString(t);
}
*/
}
}
//synchronized
static public void changeVideo(int newWidth, int newHeight){
//Log.d("Thread Video", "changeVideo");
synchronized(lock1){
for(int i=0;i<4;i++)
Emulator.setPadData(i,0);
//if(emu_width!=newWidth || emu_height!=newHeight)
//{
emu_width = newWidth;
emu_height = newHeight;
emuBitmap = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.RGB_565);
mtx.setScale((float)(window_width / (float)emu_width), (float)(window_height / (float)emu_height));
if(videoRenderMode == PrefsHelper.PREF_RENDER_GL)
{
GLRenderer r = (GLRenderer)((EmulatorViewGL)mm.getEmuView()).getRender();
if(r!=null)r.changedEmulatedSize();
}
mm.runOnUiThread(new Runnable() {
public void run() {
mm.getMainHelper().updateMAME4all();
}
});
//}
}
}
//SOUND
static public void initAudio(int freq, boolean stereo)
{
int sampleFreq = freq;
int channelConfig = stereo ? AudioFormat.CHANNEL_CONFIGURATION_STEREO : AudioFormat.CHANNEL_CONFIGURATION_MONO;
int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
int bufferSize = AudioTrack.getMinBufferSize(sampleFreq, channelConfig, audioFormat) * 2;// * 4;//*2?
//System.out.println("Buffer Size "+bufferSize);
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
sampleFreq,
channelConfig,
audioFormat,
bufferSize,
AudioTrack.MODE_STREAM);
audioTrack.play();
}
public static void endAudio(){
audioTrack.stop();
audioTrack.release();
audioTrack = null;
}
public static void writeAudio(byte[] b, int sz)
{
//System.out.println("Envio "+sz+" "+audioTrack);
if(audioTrack!=null)
{
if(isThreadedSound && soundT!=null)
{
soundT.setAudioTrack(audioTrack);
soundT.writeSample(b, sz);
}
else
{
audioTrack.write(b, 0, sz);
}
}
}
//LIVE CYCLE
public static void pause(){
//Log.d("EMULATOR", "PAUSE");
if(isEmulating)
{
//pauseEmulation(true);
paused = true;
}
if(audioTrack!=null)
audioTrack.pause();
videoT.stop();
}
public static void resume(){
//Log.d("EMULATOR", "RESUME");
if(audioTrack!=null)
audioTrack.play();
if(isEmulating)
{
//pauseEmulation(false);
Emulator.setValue(Emulator.EXIT_PAUSE, 1);
synchronized(lock2){
paused = false;
lock2.notify();
}
}
videoT.start();
}
//EMULATOR
public static void emulate(final String libPath,final String resPath){
//Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
if (isEmulating)return;
Thread t = new Thread(new Runnable(){
public void run() {
isEmulating = true;
init(libPath,resPath);
}
},"emulator-Thread");
//t.setPriority(Thread.MIN_PRIORITY);
//t.setPriority(Thread.MAX_PRIORITY);
t.start();
}
//native
protected static native void init(String libPath,String resPath);
synchronized public static native void setPadData(int i, long data);
synchronized public static native void setAnalogData(int i, float v1, float v2);
public static native int getValue(int key);
public static native void setValue(int key, int value);
}
|
923f090010f2f5120460d5c5e1e78b73581ddaaf
| 211 |
java
|
Java
|
String/CountSegment.java
|
Greedylightning/LeetCode_Second
|
da3bf7603b927e4917698ca6a81de391bbbe31f5
|
[
"MIT"
] | null | null | null |
String/CountSegment.java
|
Greedylightning/LeetCode_Second
|
da3bf7603b927e4917698ca6a81de391bbbe31f5
|
[
"MIT"
] | null | null | null |
String/CountSegment.java
|
Greedylightning/LeetCode_Second
|
da3bf7603b927e4917698ca6a81de391bbbe31f5
|
[
"MIT"
] | null | null | null | 23.444444 | 50 | 0.507109 | 1,001,006 |
class CountSegment{
public int countSegments(String s) {
s = s.trim();
if(s == null || s.length() == 0) return 0;
String[] temp = s.split("\\s+");
return temp.length;
}
}
|
923f0a54ef08d7c2dcf9334101afb2ae1cb012e5
| 4,069 |
java
|
Java
|
evosuite/client/src/main/java/org/evosuite/testcase/execution/ExecutionObserver.java
|
racoq/TESRAC
|
75a33741bd7a0c27a5fcd183fb4418d7b7146e80
|
[
"Apache-2.0"
] | null | null | null |
evosuite/client/src/main/java/org/evosuite/testcase/execution/ExecutionObserver.java
|
racoq/TESRAC
|
75a33741bd7a0c27a5fcd183fb4418d7b7146e80
|
[
"Apache-2.0"
] | null | null | null |
evosuite/client/src/main/java/org/evosuite/testcase/execution/ExecutionObserver.java
|
racoq/TESRAC
|
75a33741bd7a0c27a5fcd183fb4418d7b7146e80
|
[
"Apache-2.0"
] | null | null | null | 30.140741 | 87 | 0.670189 | 1,001,007 |
/**
* Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3.0 of the License, or
* (at your option) any later version.
*
* EvoSuite is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package org.evosuite.testcase.execution;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.evosuite.testcase.statements.Statement;
import org.evosuite.testcase.TestCase;
import org.evosuite.testcase.variable.VariableReference;
/**
* Abstract base class of all execution observers
*
* @author Gordon Fraser
*/
public abstract class ExecutionObserver {
/** The test case being monitored and executed */
protected static TestCase currentTest = null;
/** Constant <code>WRAPPER_TYPES</code> */
protected static final Set<Class<?>> WRAPPER_TYPES = new HashSet<Class<?>>(
Arrays.asList(Boolean.class, Character.class, Byte.class, Short.class,
Integer.class, Long.class, Float.class, Double.class,
Void.class));
/**
* <p>
* isWrapperType
* </p>
*
* @param clazz
* a {@link java.lang.Class} object.
* @return a boolean.
*/
protected static boolean isWrapperType(Class<?> clazz) {
return WRAPPER_TYPES.contains(clazz);
}
/**
* Setter method for current test case
*
* @param test
* a {@link org.evosuite.testcase.TestCase} object.
*/
public static void setCurrentTest(TestCase test) {
currentTest = test;
}
/**
* Getter method for current test case
*
* @return a {@link org.evosuite.testcase.TestCase} object.
*/
public static TestCase getCurrentTest() {
return currentTest;
}
/**
* This is called with the console output of each statement
*
* @param position
* a int.
* @param output
* a {@link java.lang.String} object.
*/
public abstract void output(int position, String output);
/**
* Called immediately before a statement is executed
*
* @param statement
* @param scope
*/
public abstract void beforeStatement(Statement statement, Scope scope);
/**
* After execution of a statement, the result is passed to the observer
*
* @param statement
* a {@link org.evosuite.testcase.statements.Statement} object.
* @param scope
* a {@link org.evosuite.testcase.execution.Scope} object.
* @param exception
* a {@link java.lang.Throwable} object.
*/
public abstract void afterStatement(Statement statement, Scope scope,
Throwable exception);
/**
* Allow observers to update the execution result at the end the execution of a test.
*/
public abstract void testExecutionFinished(ExecutionResult r, Scope s);
/**
* Need a way to clear previously produced results
*/
public abstract void clear();
/**
* Determine the set of variables that somehow lead to this statement
*
* @param statement
* a {@link org.evosuite.testcase.statements.Statement} object.
* @return a {@link java.util.Set} object.
*/
protected Set<VariableReference> getDependentVariables(Statement statement) {
Set<VariableReference> dependencies = new HashSet<VariableReference>();
for (VariableReference var : statement.getVariableReferences()) {
dependencies.add(var);
dependencies.addAll(currentTest.getDependencies(var));
}
return dependencies;
}
}
|
923f0a807a63e87869e07d096be6b533a60028ea
| 1,686 |
java
|
Java
|
commons/src/main/java/org/apache/mesos/elasticsearch/common/zookeeper/parser/ZKAddressParser.java
|
Klarrio/elasticsearch
|
a22fcd1b97d3efc3a9c8260d0783d6927022827b
|
[
"Apache-2.0"
] | null | null | null |
commons/src/main/java/org/apache/mesos/elasticsearch/common/zookeeper/parser/ZKAddressParser.java
|
Klarrio/elasticsearch
|
a22fcd1b97d3efc3a9c8260d0783d6927022827b
|
[
"Apache-2.0"
] | null | null | null |
commons/src/main/java/org/apache/mesos/elasticsearch/common/zookeeper/parser/ZKAddressParser.java
|
Klarrio/elasticsearch
|
a22fcd1b97d3efc3a9c8260d0783d6927022827b
|
[
"Apache-2.0"
] | null | null | null | 30.107143 | 89 | 0.670225 | 1,001,008 |
package org.apache.mesos.elasticsearch.common.zookeeper.parser;
import org.apache.commons.lang3.StringUtils;
import org.apache.mesos.elasticsearch.common.zookeeper.exception.ZKAddressException;
import org.apache.mesos.elasticsearch.common.zookeeper.model.ZKAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Validates ZK url and parses ZK addresses.
*
* IMPORTANT: Different components in the framework require different ZK address strings.
*
* 1) The ZK State requires a ZK servers url
*
* host1:port1,host2:port2
*
* 2) The MesosSchedulerDriver requires a full ZK url
*
* zk://host1:port1,host2:port2/mesos
*/
public class ZKAddressParser {
public static final String ZK_PREFIX_REGEX = "^" + ZKAddress.ZK_PREFIX + ".*";
public List<ZKAddress> validateZkUrl(final String zkUrl) {
final List<ZKAddress> zkList = new ArrayList<>();
// Ensure that string is prefixed with "zk://"
Matcher matcher = Pattern.compile(ZK_PREFIX_REGEX).matcher(zkUrl);
if (!matcher.matches()) {
throw new ZKAddressException(zkUrl);
}
if (StringUtils.countMatches(zkUrl, '/') < 3) {
throw new ZKAddressException(zkUrl);
}
// Strip zk prefix and spaces
String zkStripped = zkUrl.replace(ZKAddress.ZK_PREFIX, "").replace(" ", "");
// Split address by commas
String[] split = zkStripped.split(",");
// Validate and add each split
for (String s : split) {
zkList.add(new ZKAddress(s));
}
// Return list of zk addresses
return zkList;
}
}
|
923f0a8cb22bca62853e67fb247938a91f5b5efc
| 1,837 |
java
|
Java
|
blobstore/src/main/java/org/jclouds/blobstore/attr/FolderCapability.java
|
bosschaert/jclouds
|
f7576dfc697e54a68baf09967bccc8f708735992
|
[
"Apache-2.0"
] | 1 |
2019-09-11T01:13:03.000Z
|
2019-09-11T01:13:03.000Z
|
blobstore/src/main/java/org/jclouds/blobstore/attr/FolderCapability.java
|
bosschaert/jclouds
|
f7576dfc697e54a68baf09967bccc8f708735992
|
[
"Apache-2.0"
] | null | null | null |
blobstore/src/main/java/org/jclouds/blobstore/attr/FolderCapability.java
|
bosschaert/jclouds
|
f7576dfc697e54a68baf09967bccc8f708735992
|
[
"Apache-2.0"
] | null | null | null | 22.47561 | 75 | 0.616386 | 1,001,009 |
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <[email protected]>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.blobstore.attr;
/**
* Represents the capabilities of a BlobStore
*
* @author Adrian Cole
*
*/
public enum FolderCapability {
/**
* deletion of a container is recursive
*/
RECURSIVE_DELETE,
/**
* There's a container that exists at the root of the service
*/
ROOTCONTAINER,
/**
* Containers (and subcontainers) are created implicitly
*/
SKIP_CREATE_CONTAINER,
/**
* containers can have key-value pairs associated with them
*/
METADATA,
/**
* containers have an etag associated with them
*/
ETAG,
/**
* containers have a system generated ID associated with them
*/
ID,
/**
* container will have last modified date associated with them
*/
LAST_MODIFIED,
/**
* timestamps are precise in milliseconds (as opposed to seconds)
*/
MILLISECOND_PRECISION,
/**
* container size in bytes is exposed by service listing
*/
SIZE,
/**
* possible to expose a container to anonymous access
*/
PUBLIC
}
|
923f0af94b80d48b325e060e8736bfc6e1ff299b
| 3,592 |
java
|
Java
|
src/main/java/com/grimbo/chipped/integration/jei/JEIPlugin.java
|
qsefthuopq/Chipped
|
ac74335593bbce883e2caff0687ef4d5649500a4
|
[
"CC0-1.0"
] | null | null | null |
src/main/java/com/grimbo/chipped/integration/jei/JEIPlugin.java
|
qsefthuopq/Chipped
|
ac74335593bbce883e2caff0687ef4d5649500a4
|
[
"CC0-1.0"
] | null | null | null |
src/main/java/com/grimbo/chipped/integration/jei/JEIPlugin.java
|
qsefthuopq/Chipped
|
ac74335593bbce883e2caff0687ef4d5649500a4
|
[
"CC0-1.0"
] | null | null | null | 45.468354 | 114 | 0.814588 | 1,001,010 |
package com.grimbo.chipped.integration.jei;
import com.grimbo.chipped.Chipped;
import com.grimbo.chipped.block.ChippedBlocks;
import com.grimbo.chipped.recipe.ChippedSerializer;
import mezz.jei.api.IModPlugin;
import mezz.jei.api.JeiPlugin;
import mezz.jei.api.registration.IRecipeCatalystRegistration;
import mezz.jei.api.registration.IRecipeCategoryRegistration;
import mezz.jei.api.registration.IRecipeRegistration;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.RecipeManager;
import net.minecraft.util.ResourceLocation;
@JeiPlugin
public class JEIPlugin implements IModPlugin {
private static final ResourceLocation UID = new ResourceLocation(Chipped.MOD_ID, "chipped");
@Override
public ResourceLocation getPluginUid() {
return UID;
}
/*
* Registering workbenches under JEI
* 1. Create a new RecipeCategory in this::registerCategories
* 2. Add the recipe in this::registerRecipes
* 3. Add the recipe catalyst in this::registerRecipeCatalysts
*/
@Override
public void registerCategories(IRecipeCategoryRegistration registry) {
registry.addRecipeCategories(
new ChippedRecipeCategory("botanist_workbench", registry.getJeiHelpers().getGuiHelper()),
new ChippedRecipeCategory("glassblower", registry.getJeiHelpers().getGuiHelper()),
new ChippedRecipeCategory("carpenters_table", registry.getJeiHelpers().getGuiHelper()),
new ChippedRecipeCategory("loom_table", registry.getJeiHelpers().getGuiHelper()),
new ChippedRecipeCategory("mason_table", registry.getJeiHelpers().getGuiHelper()),
new ChippedRecipeCategory("alchemy_bench", registry.getJeiHelpers().getGuiHelper()));
}
@SuppressWarnings("resource")
@Override
public void registerRecipes(IRecipeRegistration registration) {
RecipeManager recipeManager = Minecraft.getInstance().level.getRecipeManager();
registration.addRecipes(recipeManager.getAllRecipesFor(ChippedSerializer.BOTANIST_WORKBENCH_TYPE),
getUidFromId("botanist_workbench"));
registration.addRecipes(recipeManager.getAllRecipesFor(ChippedSerializer.GLASSBLOWER_TYPE),
getUidFromId("glassblower"));
registration.addRecipes(recipeManager.getAllRecipesFor(ChippedSerializer.CARPENTERS_TABLE_TYPE),
getUidFromId("carpenters_table"));
registration.addRecipes(recipeManager.getAllRecipesFor(ChippedSerializer.LOOM_TABLE_TYPE),
getUidFromId("loom_table"));
registration.addRecipes(recipeManager.getAllRecipesFor(ChippedSerializer.MASON_TABLE_TYPE),
getUidFromId("mason_table"));
registration.addRecipes(recipeManager.getAllRecipesFor(ChippedSerializer.ALCHEMY_BENCH_TYPE),
getUidFromId("alchemy_bench"));
}
@Override
public void registerRecipeCatalysts(IRecipeCatalystRegistration registration) {
registration.addRecipeCatalyst(new ItemStack(ChippedBlocks.BOTANIST_WORKBENCH.get()),
getUidFromId("botanist_workbench"));
registration.addRecipeCatalyst(new ItemStack(ChippedBlocks.GLASSBLOWER.get()), getUidFromId("glassblower"));
registration.addRecipeCatalyst(new ItemStack(ChippedBlocks.CARPENTERS_TABLE.get()),
getUidFromId("carpenters_table"));
registration.addRecipeCatalyst(new ItemStack(ChippedBlocks.LOOM_TABLE.get()), getUidFromId("loom_table"));
registration.addRecipeCatalyst(new ItemStack(ChippedBlocks.MASON_TABLE.get()), getUidFromId("mason_table"));
registration.addRecipeCatalyst(new ItemStack(ChippedBlocks.ALCHEMY_BENCH.get()), getUidFromId("alchemy_bench"));
}
private static ResourceLocation getUidFromId(String id) {
return new ResourceLocation(Chipped.MOD_ID, id);
}
}
|
923f0b69d1fd1a322fcde6988f4d3e225699b7ef
| 379 |
java
|
Java
|
netmodule/src/main/java/com/luuu/netmodule/VolleyUtilJ/VolleyErrorManager.java
|
chennuolix/AlmightProject
|
c801f7a7af964be1f7a3e1ef62477d45a7959a1b
|
[
"Apache-2.0"
] | null | null | null |
netmodule/src/main/java/com/luuu/netmodule/VolleyUtilJ/VolleyErrorManager.java
|
chennuolix/AlmightProject
|
c801f7a7af964be1f7a3e1ef62477d45a7959a1b
|
[
"Apache-2.0"
] | null | null | null |
netmodule/src/main/java/com/luuu/netmodule/VolleyUtilJ/VolleyErrorManager.java
|
chennuolix/AlmightProject
|
c801f7a7af964be1f7a3e1ef62477d45a7959a1b
|
[
"Apache-2.0"
] | null | null | null | 17.227273 | 57 | 0.701847 | 1,001,011 |
package com.luuu.netmodule.VolleyUtilJ;
import com.android.volley.VolleyError;
/**
* Created by luuu on 2018/1/7.
*/
public class VolleyErrorManager {
private VolleyError volleyError;
public VolleyError getVolleyError() {
return volleyError;
}
public void setVolleyError(VolleyError volleyError) {
this.volleyError = volleyError;
}
}
|
923f0bede1e6b8c389bb6d0bd6bcd7174a454b84
| 60 |
java
|
Java
|
src/mano/string/package-info.java
|
manoranjan2015/handson
|
220fe1c87693b22334e7e0d6fbb770e2b9b112d0
|
[
"Apache-2.0"
] | null | null | null |
src/mano/string/package-info.java
|
manoranjan2015/handson
|
220fe1c87693b22334e7e0d6fbb770e2b9b112d0
|
[
"Apache-2.0"
] | null | null | null |
src/mano/string/package-info.java
|
manoranjan2015/handson
|
220fe1c87693b22334e7e0d6fbb770e2b9b112d0
|
[
"Apache-2.0"
] | null | null | null | 7.5 | 20 | 0.466667 | 1,001,012 |
/**
*
*/
/**
* @author mdas2
*
*/
package mano.string;
|
923f0bf3750170e949684312ff3da52799de128d
| 1,650 |
java
|
Java
|
app/src/main/java/com/ldoublem/flightseat/MainActivity.java
|
starsoft35/FlightSeat
|
add1dab8ecaf9d800e64b15c845c44654e1010b5
|
[
"MIT",
"Unlicense"
] | 751 |
2016-07-28T14:22:31.000Z
|
2021-12-27T03:30:44.000Z
|
app/src/main/java/com/ldoublem/flightseat/MainActivity.java
|
starsoft35/FlightSeat
|
add1dab8ecaf9d800e64b15c845c44654e1010b5
|
[
"MIT",
"Unlicense"
] | null | null | null |
app/src/main/java/com/ldoublem/flightseat/MainActivity.java
|
starsoft35/FlightSeat
|
add1dab8ecaf9d800e64b15c845c44654e1010b5
|
[
"MIT",
"Unlicense"
] | 147 |
2016-07-29T12:19:04.000Z
|
2021-12-21T08:34:38.000Z
| 22.60274 | 77 | 0.555152 | 1,001,013 |
package com.ldoublem.flightseat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.ldoublem.flightseatselect.FlightSeatView;
public class MainActivity extends AppCompatActivity {
FlightSeatView mFlightSeatView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFlightSeatView = (FlightSeatView) findViewById(R.id.fsv);
mFlightSeatView.setMaxSelectStates(10);
setTestData();
}
public void zoom(View v) {
mFlightSeatView.startAnim(true);
}
public void gotoposition(View v) {
mFlightSeatView.goCabinPosition(FlightSeatView.CabinPosition.Middle);
}
public void clear(View v) {
mFlightSeatView.setEmptySelecting();
}
private void setTestData() {
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 9; j = j + 2) {
mFlightSeatView.setSeatSelected(j, i);
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 8; j = j + 2) {
mFlightSeatView.setSeatSelected(i + 20, j);
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 8; j = j + 3) {
mFlightSeatView.setSeatSelected(i + 35, j);
}
}
for (int i = 11; i < 20; i++) {
for (int j = 0; j < 8; j = j + 4) {
mFlightSeatView.setSeatSelected(i + 35, j);
}
}
mFlightSeatView.invalidate();
}
}
|
923f0caf86a0f303622a633ed370d14c2d0453c2
| 1,110 |
java
|
Java
|
android/src/main/java/com/wix/reactnativenotifications/RNNotificationsPackage.java
|
flying-phoenix-ood/react-native-notifications
|
dfb3831fec7973d50751cf0accb775477def3178
|
[
"MIT"
] | 18 |
2017-08-07T05:23:14.000Z
|
2019-04-10T07:35:12.000Z
|
android/src/main/java/com/wix/reactnativenotifications/RNNotificationsPackage.java
|
infinitered/react-native-notifications
|
dfb3831fec7973d50751cf0accb775477def3178
|
[
"MIT"
] | 3 |
2017-10-05T01:55:32.000Z
|
2018-07-27T05:41:46.000Z
|
android/src/main/java/com/wix/reactnativenotifications/RNNotificationsPackage.java
|
infinitered/react-native-notifications
|
dfb3831fec7973d50751cf0accb775477def3178
|
[
"MIT"
] | 30 |
2017-07-19T11:03:53.000Z
|
2020-11-18T11:00:09.000Z
| 28.461538 | 98 | 0.772973 | 1,001,014 |
package com.wix.reactnativenotifications;
import android.app.Application;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class RNNotificationsPackage implements ReactPackage {
final Application mApplication;
public RNNotificationsPackage(Application application) {
mApplication = application;
}
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new RNNotificationsModule(mApplication, reactContext));
}
// Deprecated RN 0.47
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
|
923f0d63248343534cb892330735e968843328d2
| 2,416 |
java
|
Java
|
src/main/java/com/highmobility/value/BytesWithLength.java
|
highmobility/-hm-java-utils
|
85df905a84ff748bca498a6b0377a3b11394a6df
|
[
"MIT"
] | 1 |
2019-06-24T08:37:17.000Z
|
2019-06-24T08:37:17.000Z
|
src/main/java/com/highmobility/value/BytesWithLength.java
|
highmobility/-hm-java-utils
|
85df905a84ff748bca498a6b0377a3b11394a6df
|
[
"MIT"
] | null | null | null |
src/main/java/com/highmobility/value/BytesWithLength.java
|
highmobility/-hm-java-utils
|
85df905a84ff748bca498a6b0377a3b11394a6df
|
[
"MIT"
] | null | null | null | 33.09589 | 111 | 0.666391 | 1,001,015 |
/*
* The MIT License
*
* Copyright (c) 2014- High-Mobility GmbH (https://high-mobility.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.highmobility.value;
import com.highmobility.utils.ByteUtils;
import com.highmobility.utils.Range;
public class BytesWithLength extends Bytes {
public BytesWithLength(Bytes value) {
super(value.getByteArray());
validateBytes();
}
/**
* @param value The bytes in hex or Base64.
*/
public BytesWithLength(String value) {
super(value);
validateBytes();
}
/**
* @param bytes The raw bytes.
*/
public BytesWithLength(byte[] bytes) {
super(bytes);
validateBytes();
}
public BytesWithLength() {
super();
}
void validateBytes() {
if ((getExpectedLength() != -1 && getExpectedLength() != bytes.length) ||
(getExpectedRange() != null && getExpectedRange().contains(bytes.length) ==
false)) {
throw new IllegalArgumentException(this.getClass() + ": invalid bytes " + ByteUtils.hexFromBytes
(bytes) + " for expected length: " + getExpectedLength() + " range " + getExpectedRange());
}
}
protected int getExpectedLength() {
return -1;
}
protected Range getExpectedRange() {
return null;
}
}
|
923f0e4c3b0b9fa7d41214d0519875aa4727b376
| 6,976 |
java
|
Java
|
engine/src/main/java/org/hippoecm/frontend/plugins/login/DefaultLoginPlugin.java
|
woshi114/hippo-cms
|
baf4516e800202468f71892e9b82d72dd22f2056
|
[
"Apache-2.0"
] | null | null | null |
engine/src/main/java/org/hippoecm/frontend/plugins/login/DefaultLoginPlugin.java
|
woshi114/hippo-cms
|
baf4516e800202468f71892e9b82d72dd22f2056
|
[
"Apache-2.0"
] | null | null | null |
engine/src/main/java/org/hippoecm/frontend/plugins/login/DefaultLoginPlugin.java
|
woshi114/hippo-cms
|
baf4516e800202468f71892e9b82d72dd22f2056
|
[
"Apache-2.0"
] | null | null | null | 46.198675 | 129 | 0.699685 | 1,001,016 |
/*
* Copyright 2016 Hippo B.V. (http://www.onehippo.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hippoecm.frontend.plugins.login;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.TimeZone;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.markup.head.JavaScriptReferenceHeaderItem;
import org.apache.wicket.markup.head.OnLoadHeaderItem;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.internal.HtmlHeaderContainer;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.request.resource.JavaScriptResourceReference;
import org.apache.wicket.request.resource.ResourceReference;
import org.apache.wicket.util.template.PackageTextTemplate;
import org.apache.wicket.util.template.TextTemplate;
import org.hippoecm.frontend.Main;
import org.hippoecm.frontend.plugin.IPluginContext;
import org.hippoecm.frontend.plugin.config.IPluginConfig;
import org.hippoecm.frontend.session.UserSession;
import org.hippoecm.frontend.util.WebApplicationHelper;
public class DefaultLoginPlugin extends SimpleLoginPlugin {
private static final TextTemplate INIT_JS = new PackageTextTemplate(DefaultLoginPlugin.class, "timezones-init.js");
// jstz.min.js is fetched by npm
private static final ResourceReference JSTZ_JS = new JavaScriptResourceReference(DefaultLoginPlugin.class, "jstz.min.js");
public static final String SHOW_TIMEZONES_CONFIG_PARAM = "show.timezones";
public static final String SELECTABLE_TIMEZONES_CONFIG_PARAM = "selectable.timezones";
public static final List<String> SUPPORTED_JAVA_TIMEZONES = excludeEtcTimeZones(Arrays.asList(TimeZone.getAvailableIDs()));
/**
* Exclude POSIX compatible timezones because they may cause confusions
*/
private static List<String> excludeEtcTimeZones(final List<String> timezones) {
return timezones.stream()
.filter((tz) -> !tz.startsWith("Etc/"))
.collect(Collectors.toList());
}
public DefaultLoginPlugin(final IPluginContext context, final IPluginConfig config) {
super(context, config);
}
@Override
protected LoginPanel createLoginPanel(final String id, final boolean autoComplete, final List<String> locales,
final LoginHandler handler) {
return new LoginForm(id, autoComplete, locales, handler);
}
protected class LoginForm extends CaptchaForm {
private static final String TIMEZONE_COOKIE = "tzcookie";
private static final int TIMEZONE_COOKIE_MAX_AGE = 365 * 24 * 3600; // expire one year from now
private String selectedTimeZone;
private List<String> availableTimeZones = Collections.emptyList();
private boolean useBrowserTimeZoneIfAvailable;
public LoginForm(final String id, final boolean autoComplete, final List<String> locales, final LoginHandler handler) {
super(id, autoComplete, locales, handler);
final IPluginConfig config = getPluginConfig();
final boolean consoleLogin = WebApplicationHelper.getApplicationName().equals(Main.PLUGIN_APPLICATION_VALUE_CONSOLE);
final boolean isTimeZoneVisible = !consoleLogin && config.getBoolean(SHOW_TIMEZONES_CONFIG_PARAM);
if (isTimeZoneVisible) {
availableTimeZones = getSelectableTimezones(config.getStringArray(SELECTABLE_TIMEZONES_CONFIG_PARAM));
// Check if user has previously selected a timezone
final String cookieTimeZone = getCookieValue(TIMEZONE_COOKIE);
if (isTimeZoneValid(cookieTimeZone)) {
selectedTimeZone = cookieTimeZone;
} else {
selectedTimeZone = availableTimeZones.get(0);
useBrowserTimeZoneIfAvailable = true;
}
}
// Add the time zone dropdown
final PropertyModel<String> selected = PropertyModel.of(this, "selectedTimeZone");
final DropDownChoice<String> timeZone = new DropDownChoice<>("timezone", selected, availableTimeZones);
timeZone.setNullValid(false);
final Label timeZoneLabel = new Label("timezone-label", new ResourceModel("timezone-label", "Time zone:"));
timeZoneLabel.setVisible(isTimeZoneVisible);
form.addLabelledComponent(timeZoneLabel);
form.add(timeZone);
}
@Override
public void renderHead(HtmlHeaderContainer container) {
super.renderHead(container);
if (getPluginConfig().getBoolean(SHOW_TIMEZONES_CONFIG_PARAM) && useBrowserTimeZoneIfAvailable) {
container.getHeaderResponse().render(JavaScriptReferenceHeaderItem.forReference(JSTZ_JS));
container.getHeaderResponse().render(OnLoadHeaderItem.forScript(INIT_JS.asString()));
}
}
@Override
protected void loginSuccess() {
if (isTimeZoneValid(selectedTimeZone)) {
final TimeZone timeZone = TimeZone.getTimeZone(selectedTimeZone);
// Store selected timezone in session and cookie
UserSession.get().getClientInfo().getProperties().setTimeZone(timeZone);
setCookieValue(TIMEZONE_COOKIE, selectedTimeZone, TIMEZONE_COOKIE_MAX_AGE);
}
super.loginSuccess();
}
private boolean isTimeZoneValid(String timeZone) {
return timeZone != null && availableTimeZones != null
&& availableTimeZones.contains(timeZone);
}
private List<String> getSelectableTimezones(final String[] configuredSelectableTimezones) {
List<String> selectableTimezones = new ArrayList<>();
if (configuredSelectableTimezones != null) {
selectableTimezones = Arrays.stream(configuredSelectableTimezones)
.filter(StringUtils::isNotBlank)
.filter(SUPPORTED_JAVA_TIMEZONES::contains)
.collect(Collectors.toList());
}
return selectableTimezones.isEmpty() ? SUPPORTED_JAVA_TIMEZONES : selectableTimezones;
}
}
}
|
923f0e9e7f1fed9f1900de2155144b31e060a410
| 1,657 |
java
|
Java
|
provider/provider-usc/src/main/java/org/tc/provider/config/AsyncTaskExecutorConfig.java
|
tc214/mallcloud-srv-master
|
c96e941764453b4d90c8ce2d4ee9e420dcf53780
|
[
"Apache-2.0"
] | null | null | null |
provider/provider-usc/src/main/java/org/tc/provider/config/AsyncTaskExecutorConfig.java
|
tc214/mallcloud-srv-master
|
c96e941764453b4d90c8ce2d4ee9e420dcf53780
|
[
"Apache-2.0"
] | null | null | null |
provider/provider-usc/src/main/java/org/tc/provider/config/AsyncTaskExecutorConfig.java
|
tc214/mallcloud-srv-master
|
c96e941764453b4d90c8ce2d4ee9e420dcf53780
|
[
"Apache-2.0"
] | null | null | null | 40.414634 | 90 | 0.812311 | 1,001,017 |
package org.tc.provider.config;
import org.tc.config.properties.MallCloudProperties;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import javax.annotation.Resource;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync
@EnableScheduling
public class AsyncTaskExecutorConfig implements AsyncConfigurer {
@Resource
private MallCloudProperties mallCloudProperties;
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(mallCloudProperties.getTask().getCorePoolSize());
executor.setMaxPoolSize(mallCloudProperties.getTask().getMaxPoolSize());
executor.setQueueCapacity(mallCloudProperties.getTask().getQueueCapacity());
executor.setKeepAliveSeconds(mallCloudProperties.getTask().getKeepAliveSeconds());
executor.setThreadNamePrefix(mallCloudProperties.getTask().getThreadNamePrefix());
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}
|
923f0edf90ba26b24a33d11c1039de1d3ade81e4
| 1,889 |
java
|
Java
|
core/src/main/java/com/predic8/membrane/core/interceptor/balancer/JSESSIONIDExtractor.java
|
LarsP8/service-proxy
|
d893246177eec8c3133bcc5bbdcd173d118ecf9c
|
[
"Apache-2.0"
] | 363 |
2015-01-08T20:23:26.000Z
|
2022-03-31T23:14:56.000Z
|
core/src/main/java/com/predic8/membrane/core/interceptor/balancer/JSESSIONIDExtractor.java
|
LarsP8/service-proxy
|
d893246177eec8c3133bcc5bbdcd173d118ecf9c
|
[
"Apache-2.0"
] | 224 |
2015-01-24T09:17:51.000Z
|
2022-03-31T20:24:02.000Z
|
core/src/main/java/com/predic8/membrane/core/interceptor/balancer/JSESSIONIDExtractor.java
|
LarsP8/service-proxy
|
d893246177eec8c3133bcc5bbdcd173d118ecf9c
|
[
"Apache-2.0"
] | 143 |
2015-01-23T10:59:28.000Z
|
2022-03-23T08:20:34.000Z
| 29.061538 | 90 | 0.73478 | 1,001,018 |
/* Copyright 2009, 2011 predic8 GmbH, www.predic8.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
package com.predic8.membrane.core.interceptor.balancer;
import java.util.regex.*;
import javax.xml.stream.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.predic8.membrane.annot.MCElement;
import com.predic8.membrane.core.http.Message;
/**
* @description The <i>jSessionIdExtractor</i> extracts the JSESSIONID from a
* message and provides it to the {@link Balancer}.
*/
@MCElement(name="jSessionIdExtractor")
public class JSESSIONIDExtractor extends AbstractSessionIdExtractor {
private static Logger log = LoggerFactory.getLogger(JSESSIONIDExtractor.class.getName());
Pattern pattern = Pattern.compile(".*JSESSIONID\\s*=([^;]*)");
@Override
public String getSessionId(Message msg) throws Exception {
String cookie = msg.getHeader().getFirstValue("Cookie");
if (cookie == null) {
log.debug("no cookie set");
return null;
}
Matcher m = pattern.matcher(cookie);
log.debug("cookie: " + msg.getHeader().getFirstValue("Cookie"));
if (!m.lookingAt()) return null;
log.debug("JSESSION cookie found: "+m.group(1).trim());
return m.group(1).trim();
}
@Override
public void write(XMLStreamWriter out)
throws XMLStreamException {
out.writeStartElement("jSessionIdExtractor");
out.writeEndElement();
}
}
|
923f0f2554d67d47c500993d3dc40c3537bca790
| 1,003 |
java
|
Java
|
shared/src/main/java/shared/results/DrawTrainCardsResult.java
|
bdemann/ticket-to-ride
|
2540fc3c853fa1bd0b86bed2f3ad23895ec881d9
|
[
"MIT"
] | null | null | null |
shared/src/main/java/shared/results/DrawTrainCardsResult.java
|
bdemann/ticket-to-ride
|
2540fc3c853fa1bd0b86bed2f3ad23895ec881d9
|
[
"MIT"
] | 2 |
2018-01-31T23:23:40.000Z
|
2018-01-31T23:27:45.000Z
|
shared/src/main/java/shared/results/DrawTrainCardsResult.java
|
bdemann/ticket-to-ride
|
2540fc3c853fa1bd0b86bed2f3ad23895ec881d9
|
[
"MIT"
] | null | null | null | 25.717949 | 151 | 0.718843 | 1,001,019 |
package shared.results;
import java.util.List;
import shared.command.ICommand;
import shared.model.TrainCard;
/**
* Created by bdemann on 3/20/18.
*/
public class DrawTrainCardsResult extends Result {
private List<TrainCard> faceUpCards;
private TrainCard drawnCard;
public DrawTrainCardsResult(TrainCard drawnCard, List<TrainCard> faceUpCards, boolean success, List<ICommand> clientCommands, String userMessage) {
super(success, clientCommands, userMessage);
this.drawnCard = drawnCard;
this.faceUpCards = faceUpCards;
}
public DrawTrainCardsResult(String exceptionType, String exceptionMessage) {
super(exceptionType, exceptionMessage);
}
public DrawTrainCardsResult(List<ICommand> clientCommands, String userMessage) {
super(false, clientCommands, userMessage);
}
public TrainCard getDrawnCard() {
return drawnCard;
}
public List<TrainCard> getFaceUpCards() {
return faceUpCards;
}
}
|
923f1079e334b5eb52e56008b017a7f3e2aa7ab4
| 634 |
java
|
Java
|
app/src/main/java/com/rakshitgl/trace/models/User.java
|
Raks110/Trace
|
ffd059985c8db8211226037b37207e449e50b1fd
|
[
"BSD-3-Clause"
] | 1 |
2020-07-01T05:25:45.000Z
|
2020-07-01T05:25:45.000Z
|
app/src/main/java/com/rakshitgl/trace/models/User.java
|
Raks110/Trace
|
ffd059985c8db8211226037b37207e449e50b1fd
|
[
"BSD-3-Clause"
] | null | null | null |
app/src/main/java/com/rakshitgl/trace/models/User.java
|
Raks110/Trace
|
ffd059985c8db8211226037b37207e449e50b1fd
|
[
"BSD-3-Clause"
] | 1 |
2020-07-01T05:25:59.000Z
|
2020-07-01T05:25:59.000Z
| 18.114286 | 52 | 0.635647 | 1,001,020 |
package com.rakshitgl.trace.models;
import android.net.Uri;
public class User {
private String email;
private String displayName;
private String photoURL;
public String getEmail() {
return email;
}
public String getDisplayName() {
return displayName;
}
public String getPhotoURL() {
return photoURL;
}
public void setEmail(String email) {
this.email = email;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public void setPhotoURL(String photoURL) {
this.photoURL = photoURL;
}
}
|
923f11981e5485694d47e0ddac11b58a7549d1ed
| 229 |
java
|
Java
|
api/src/main/java/com/fesg3/server/repositories/DisciplineRepository.java
|
luizmariz/Scoa
|
21fde138a8782222ed998b9f9f0d7e925ea8604a
|
[
"MIT"
] | null | null | null |
api/src/main/java/com/fesg3/server/repositories/DisciplineRepository.java
|
luizmariz/Scoa
|
21fde138a8782222ed998b9f9f0d7e925ea8604a
|
[
"MIT"
] | null | null | null |
api/src/main/java/com/fesg3/server/repositories/DisciplineRepository.java
|
luizmariz/Scoa
|
21fde138a8782222ed998b9f9f0d7e925ea8604a
|
[
"MIT"
] | null | null | null | 22.9 | 78 | 0.838428 | 1,001,021 |
package com.fesg3.server.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.fesg3.server.models.Discipline;
public interface DisciplineRepository extends JpaRepository<Discipline, Long>{
}
|
923f11a9315f083e69cedc034478109ccb2dc95d
| 798 |
java
|
Java
|
app/src/main/java/com/panda/videolivecore/view/HomeGridView.java
|
chenstrace/Videoliveplatform
|
4ac66da6db4183c209f6054e9bad780c00f5f27a
|
[
"MIT"
] | null | null | null |
app/src/main/java/com/panda/videolivecore/view/HomeGridView.java
|
chenstrace/Videoliveplatform
|
4ac66da6db4183c209f6054e9bad780c00f5f27a
|
[
"MIT"
] | null | null | null |
app/src/main/java/com/panda/videolivecore/view/HomeGridView.java
|
chenstrace/Videoliveplatform
|
4ac66da6db4183c209f6054e9bad780c00f5f27a
|
[
"MIT"
] | null | null | null | 26.6 | 89 | 0.759398 | 1,001,022 |
package com.panda.videolivecore.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.View.MeasureSpec;
import android.widget.GridView;
public class HomeGridView extends GridView
{
public HomeGridView(Context paramContext)
{
super(paramContext);
}
public HomeGridView(Context paramContext, AttributeSet paramAttributeSet)
{
super(paramContext, paramAttributeSet);
}
protected void onMeasure(int paramInt1, int paramInt2)
{
super.onMeasure(paramInt1, View.MeasureSpec.makeMeasureSpec(536870911, -2147483648));
}
}
/* Location: D:\software\onekey-decompile-apk好用版本\pandalive_1.0.0.1097.apk.jar
* Qualified Name: com.panda.videolivecore.view.HomeGridView
* JD-Core Version: 0.6.1
*/
|
923f12a9d2aa61c7c78b830674a8f4c67a6f3ea6
| 1,133 |
java
|
Java
|
zheng-common/src/main/java/com/zheng/common/db/DynamicDataSource.java
|
ZORO-3/ssh
|
eae97d86ea167da3a6e5a6036fb0eaae084e6540
|
[
"MIT"
] | 56 |
2017-08-23T15:44:43.000Z
|
2021-11-16T07:45:43.000Z
|
zheng-common/src/main/java/com/zheng/common/db/DynamicDataSource.java
|
ZORO-3/ssh
|
eae97d86ea167da3a6e5a6036fb0eaae084e6540
|
[
"MIT"
] | 3 |
2021-01-21T01:43:07.000Z
|
2021-12-09T22:52:49.000Z
|
zheng-common/src/main/java/com/zheng/common/db/DynamicDataSource.java
|
ZORO-3/ssh
|
eae97d86ea167da3a6e5a6036fb0eaae084e6540
|
[
"MIT"
] | 45 |
2017-11-22T03:35:28.000Z
|
2021-11-27T05:47:27.000Z
| 21.377358 | 85 | 0.731686 | 1,001,023 |
package com.zheng.common.db;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* 动态数据源(数据源切换)
* Created by ZhangShuzheng on 2017/1/15.
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
private final static Logger _log = LoggerFactory.getLogger(DynamicDataSource.class);
private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();
@Override
protected Object determineCurrentLookupKey() {
String dataSource = getDataSource();
_log.info("当前操作使用的数据源:{}", dataSource);
return dataSource;
}
/**
* 设置数据源
* @param dataSource
*/
public static void setDataSource(String dataSource) {
contextHolder.set(dataSource);
}
/**
* 获取数据源
* @return
*/
public static String getDataSource() {
String dataSource = contextHolder.get();
// 如果没有指定数据源,使用默认数据源
if (null == dataSource) {
DynamicDataSource.setDataSource(DataSourceEnum.MASTER.getDefault());
}
return contextHolder.get();
}
/**
* 清除数据源
*/
public static void clearDataSource() {
contextHolder.remove();
}
}
|
923f12d05c2e81056d4c2335833919c6ec9b83b4
| 8,527 |
java
|
Java
|
exec/java-exec/src/test/java/org/apache/drill/exec/store/TestImplicitFileColumns.java
|
idvp-project/drill
|
94e86d19407b0a66cfe432f45fb91a880eae4ea9
|
[
"Apache-2.0"
] | 1,510 |
2015-01-04T01:35:19.000Z
|
2022-03-28T23:36:02.000Z
|
exec/java-exec/src/test/java/org/apache/drill/exec/store/TestImplicitFileColumns.java
|
idvp-project/drill
|
94e86d19407b0a66cfe432f45fb91a880eae4ea9
|
[
"Apache-2.0"
] | 1,979 |
2015-01-28T03:18:38.000Z
|
2022-03-31T13:49:32.000Z
|
exec/java-exec/src/test/java/org/apache/drill/exec/store/TestImplicitFileColumns.java
|
idvp-project/drill
|
94e86d19407b0a66cfe432f45fb91a880eae4ea9
|
[
"Apache-2.0"
] | 940 |
2015-01-01T01:39:39.000Z
|
2022-03-25T08:46:59.000Z
| 38.237668 | 147 | 0.693679 | 1,001,024 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.store;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.drill.common.types.TypeProtos;
import org.apache.drill.exec.record.BatchSchema;
import org.apache.drill.exec.record.BatchSchemaBuilder;
import org.apache.drill.exec.record.metadata.SchemaBuilder;
import org.apache.drill.exec.util.JsonStringArrayList;
import org.apache.drill.exec.util.Text;
import org.apache.drill.shaded.guava.com.google.common.base.Charsets;
import org.apache.drill.shaded.guava.com.google.common.io.Files;
import org.apache.drill.test.BaseTestQuery;
import org.junit.BeforeClass;
import org.junit.Test;
public class TestImplicitFileColumns extends BaseTestQuery {
public static final String CSV = "csv";
public static final String MAIN = "main";
public static final String NESTED = "nested";
public static final String MAIN_FILE = MAIN + "." + CSV;
public static final String NESTED_FILE = NESTED + "." + CSV;
public static final Path FILES = Paths.get("files");
public static final Path NESTED_DIR = FILES.resolve(NESTED);
public static final Path JSON_TBL = Paths.get("scan", "jsonTbl"); // 1990/1.json : {id:100, name: "John"}, 1991/2.json : {id: 1000, name : "Joe"}
public static final Path PARQUET_TBL = Paths.get("multilevel", "parquet"); // 1990/Q1/orders_1990_q1.parquet, ...
public static final Path PARQUET_CHANGE_TBL = Paths.get("multilevel", "parquetWithSchemaChange");
public static final Path CSV_TBL = Paths.get("multilevel", "csv"); // 1990/Q1/orders_1990_q1.csv, ..
@SuppressWarnings("serial")
private static final JsonStringArrayList<Text> mainColumnValues = new JsonStringArrayList<Text>() {{
add(new Text(MAIN));
}};
@SuppressWarnings("serial")
private static final JsonStringArrayList<Text> nestedColumnValues = new JsonStringArrayList<Text>() {{
add(new Text(NESTED));
}};
private static File mainFile;
private static File nestedFile;
@BeforeClass
public static void setup() throws Exception {
File files = dirTestWatcher.makeRootSubDir(FILES);
mainFile = new File(files, MAIN_FILE);
Files.asCharSink(mainFile, Charsets.UTF_8).write(MAIN);
File nestedFolder = new File(files, NESTED);
nestedFolder.mkdirs();
nestedFile = new File(nestedFolder, NESTED_FILE);
Files.asCharSink(nestedFile, Charsets.UTF_8).write(NESTED);
dirTestWatcher.copyResourceToRoot(JSON_TBL);
dirTestWatcher.copyResourceToRoot(PARQUET_TBL);
dirTestWatcher.copyResourceToRoot(CSV_TBL);
dirTestWatcher.copyResourceToRoot(PARQUET_CHANGE_TBL);
}
@Test
public void testImplicitColumns() throws Exception {
testBuilder()
.sqlQuery("select *, filename, suffix, fqn, filepath from dfs.`%s` order by filename", FILES)
.ordered()
.baselineColumns("columns", "dir0", "filename", "suffix", "fqn", "filepath")
.baselineValues(mainColumnValues, null, mainFile.getName(), CSV, mainFile.getCanonicalPath(), mainFile.getParentFile().getCanonicalPath())
.baselineValues(nestedColumnValues, NESTED, NESTED_FILE, CSV, nestedFile.getCanonicalPath(), nestedFile.getParentFile().getCanonicalPath())
.go();
}
@Test
public void testImplicitColumnInWhereClause() throws Exception {
testBuilder()
.sqlQuery("select * from dfs.`%s` where filename = '%s'", NESTED_DIR, NESTED_FILE)
.unOrdered()
.baselineColumns("columns")
.baselineValues(nestedColumnValues)
.go();
}
@Test
public void testImplicitColumnAlone() throws Exception {
testBuilder()
.sqlQuery("select filename from dfs.`%s`", NESTED_DIR)
.unOrdered()
.baselineColumns("filename")
.baselineValues(NESTED_FILE)
.go();
}
@Test
public void testImplicitColumnWithTableColumns() throws Exception {
testBuilder()
.sqlQuery("select columns, filename from dfs.`%s`", NESTED_DIR)
.unOrdered()
.baselineColumns("columns", "filename")
.baselineValues(nestedColumnValues, NESTED_FILE)
.go();
}
@Test
public void testCountStarWithImplicitColumnsInWhereClause() throws Exception {
testBuilder()
.sqlQuery("select count(*) as cnt from dfs.`%s` where filename = '%s'", NESTED_DIR, NESTED_FILE)
.unOrdered()
.baselineColumns("cnt")
.baselineValues(1L)
.go();
}
@Test
public void testImplicitAndPartitionColumnsInSelectClause() throws Exception {
testBuilder()
.sqlQuery("select dir0, filename from dfs.`%s` order by filename", FILES)
.ordered()
.baselineColumns("dir0", "filename")
.baselineValues(null, MAIN_FILE)
.baselineValues(NESTED, NESTED_FILE)
.go();
}
@Test
public void testImplicitColumnsForParquet() throws Exception {
testBuilder()
.sqlQuery("select filename, suffix from cp.`tpch/region.parquet` limit 1")
.unOrdered()
.baselineColumns("filename", "suffix")
.baselineValues("region.parquet", "parquet")
.go();
}
@Test // DRILL-4733
public void testMultilevelParquetWithSchemaChange() throws Exception {
try {
test("alter session set `planner.enable_decimal_data_type` = true");
testBuilder()
.sqlQuery("select max(dir0) as max_dir from dfs.`%s`", PARQUET_CHANGE_TBL)
.unOrdered()
.baselineColumns("max_dir")
.baselineValues("voter50")
.go();
} finally {
test("alter session set `planner.enable_decimal_data_type` = false");
}
}
@Test
public void testStarColumnJson() throws Exception {
SchemaBuilder schemaBuilder = new SchemaBuilder()
.addNullable("dir0", TypeProtos.MinorType.VARCHAR)
.addNullable("id", TypeProtos.MinorType.BIGINT)
.addNullable("name", TypeProtos.MinorType.VARCHAR);
final BatchSchema expectedSchema = new BatchSchemaBuilder()
.withSchemaBuilder(schemaBuilder)
.build();
testBuilder()
.sqlQuery("select * from dfs.`%s` ", JSON_TBL)
.schemaBaseLine(expectedSchema)
.build()
.run();
}
@Test
public void testStarColumnParquet() throws Exception {
SchemaBuilder schemaBuilder = new SchemaBuilder()
.addNullable("dir0", TypeProtos.MinorType.VARCHAR)
.addNullable("dir1", TypeProtos.MinorType.VARCHAR)
.add("o_orderkey", TypeProtos.MinorType.INT)
.add("o_custkey", TypeProtos.MinorType.INT)
.add("o_orderstatus", TypeProtos.MinorType.VARCHAR)
.add("o_totalprice", TypeProtos.MinorType.FLOAT8)
.add("o_orderdate", TypeProtos.MinorType.DATE)
.add("o_orderpriority", TypeProtos.MinorType.VARCHAR)
.add("o_clerk", TypeProtos.MinorType.VARCHAR)
.add("o_shippriority", TypeProtos.MinorType.INT)
.add("o_comment", TypeProtos.MinorType.VARCHAR);
final BatchSchema expectedSchema = new BatchSchemaBuilder()
.withSchemaBuilder(schemaBuilder)
.build();
testBuilder()
.sqlQuery("select * from dfs.`%s` ", PARQUET_TBL)
.schemaBaseLine(expectedSchema)
.build()
.run();
}
@Test
public void testStarColumnCsv() throws Exception {
SchemaBuilder schemaBuilder = new SchemaBuilder()
.addArray("columns", TypeProtos.MinorType.VARCHAR)
.addNullable("dir0", TypeProtos.MinorType.VARCHAR)
.addNullable("dir1", TypeProtos.MinorType.VARCHAR);
final BatchSchema expectedSchema = new BatchSchemaBuilder()
.withSchemaBuilder(schemaBuilder)
.build();
testBuilder()
.sqlQuery("select * from dfs.`%s` ", CSV_TBL)
.schemaBaseLine(expectedSchema)
.build()
.run();
}
}
|
923f1434fa072ebd7d63b659d0586dc598addef8
| 6,611 |
java
|
Java
|
framework/FSF-Core/src/main/java/de/bright_side/filesystemfacade/facade/FSFFileWithInnerFile.java
|
pheyse/FileSystemFacade
|
f0b7c90fbd3da760e8143ca7ca89def82b1e2838
|
[
"Apache-2.0"
] | 2 |
2019-09-16T18:01:16.000Z
|
2021-02-05T18:28:44.000Z
|
framework/FSF-Core/src/main/java/de/bright_side/filesystemfacade/facade/FSFFileWithInnerFile.java
|
pheyse/FileSystemFacade
|
f0b7c90fbd3da760e8143ca7ca89def82b1e2838
|
[
"Apache-2.0"
] | null | null | null |
framework/FSF-Core/src/main/java/de/bright_side/filesystemfacade/facade/FSFFileWithInnerFile.java
|
pheyse/FileSystemFacade
|
f0b7c90fbd3da760e8143ca7ca89def82b1e2838
|
[
"Apache-2.0"
] | null | null | null | 23.196491 | 125 | 0.760702 | 1,001,025 |
package de.bright_side.filesystemfacade.facade;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedSet;
import de.bright_side.filesystemfacade.util.FSFFileUtil;
import de.bright_side.filesystemfacade.util.ListDirFormatting;
/**
* @author Philip Heyse
*
*/
abstract public class FSFFileWithInnerFile implements FSFFile{
private FSFFile innerFile;
public FSFFileWithInnerFile(FSFFile innerFile) {
this.innerFile = innerFile;
}
@Override
public int compareTo(FSFFile o) {
return innerFile.compareTo(o);
}
@Override
public List<FSFFile> listFiles() {
List<FSFFile> innerResult = innerFile.listFiles();
if (innerResult == null) {
return null;
}
List<FSFFile> result = new ArrayList<FSFFile>();
for (FSFFile i: innerResult) {
result.add(wrap(i));
}
return result;
}
@Override
public String getName() {
return innerFile.getName();
}
@Override
public long getTimeLastModified() throws Exception{
return innerFile.getTimeLastModified();
}
@Override
public long getTimeCreated() throws Exception {
return innerFile.getTimeCreated();
}
@Override
public boolean isFile() {
return innerFile.isFile();
}
@Override
public boolean isDirectory() {
return innerFile.isDirectory();
}
@Override
public boolean exists() {
return innerFile.exists();
}
@Override
public FSFFile getParentFile() {
return wrap(innerFile.getParentFile());
}
@Override
public OutputStream getOutputStream(boolean append) throws Exception {
return innerFile.getOutputStream(append);
}
@Override
public InputStream getInputStream() throws Exception {
return innerFile.getInputStream();
}
@Override
public void rename(String newName) throws Exception {
innerFile.rename(newName);
}
@Override
public FSFFile getChild(String name) {
return wrap(innerFile.getChild(name));
}
@Override
public FSFFile mkdirs() throws Exception {
return wrap(innerFile.mkdirs());
}
@Override
public FSFFile mkdir() throws Exception {
return wrap(innerFile.mkdir());
}
@Override
public String getAbsolutePath() {
return innerFile.getAbsolutePath();
}
@Override
public void delete() throws Exception {
innerFile.delete();
}
@Override
abstract public FSFSystem getFSFSystem() ;
// return wrap(innerFile).getFSFSystem();
// }
@Override
public <K> K readObject(Class<K> classType) throws Exception {
return innerFile.readObject(classType);
}
@Override
public <K> FSFFile writeObject(K objectToWrite) throws Exception {
return wrap(innerFile.writeObject(objectToWrite));
}
@Override
public void moveTo(FSFFile otherFile) throws Exception {
innerFile.moveTo(otherFile);
}
@Override
public void copyTo(FSFFile destFile) throws Exception {
innerFile.copyTo(destFile);
destFile.setVersion(getVersion(false));
}
@Override
public long getLength() {
return innerFile.getLength();
}
@Override
public String listDirAsString(ListDirFormatting formatting) {
return innerFile.listDirAsString(formatting);
}
@Override
public byte[] readBytes() throws Exception {
return innerFile.readBytes();
}
@Override
public void copyFilesTree(FSFFile dest) throws Exception {
FSFFileUtil.copyFilesTree(this, dest, true);
}
@Override
public void deleteTree() throws Exception {
innerFile.deleteTree();
}
@Override
public List<FSFFile> listFilesTree() throws Exception {
List<FSFFile> innerResult = innerFile.listFilesTree();
if (innerResult == null) {
return null;
}
List<FSFFile> result = new ArrayList<FSFFile>();
for (FSFFile i: innerResult) {
result.add(wrap(i));
}
return result;
}
@Override
public void setTimeLastModified(long timeLastModified) throws Exception {
innerFile.setTimeLastModified(timeLastModified);
}
@Override
public FSFFile writeBytes(boolean append, byte[] bytes) throws Exception {
return wrap(innerFile.writeBytes(append, bytes));
}
@Override
public FSFFile writeString(String string) throws Exception {
return wrap(innerFile.writeString(string));
}
@Override
public String readString() throws Exception {
return innerFile.readString();
}
@Override
public SortedSet<Long> getHistoryTimes() throws Exception{
return innerFile.getHistoryTimes();
}
@Override
public void copyHistoryFilesTree(FSFFile dest, long version) throws Exception {
innerFile.copyHistoryFilesTree(dest, version);
}
@Override
public InputStream getHistoryInputStream(long version) throws Exception {
return innerFile.getHistoryInputStream(version);
}
@Override
public VersionedData<InputStream> getInputStreamAndVersion() throws Exception {
return innerFile.getInputStreamAndVersion();
}
@Override
public OutputStream getOutputStreamForVersion(boolean append, long newVersion) throws WrongVersionException, Exception {
return innerFile.getOutputStreamForVersion(append, newVersion);
}
@Override
public <K> VersionedData<K> readObjectAndVersion(Class<K> classType) throws Exception {
return innerFile.readObjectAndVersion(classType);
}
@Override
public <K> FSFFile writeObjectForVersion(K objectToWrite, long newVersion) throws WrongVersionException, Exception {
return wrap(innerFile.writeObjectForVersion(objectToWrite, newVersion));
}
@Override
public VersionedData<byte[]> readBytesAndVersion() throws Exception {
return innerFile.readBytesAndVersion();
}
@Override
public FSFFile writeBytesForVersion(boolean append, byte[] bytes, long newVersion) throws WrongVersionException, Exception {
return wrap(innerFile.writeBytesForVersion(append, bytes, newVersion));
}
@Override
public long getVersion() throws Exception {
return innerFile.getVersion();
}
@Override
public long getVersion(boolean allowCache) throws Exception {
return innerFile.getVersion(allowCache);
}
@Override
public void setVersion(long version) throws Exception {
innerFile.setVersion(version);
}
@Override
public VersionedData<String> readStringAndVersion() throws Exception {
return innerFile.readStringAndVersion();
}
@Override
public FSFFile writeStringForVersion(String string, long newVersion) throws WrongVersionException, Exception {
return wrap(innerFile.writeStringForVersion(string, newVersion));
}
@Override
public boolean setTimeCreated(long timeCreated) throws Exception {
return innerFile.setTimeCreated(timeCreated);
}
public FSFFile getInnerFile() {
return innerFile;
}
public void setInnerFile(FSFFile innerFile) {
this.innerFile = innerFile;
}
abstract protected FSFFile wrap(FSFFile innerFile);
}
|
923f14f8cd8dba1ad66b8d7bf5c048aac3d3efe0
| 4,682 |
java
|
Java
|
src/main/java/com/enterprisepasswordsafe/ui/web/servletfilter/HeaderParameterFilter.java
|
sottolski/enterprisepasswordsafe
|
1d40bdb2e9d951a5747271aa0fb5d2bd0111acd8
|
[
"ISC"
] | 3 |
2017-09-02T13:13:27.000Z
|
2019-04-30T09:35:18.000Z
|
src/main/java/com/enterprisepasswordsafe/ui/web/servletfilter/HeaderParameterFilter.java
|
ImaginaryLandscape/enterprisepasswordsafe
|
1128a16002263735a46c566d9570e762f0b2f993
|
[
"0BSD"
] | 12 |
2020-08-21T06:38:01.000Z
|
2021-02-12T11:55:22.000Z
|
src/main/java/com/enterprisepasswordsafe/ui/web/servletfilter/HeaderParameterFilter.java
|
ImaginaryLandscape/enterprisepasswordsafe
|
1128a16002263735a46c566d9570e762f0b2f993
|
[
"0BSD"
] | 3 |
2018-09-07T17:18:38.000Z
|
2021-01-27T04:43:25.000Z
| 31.099338 | 117 | 0.72253 | 1,001,026 |
/*
* Copyright (c) 2017 Carbon Security Ltd. <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.enterprisepasswordsafe.ui.web.servletfilter;
import com.enterprisepasswordsafe.database.ConfigurationDAO;
import com.enterprisepasswordsafe.database.ConfigurationListenersDAO;
import com.enterprisepasswordsafe.database.ConfigurationOption;
import com.enterprisepasswordsafe.engine.Repositories;
import com.enterprisepasswordsafe.engine.utils.DateFormatter;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public final class HeaderParameterFilter
implements Filter, ConfigurationListenersDAO.ConfigurationListener {
/**
* The timeout parameter.
*/
public static final String TIMEOUT_PARAMETER = "timeout";
/**
* The timeout for the cached values.
*/
private static final long CACHE_TIMEOUT = 60000; // 1 minute.
/**
* The last update for the cache.
*/
private static long cacheLastUpdate = 0;
/**
* The cahced session timeout value.
*/
private static String sessionTimeoutCache;
/**
* The object used to synchroized the fetching of the
* stylesheet URL.
*/
private static final Object SYNC_OBJECT = new Object();
@Override
public void init(final FilterConfig config) {
setTimeout(ConfigurationOption.SESSION_TIMEOUT.getDefaultValue());
ConfigurationListenersDAO.addListener(ConfigurationOption.SESSION_TIMEOUT.getPropertyName(), this);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain next) throws IOException, ServletException {
long now = System.currentTimeMillis();
if( now - cacheLastUpdate > CACHE_TIMEOUT ) {
updateCachedTimeout();
}
request.setAttribute(TIMEOUT_PARAMETER, sessionTimeoutCache);
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.addHeader("Cache-Control", "no-cache, no-store, must-revalidate, max-age=0");
httpResponse.addHeader("Expires", "0");
httpResponse.addHeader("Pragma", "no-cache");
httpResponse.addHeader("X-Frame-Options", "DENY");
httpResponse.addHeader("Content-Security-Policy", "default-src 'self'; frame-src 'none'; object-src 'none'");
next.doFilter(request, response);
}
@Override
public void destroy() {
}
private void updateCachedTimeout() {
synchronized(SYNC_OBJECT) {
long now = System.currentTimeMillis();
if( now - cacheLastUpdate > CACHE_TIMEOUT ) {
try {
updateParameters();
} catch(SQLException sqle) {
Logger.
getLogger(getClass().toString()).
log(Level.SEVERE, "Error updating parameters", sqle);
}
}
cacheLastUpdate = System.currentTimeMillis();
}
}
private void updateParameters()
throws SQLException {
// Don't try to refresh using an invalid database pool
if( ! Repositories.databasePoolFactory.isConfigured() ) {
return;
}
updateTimeout();
}
public void updateTimeout()
throws SQLException {
String sessionTimeout = ConfigurationDAO.getValue(ConfigurationOption.SESSION_TIMEOUT);
if (sessionTimeout != null && sessionTimeout.length() > 0) {
setTimeout(sessionTimeout);
}
}
private static synchronized void setTimeout(String timeout) {
try {
int value = Integer.parseInt(timeout) - 1;
value *= DateFormatter.MILLIS_IN_MINUTE;
sessionTimeoutCache = Integer.toString(value);
} catch (Exception ex) {
Logger.
getAnonymousLogger().
log(Level.SEVERE, "Error updating timeout cache", ex);
}
}
@Override
public void configurationChange(String propertyName, String propertyValue) {
if ( propertyName.equals(ConfigurationOption.SESSION_TIMEOUT.getPropertyName()) ) {
setTimeout( propertyValue );
}
}
}
|
923f1611e4afd000bb48807301689cc77d7aec12
| 8,527 |
java
|
Java
|
java/apiexamples/src/main/java/io/statx/examples/StockExample.java
|
StatXApp/statx-api-examples
|
889484e64b59f94caaa1721a126c3a03e3b9135a
|
[
"Apache-2.0"
] | null | null | null |
java/apiexamples/src/main/java/io/statx/examples/StockExample.java
|
StatXApp/statx-api-examples
|
889484e64b59f94caaa1721a126c3a03e3b9135a
|
[
"Apache-2.0"
] | null | null | null |
java/apiexamples/src/main/java/io/statx/examples/StockExample.java
|
StatXApp/statx-api-examples
|
889484e64b59f94caaa1721a126c3a03e3b9135a
|
[
"Apache-2.0"
] | null | null | null | 49.005747 | 116 | 0.654861 | 1,001,027 |
/**
* Copyright 2016 StatX Inc.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for
* the specific language governing permissions and limitations under the License.
*/
package io.statx.examples;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import io.statx.rest.StatXClient;
import io.statx.rest.api.GroupsApi;
import io.statx.rest.api.StatsApi;
import io.statx.rest.model.*;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Example to show how to create/update a horizontal bars stat through the StatX REST API.
*
* Prerequisite: Download the StatX app from the appstore (IOS) or playstore (android) and sign up.
*
* Build it with maven with:
* mvn clean compile
*
* Call it with maven with:
* mvn exec:java -Dexec.mainClass="io.statx.examples.StockExample" -Dexec.args="
* <ClientName> <Phone Number in international format> <Stat Title> <Update Frequency in Minutes>"
*
* For instance:
* mvn exec:java -Dexec.mainClass="io.statx.examples.StockExample" -Dexec.args="
* testclient +16509999999 StockExample 2"
*/
public class StockExample {
public static void main(String[] args) throws Exception {
if (args.length < 3) {
System.out.println("Usage java io.statx.examples.StockExample <ClientName> " +
"<PhoneNumber Int Format> <StatTitle> <FrequencyInMinutes>");
System.exit(-1);
}
String clientName = args[0];
String phoneNumber = args[1];
String statTitle = args[2];
int frequencyInMinutes = Integer.parseInt(args[3]);
// Lets sign up through the rest API and get an AuthToken. Once you get the credentials
// you should save them somewhere safe for use at a later time.
StatXClient statXClient = new StatXClient();
StatXClient.UserCredential userCredential = statXClient.getCredentials(clientName, phoneNumber);
// Repeat once every <frequency minutes> (see parameter below).
while (true) {
// Find the group with the stat. If the group does not exist then create it.
//
// Note: The group name is not unique. In general it is not a good idea to use the group
// name as a key to determine whether the group exists or not. If possible use the
// groupid instead.
String groupName = "StatX-API-Examples";
GroupsApi groupsApi = statXClient.getGroupsApi(userCredential);
GroupList groupList = groupsApi.getGroups(groupName);
Group group;
if ((groupList == null) || (groupList.getData() == null) || (groupList.getData().isEmpty())) {
// The group does not exist. Let's create one. Since we are creating the group
// the api will add the current user as a member and admin of the group.
group = new Group();
group.setName(groupName);
group = groupsApi.createGroup(group);
} else {
// Pick the first group (should be the only one).
group = groupList.getData().get(0);
}
// Find the stat by name. If the stat does not exist then create it.
//
// Note: The stat title is not unique. In general it is not a good idea to use
// the stat title as a key to determine whether the stat exists or not. If possible
// use the statid instead.
StatsApi statsApi = statXClient.getStatsApi(userCredential);
StatList statList = statsApi.getStats(group.getName(), statTitle);
if ((statList == null) || (statList.getData() == null) || (statList.getData().isEmpty())) {
// The stat does not exist. Let's create it.
HorizontalBarStat horizontalBarStat = new HorizontalBarStat();
horizontalBarStat.setTitle(statTitle);
horizontalBarStat.setVisualType(Stat.VisualTypeEnum.HORIZONTAL_BARS);
horizontalBarStat.setGroupName(groupName);
horizontalBarStat.setItems(getStockInfo());
statsApi.createStat(group.getId(), horizontalBarStat);
} else {
// Pick the first stat (should be the only one) and get the statId from it.
String statId = statList.getData().get(0).getId();
// Create the stat to update the value.
HorizontalBarStat horizontalBarStat = new HorizontalBarStat();
horizontalBarStat.setItems(getStockInfo());
horizontalBarStat.setLastUpdatedDateTime(new Date(System.currentTimeMillis()));
statsApi.updateStat(group.getId(), statId, horizontalBarStat);
}
System.out.println("Last update at: " + new Date(System.currentTimeMillis()));
Thread.sleep(TimeUnit.MINUTES.toMillis(frequencyInMinutes));
}
}
/**
* Fetch a few stocks from Yahoo finance.
* @return a {@code List<HorizontalBarItem} with the details of the stock prices.
* @throws IOException
* @throws URISyntaxException
*/
private static List<HorizontalBarItem> getStockInfo() throws IOException, URISyntaxException {
List<HorizontalBarItem> results = new ArrayList<>();
int TIMEOUT_MILLIS = (int) TimeUnit.SECONDS.toMillis(30);
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(TIMEOUT_MILLIS)
.setConnectionRequestTimeout(TIMEOUT_MILLIS)
.setSocketTimeout(TIMEOUT_MILLIS).build();
HttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(config)
.setMaxConnTotal(50)
.setMaxConnPerRoute(10)
.build();
URIBuilder uriBuilder = new URIBuilder();
uriBuilder.setScheme("https").setHost("query.yahooapis.com").setPath("/v1/public/yql");
uriBuilder.addParameter("q", "select * from yahoo.finance.quotes where symbol in(" +
"\"AAPL\", \"AMZN\",\"GOOGL\")");
uriBuilder.addParameter("format","json");
uriBuilder.addParameter("env", "store://datatables.org/alltableswithkeys");
URI uri = uriBuilder.build();
HttpGet httpGet = new HttpGet(uri);
httpGet.addHeader("content-type", ContentType.APPLICATION_JSON.toString());
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
Gson gson = new Gson();
JsonObject job = gson.fromJson(
new InputStreamReader(httpResponse.getEntity().getContent()), JsonObject.class);
JsonArray jsonArray = job.getAsJsonObject("query").getAsJsonObject("results").getAsJsonArray("quote");
int colorIndex;
for (int i = 0; i < jsonArray.size(); i++) {
JsonElement jsonElement = jsonArray.get(i);
HorizontalBarItem horizontalBarItem = new HorizontalBarItem();
horizontalBarItem.setName(((JsonObject) jsonElement).get("symbol").getAsString());
horizontalBarItem.setRawValue(((JsonObject) jsonElement).get("Ask").getAsDouble());
colorIndex = i % HorizontalBarItem.ColorEnum.values().length;
horizontalBarItem.setColor(HorizontalBarItem.ColorEnum.values()[colorIndex]);
results.add(horizontalBarItem);
}
}
return results;
}
}
|
923f16489576ddf0516da4e4e5ebbadce8334383
| 680 |
java
|
Java
|
src/main/java/asw/inciProcessor/webService/responses/errors/RequiredNameIncidenceErrorResponse.java
|
Arquisoft/InciManager_e4a
|
d78814306437c86421357bd2ec412dde55b2bfbb
|
[
"Unlicense"
] | 4 |
2018-03-16T08:43:26.000Z
|
2018-05-04T08:37:20.000Z
|
src/main/java/asw/inciProcessor/webService/responses/errors/RequiredNameIncidenceErrorResponse.java
|
Arquisoft/InciManager_e4a
|
d78814306437c86421357bd2ec412dde55b2bfbb
|
[
"Unlicense"
] | 7 |
2018-03-09T09:49:39.000Z
|
2018-05-01T05:10:36.000Z
|
src/main/java/asw/inciProcessor/webService/responses/errors/RequiredNameIncidenceErrorResponse.java
|
Arquisoft/InciManager_e4a
|
d78814306437c86421357bd2ec412dde55b2bfbb
|
[
"Unlicense"
] | 2 |
2018-04-05T18:16:22.000Z
|
2018-05-04T08:12:48.000Z
| 28.333333 | 85 | 0.754412 | 1,001,028 |
package asw.inciProcessor.webService.responses.errors;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Incidence name is required")
public class RequiredNameIncidenceErrorResponse extends ErrorResponse{
private static final long serialVersionUID = 1L;
@Override
public String getMessageJSONFormat() {
// TODO Auto-generated method stub
return "{\"reason\": \"Incidence name is required\"}";
}
@Override
public String getMessageStringFormat() {
// TODO Auto-generated method stub
return "Incidence name is required";
}
}
|
923f1784d42c66d4848947a46b738b5ed1c58dd7
| 1,132 |
java
|
Java
|
core/src/main/java/de/mirkosertic/bytecoder/core/BytecodeSourceFileAttributeInfo.java
|
Suyashtnt/Bytecoder
|
d957081d50f2d30b3206447b805b1ca9da69c8c2
|
[
"Apache-2.0"
] | 543 |
2017-06-14T14:53:33.000Z
|
2022-03-23T14:18:09.000Z
|
core/src/main/java/de/mirkosertic/bytecoder/core/BytecodeSourceFileAttributeInfo.java
|
Suyashtnt/Bytecoder
|
d957081d50f2d30b3206447b805b1ca9da69c8c2
|
[
"Apache-2.0"
] | 381 |
2017-10-31T14:29:54.000Z
|
2022-03-25T15:27:27.000Z
|
core/src/main/java/de/mirkosertic/bytecoder/core/BytecodeSourceFileAttributeInfo.java
|
Suyashtnt/Bytecoder
|
d957081d50f2d30b3206447b805b1ca9da69c8c2
|
[
"Apache-2.0"
] | 50 |
2018-01-06T12:35:14.000Z
|
2022-03-13T14:54:33.000Z
| 35.375 | 108 | 0.749117 | 1,001,029 |
/*
* Copyright 2019 Mirko Sertic
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.mirkosertic.bytecoder.core;
public class BytecodeSourceFileAttributeInfo implements BytecodeAttributeInfo {
private final BytecodeConstantPool constantPool;
private final int nameIndex;
public BytecodeSourceFileAttributeInfo(final BytecodeConstantPool aConstantPool, final int aNameIndex) {
constantPool = aConstantPool;
nameIndex = aNameIndex;
}
public String getFileName() {
return ((BytecodeUtf8Constant)constantPool.constantByIndex(nameIndex - 1)).stringValue();
}
}
|
923f183f0014464d0f7dcd799550a45dec0bf45d
| 797 |
java
|
Java
|
elastic-config-console/src/main/java/com/github/config/observer/AbstractSubject.java
|
ErinDavid/elastic-config
|
b50e10c5bf431133ba86019123675446f441d62a
|
[
"Apache-2.0"
] | 9 |
2016-10-28T14:03:52.000Z
|
2018-05-06T13:06:03.000Z
|
elastic-config-console/src/main/java/com/github/config/observer/AbstractSubject.java
|
ErinDavid/elastic-config
|
b50e10c5bf431133ba86019123675446f441d62a
|
[
"Apache-2.0"
] | null | null | null |
elastic-config-console/src/main/java/com/github/config/observer/AbstractSubject.java
|
ErinDavid/elastic-config
|
b50e10c5bf431133ba86019123675446f441d62a
|
[
"Apache-2.0"
] | 2 |
2018-05-06T13:06:05.000Z
|
2018-11-07T07:40:46.000Z
| 21.540541 | 66 | 0.598494 | 1,001,030 |
package com.github.config.observer;
import java.util.List;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
/**
* 主题通用实现
*/
public abstract class AbstractSubject implements ISubject {
/**
* 观察者列表
*/
private final List<IObserver> watchers = Lists.newArrayList();
@Override
public void register(final IObserver watcher) {
watchers.add(Preconditions.checkNotNull(watcher));
}
@Override
public void notify(final String key, final String value) {
for (final IObserver watcher : watchers) {
new Thread(new Runnable() {
@Override
public void run() {
watcher.notified(key, value);
}
}).start();
}
}
}
|
923f18b73840518c2881458325182cb519c4a313
| 520 |
java
|
Java
|
workcraft/WorkcraftCore/test-src/org/workcraft/dom/visual/MockVisualModel.java
|
anirban59/workcraft
|
1c2fb528deb79d10109d4b04cd20189ce5d081f8
|
[
"MIT"
] | 28 |
2017-10-20T22:34:37.000Z
|
2022-02-05T16:46:51.000Z
|
workcraft/WorkcraftCore/test-src/org/workcraft/dom/visual/MockVisualModel.java
|
anirban59/workcraft
|
1c2fb528deb79d10109d4b04cd20189ce5d081f8
|
[
"MIT"
] | 605 |
2017-03-04T21:41:38.000Z
|
2022-03-18T15:45:59.000Z
|
workcraft/WorkcraftCore/test-src/org/workcraft/dom/visual/MockVisualModel.java
|
anirban59/workcraft
|
1c2fb528deb79d10109d4b04cd20189ce5d081f8
|
[
"MIT"
] | 263 |
2017-03-07T14:33:38.000Z
|
2021-11-26T12:42:05.000Z
| 23.636364 | 102 | 0.740385 | 1,001,031 |
package org.workcraft.dom.visual;
import org.workcraft.dom.math.MathConnection;
import org.workcraft.dom.visual.connections.VisualConnection;
public class MockVisualModel extends AbstractVisualModel {
public MockVisualModel() {
super(new MockMathModel());
}
@Override
public void validateConnection(VisualNode first, VisualNode second) {
}
@Override
public VisualConnection connect(VisualNode first, VisualNode second, MathConnection mConnection) {
return null;
}
}
|
923f194703c01caf9ab758f25da05323c8f3c080
| 1,268 |
java
|
Java
|
LACCPlus/Zookeeper/205_2.java
|
sgholamian/log-aware-clone-detection
|
9993cb081c420413c231d1807bfff342c39aa69a
|
[
"MIT"
] | null | null | null |
LACCPlus/Zookeeper/205_2.java
|
sgholamian/log-aware-clone-detection
|
9993cb081c420413c231d1807bfff342c39aa69a
|
[
"MIT"
] | null | null | null |
LACCPlus/Zookeeper/205_2.java
|
sgholamian/log-aware-clone-detection
|
9993cb081c420413c231d1807bfff342c39aa69a
|
[
"MIT"
] | null | null | null | 39.625 | 88 | 0.506309 | 1,001,032 |
//,temp,ObserverRequestProcessor.java,125,145,temp,FollowerRequestProcessor.java,117,143
//,3
public class xxx {
void processRequest(Request request, boolean checkForUpgrade) {
if (!finished) {
if (checkForUpgrade) {
// Before sending the request, check if the request requires a
// global session and what we have is a local session. If so do
// an upgrade.
Request upgradeRequest = null;
try {
upgradeRequest = zks.checkUpgradeSession(request);
} catch (KeeperException ke) {
if (request.getHdr() != null) {
request.getHdr().setType(OpCode.error);
request.setTxn(new ErrorTxn(ke.code().intValue()));
}
request.setException(ke);
LOG.info("Error creating upgrade request", ke);
} catch (IOException ie) {
LOG.error("Unexpected error in upgrade", ie);
}
if (upgradeRequest != null) {
queuedRequests.add(upgradeRequest);
}
}
queuedRequests.add(request);
}
}
};
|
923f195446465fc80c73725dd18206d2fcfa702b
| 1,582 |
java
|
Java
|
pet-clinic-data/src/main/java/caseychen/springboot/springbootpetclinic/services/map/VetServiceMap.java
|
cshinoc/Springboot-petclinic
|
12974a90bbb8f47d9b80e051be80c30d71c31d05
|
[
"Apache-2.0"
] | 2 |
2019-08-13T23:14:10.000Z
|
2019-08-14T04:29:59.000Z
|
pet-clinic-data/src/main/java/caseychen/springboot/springbootpetclinic/services/map/VetServiceMap.java
|
cshinoc/Springboot-petclinic
|
12974a90bbb8f47d9b80e051be80c30d71c31d05
|
[
"Apache-2.0"
] | 76 |
2019-08-06T18:24:52.000Z
|
2019-08-13T23:01:01.000Z
|
pet-clinic-data/src/main/java/caseychen/springboot/springbootpetclinic/services/map/VetServiceMap.java
|
cshinoc/SpringBoot-PetClinic
|
12974a90bbb8f47d9b80e051be80c30d71c31d05
|
[
"Apache-2.0"
] | null | null | null | 28.25 | 88 | 0.685209 | 1,001,033 |
package caseychen.springboot.springbootpetclinic.services.map;
import caseychen.springboot.springbootpetclinic.model.Speciality;
import caseychen.springboot.springbootpetclinic.model.Vet;
import caseychen.springboot.springbootpetclinic.services.SpecialitiesService;
import caseychen.springboot.springbootpetclinic.services.VetService;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
@Profile({"default", "map"})
public class VetServiceMap extends AbstractMapService<Vet, Long> implements VetService {
private final SpecialitiesService specialitiesService;
public VetServiceMap(SpecialitiesService specialitiesService) {
this.specialitiesService = specialitiesService;
}
@Override
public Set<Vet> findAll() {
return super.findAll();
}
@Override
public Vet findById(Long id) {
return super.findById(id);
}
@Override
public Vet save(Vet object) {
if (object.getSpecialities().size() > 0) {
object.getSpecialities().forEach(speciality -> {
if (speciality.getId() == null) {
Speciality savedSpeciality = specialitiesService.save(speciality);
speciality.setId(savedSpeciality.getId());
}
});
}
return super.save(object);
}
@Override
public void delete(Vet object) {
super.delete(object);
}
@Override
public void deleteById(Long id) {
super.deleteById(id);
}
}
|
923f1c5775de613e1bb90c5a8b483641978e23f6
| 332 |
java
|
Java
|
panda-parent/panda-security/src/main/java/org/malagu/panda/security/service/ComponentService.java
|
SuStudent/panda
|
09a254e7028435e26b60ce3304d55ea42c5bd288
|
[
"Apache-2.0"
] | 14 |
2018-07-23T01:37:29.000Z
|
2019-02-25T06:51:34.000Z
|
panda-parent/panda-security/src/main/java/org/malagu/panda/security/service/ComponentService.java
|
SuStudent/panda
|
09a254e7028435e26b60ce3304d55ea42c5bd288
|
[
"Apache-2.0"
] | 1 |
2018-07-25T03:36:06.000Z
|
2018-07-25T03:36:06.000Z
|
panda-parent/panda-security/src/main/java/org/malagu/panda/security/service/ComponentService.java
|
SuStudent/panda
|
09a254e7028435e26b60ce3304d55ea42c5bd288
|
[
"Apache-2.0"
] | 5 |
2018-07-23T06:46:09.000Z
|
2019-10-15T07:42:38.000Z
| 15.227273 | 51 | 0.701493 | 1,001,034 |
package org.malagu.panda.security.service;
import java.util.List;
import org.malagu.panda.security.orm.Component;
/**
* 组件权限服务接口
* @author Kevin Yang (mailto:[email protected])
* @since 2016年1月30日
*/
public interface ComponentService {
/**
* 获取所有的组件(包含权限信息)
* @return 所有组件(包含权限信息)
*/
List<Component> findAll();
}
|
923f1d41bfbff364e728564880ea2ffe184719a4
| 1,527 |
java
|
Java
|
htb/fatty-10.10.10.174/fatty-client/org/springframework/context/PayloadApplicationEvent.java
|
benhunter/ctf
|
3de1a222ea0034ef15eb6b75585b03a6ee37ec37
|
[
"MIT"
] | null | null | null |
htb/fatty-10.10.10.174/fatty-client/org/springframework/context/PayloadApplicationEvent.java
|
benhunter/ctf
|
3de1a222ea0034ef15eb6b75585b03a6ee37ec37
|
[
"MIT"
] | 1 |
2022-03-31T22:44:36.000Z
|
2022-03-31T22:44:36.000Z
|
htb/fatty-10.10.10.174/fatty-client/org/springframework/context/PayloadApplicationEvent.java
|
benhunter/ctf
|
3de1a222ea0034ef15eb6b75585b03a6ee37ec37
|
[
"MIT"
] | null | null | null | 22.791045 | 143 | 0.466274 | 1,001,035 |
/* */ package org.springframework.context;
/* */
/* */ import org.springframework.core.ResolvableType;
/* */ import org.springframework.core.ResolvableTypeProvider;
/* */ import org.springframework.util.Assert;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class PayloadApplicationEvent<T>
/* */ extends ApplicationEvent
/* */ implements ResolvableTypeProvider
/* */ {
/* */ private final T payload;
/* */
/* */ public PayloadApplicationEvent(Object source, T payload) {
/* 44 */ super(source);
/* 45 */ Assert.notNull(payload, "Payload must not be null");
/* 46 */ this.payload = payload;
/* */ }
/* */
/* */
/* */
/* */ public ResolvableType getResolvableType() {
/* 52 */ return ResolvableType.forClassWithGenerics(getClass(), new ResolvableType[] { ResolvableType.forInstance(getPayload()) });
/* */ }
/* */
/* */
/* */
/* */
/* */ public T getPayload() {
/* 59 */ return this.payload;
/* */ }
/* */ }
/* Location: /home/kali/ctf/htb/fatty-10.10.10.174/ftp/fatty-client.jar!/org/springframework/context/PayloadApplicationEvent.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
923f1de0f2897d1e6adcdf03faafb31ef077f61d
| 1,208 |
java
|
Java
|
maygard/com/maygard/options/exotics/AssetOrNothingOption.java
|
odeyemis/maygard
|
b11271511e3964600f34b6abdd5139e6dbc7c589
|
[
"Artistic-2.0"
] | 21 |
2015-03-27T16:42:24.000Z
|
2021-01-19T08:37:33.000Z
|
maygard/com/maygard/options/exotics/AssetOrNothingOption.java
|
odeyemis/maygard
|
b11271511e3964600f34b6abdd5139e6dbc7c589
|
[
"Artistic-2.0"
] | 1 |
2018-06-05T17:17:27.000Z
|
2018-06-05T17:17:27.000Z
|
maygard/com/maygard/options/exotics/AssetOrNothingOption.java
|
odeyemis/maygard
|
b11271511e3964600f34b6abdd5139e6dbc7c589
|
[
"Artistic-2.0"
] | 16 |
2015-12-18T15:11:23.000Z
|
2020-01-05T08:39:39.000Z
| 23.705882 | 75 | 0.64847 | 1,001,036 |
/**
Copyright (C) 2013 Sijuola F. Odeyemi
This source code is released under the Artistic License 2.0.
Code license: http://www.opensource.org/licenses/artistic-license-2.0.php
Contact: [email protected]
*/
package com.maygard.options.exotics;
import com.maygard.core.Probnormal;
// Asset-or-nothing Option.
public class AssetOrNothingOption {
public AssetOrNothingOption(double rate, double yield, double time) {
r=rate;
crate=yield;
t=time;
b=crate==0.0?0.0:(b=crate!=r?(r-crate):r);
}
double b;
double crate;
double r;
double t;
public double assetornoPut(double s, double x, double sigma) {
return s*Math.exp((b-r)*t)*N(-d(s,x,sigma));
}
public double assetornoCall(double s, double x, double sigma) {
return s*Math.exp((b-r)*t)*N(d(s,x,sigma));
}
private double d(double s, double x, double sigma) {
double sig=(sigma*sigma);
double f= (Math.log(s/x)+((b+sig*0.5)*t))/(sigma*Math.sqrt(t));
return f;
}
private double N(double x) {
Probnormal p=new Probnormal();
double ret=x>(6.95)?1.0:x<(-6.95)?0.0:p.ncDisfnc(x);
//restrict the range of cdf values to stable values
return ret;
}
}
|
923f1e51c26de27eda50072d703b325dd6511439
| 2,762 |
java
|
Java
|
spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/FileEncodingApplicationListener.java
|
yangfancoming/spring-boot-build
|
3d4b8cbb8fea3e68617490609a68ded8f034bc67
|
[
"Apache-2.0"
] | null | null | null |
spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/FileEncodingApplicationListener.java
|
yangfancoming/spring-boot-build
|
3d4b8cbb8fea3e68617490609a68ded8f034bc67
|
[
"Apache-2.0"
] | 8 |
2020-01-31T18:21:07.000Z
|
2022-03-08T21:12:35.000Z
|
spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/FileEncodingApplicationListener.java
|
yangfancoming/spring-boot-build
|
3d4b8cbb8fea3e68617490609a68ded8f034bc67
|
[
"Apache-2.0"
] | null | null | null | 52.113208 | 163 | 0.766474 | 1,001,037 |
package org.springframework.boot.context;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
/**
* An {@link ApplicationListener} that halts application startup if the system file
* encoding does not match an expected value set in the environment. By default has no
* effect, but if you set {@code spring.mandatory_file_encoding} (or some camelCase or
* UPPERCASE variant of that) to the name of a character encoding (e.g. "UTF-8") then this
* initializer throws an exception when the {@code file.encoding} System property does not equal it.
* The System property {@code file.encoding} is normally set by the JVM in response to the
* {@code LANG} or {@code LC_ALL} environment variables. It is used (along with other
* platform-dependent variables keyed off those environment variables) to encode JVM
* arguments as well as file names and paths. In most cases you can override the file
* encoding System property on the command line (with standard JVM features), but also
* consider setting the {@code LANG} environment variable to an explicit
* character-encoding value (e.g. "en_GB.UTF-8").
*/
public class FileEncodingApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {
private static final Log logger = LogFactory.getLog(FileEncodingApplicationListener.class);
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
ConfigurableEnvironment environment = event.getEnvironment();
if (!environment.containsProperty("spring.mandatory-file-encoding")) {
return;
}
String encoding = System.getProperty("file.encoding");
String desired = environment.getProperty("spring.mandatory-file-encoding");
if (encoding != null && !desired.equalsIgnoreCase(encoding)) {
logger.error("System property 'file.encoding' is currently '" + encoding + "'. It should be '" + desired + "' (as defined in 'spring.mandatoryFileEncoding').");
logger.error("Environment variable LANG is '" + System.getenv("LANG") + "'. You could use a locale setting that matches encoding='"+ desired + "'.");
logger.error("Environment variable LC_ALL is '" + System.getenv("LC_ALL") + "'. You could use a locale setting that matches encoding='" + desired + "'.");
throw new IllegalStateException("The Java Virtual Machine has not been configured to use the desired default character encoding (" + desired + ").");
}
}
}
|
923f1f15802c4eeab12167121762a576d7091807
| 89 |
java
|
Java
|
src/main/java/helloworld/hmrc/camel/ServerProcessingError.java
|
publicmayhem/hmrc-hello-world-camel
|
b519626dbf6e31c170d1469b0467798d3c4bb9f2
|
[
"MIT"
] | null | null | null |
src/main/java/helloworld/hmrc/camel/ServerProcessingError.java
|
publicmayhem/hmrc-hello-world-camel
|
b519626dbf6e31c170d1469b0467798d3c4bb9f2
|
[
"MIT"
] | null | null | null |
src/main/java/helloworld/hmrc/camel/ServerProcessingError.java
|
publicmayhem/hmrc-hello-world-camel
|
b519626dbf6e31c170d1469b0467798d3c4bb9f2
|
[
"MIT"
] | null | null | null | 17.8 | 54 | 0.831461 | 1,001,038 |
package helloworld.hmrc.camel;
public class ServerProcessingError extends Exception {
}
|
923f1fb4771a53b8a600001cffb622f9f65e0cc2
| 1,720 |
java
|
Java
|
ICS3UE.90/StructuredProgramming/Activity 6/ThreeDigitRodC.java
|
cam-rod/classic-scripts
|
9eaf13cf70cdc133e6c00ea92fac5dcaea356b6a
|
[
"MIT"
] | null | null | null |
ICS3UE.90/StructuredProgramming/Activity 6/ThreeDigitRodC.java
|
cam-rod/classic-scripts
|
9eaf13cf70cdc133e6c00ea92fac5dcaea356b6a
|
[
"MIT"
] | null | null | null |
ICS3UE.90/StructuredProgramming/Activity 6/ThreeDigitRodC.java
|
cam-rod/classic-scripts
|
9eaf13cf70cdc133e6c00ea92fac5dcaea356b6a
|
[
"MIT"
] | null | null | null | 26.875 | 135 | 0.62907 | 1,001,039 |
/**
* "The Number Sum Calculator"
*
* This program calaculates and displays the sum of a positive three digit interger.
*
* @author Cameron Rodriguez
* @version 1.0 07/09/17
*/
//Importing toolkits
import java.io.*;
import javax.swing.*; //ONE OUTPUT ONLY
public class ThreeDigitRodC {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//Declaring the variables
int threeDigInt, twoDigInt;
int ones, tens, hundreds;
int intSum;
/**
* Get the three digit integer from user
*
* @param threeDigInt the three digit interger
* @return the three digit interger
*/
String numinput = JOptionPane.showInputDialog ("Welcome to the Number Sum Calculator!" + "\n\nPlease enter a three digit number:");
threeDigInt = Integer.parseInt (numinput);
/**
* Determine value of each digit
*
* @param ones the ones place digit of threeDigInt
* @param twoDigInt the first two digits of threeDigInt
* @param tens the tens place digit of threeDigInt
* @param hundreds the hundreds place digit of threeDigInt
* @return the value of each digit
*/
ones = threeDigInt % 10;
twoDigInt = threeDigInt / 10;
tens = twoDigInt % 10;
hundreds = twoDigInt / 10;
/**
* Calculate the sum of the the digits
*
* @param intSum the sum of all digits
* @return the sum of the digits
*/
intSum = ones + tens + hundreds;
/**
* Displays sum of digits to user
*/
System.out.println ("When the digits of the number " + threeDigInt + " are added,");
System.out.println ("the sum is " + intSum + ".");
}
}
|
923f1fd73314507b5772e1d57f567d6414b387d4
| 4,405 |
java
|
Java
|
src/test/java/be/yildizgames/module/graphic/gui/DummyGuiFactory.java
|
yildiz-online/module-graphic
|
1eb1effccfb365b0eac14afbbc6fa2dff3cc546b
|
[
"MIT"
] | null | null | null |
src/test/java/be/yildizgames/module/graphic/gui/DummyGuiFactory.java
|
yildiz-online/module-graphic
|
1eb1effccfb365b0eac14afbbc6fa2dff3cc546b
|
[
"MIT"
] | 26 |
2018-11-12T20:29:14.000Z
|
2022-02-17T07:33:14.000Z
|
src/test/java/be/yildizgames/module/graphic/gui/DummyGuiFactory.java
|
yildiz-online/module-graphic
|
1eb1effccfb365b0eac14afbbc6fa2dff3cc546b
|
[
"MIT"
] | null | null | null | 37.016807 | 143 | 0.715096 | 1,001,040 |
/*
* This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT)
*
* Copyright (c) 2019 Grégory Van den Borre
*
* More infos available: https://engine.yildiz-games.be
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package be.yildizgames.module.graphic.gui;
import be.yildizgames.module.color.Color;
import be.yildizgames.module.coordinates.Coordinates;
import be.yildizgames.module.graphic.Font;
import be.yildizgames.module.graphic.gui.container.Container;
import be.yildizgames.module.graphic.gui.element.AbstractIconElement;
import be.yildizgames.module.graphic.gui.element.AbstractTextElement;
import be.yildizgames.module.graphic.gui.internal.impl.SimpleContainer;
import be.yildizgames.module.graphic.gui.internal.impl.StandardGuiFactory;
import be.yildizgames.module.graphic.material.Material;
import be.yildizgames.module.graphic.material.MaterialEffect;
import be.yildizgames.module.graphic.material.MaterialEffect.EffectType;
import be.yildizgames.module.graphic.material.MaterialTechnique;
import be.yildizgames.module.window.ScreenSize;
import java.time.Duration;
import java.util.Arrays;
/**
* @author Grégory Van den Borre
*/
public class DummyGuiFactory extends StandardGuiFactory {
public static final Font defaultFont = new Font("default", 0, Color.BLACK) {
@Override
protected void loadImpl() {
float[] widthArray = new float[256];
Arrays.fill(widthArray, 1.0f);
this.setCharWidth(widthArray);
}
};
public static final Material empty = new Material(Material.EMPTY_NAME) {
@Override
protected void loadImpl() {
//Empty method.
}
@Override
protected void receiveShadowImpl(boolean receive) {
//Empty method.
}
@Override
protected MaterialTechnique createTechniqueImpl(int techniqueIndex) {
// TODO Auto-generated method stub
return null;
}
@Override
protected Material copyImpl(String name) {
return this;
}
@Override
public MaterialEffect addEffect(EffectType type, long time) {
return new MaterialEffect(this, Duration.ofMillis(time)) {
@Override
protected void executeImpl(Material material) {
}
};
}
};
public DummyGuiFactory() {
super(new ScreenSize(1024, 768));
defaultFont.load();
}
@Override
protected AbstractIconElement buildIconElement(String name, Coordinates coordinates, Material material, Container container) {
return new DummyIconElement(name, coordinates, material);
}
@Override
protected AbstractTextElement buildTextElement(Coordinates coordinates, Font font, Container container) {
return new DummyTextElement(coordinates, font);
}
@Override
public SimpleContainer buildContainerElement(String name, Coordinates coordinates, Material background) {
return new DummyGuiContainer(name, coordinates, background);
}
@Override
public SimpleContainer buildContainerElement(String name, Coordinates coordinates, Material background, Container parent, boolean widget) {
return new DummyGuiContainer(name, coordinates, background, parent, widget);
}
}
|
923f208c2f77a870182f818c12029c90011258e6
| 333 |
java
|
Java
|
spring-aop/src/main/java/com/baeldung/aspectj/Secured.java
|
adrhc/tutorials
|
84cd9d8fdc23beb4fa552ba9c5fd8d9df292c4c4
|
[
"MIT"
] | 32,544 |
2015-01-02T16:59:22.000Z
|
2022-03-31T21:04:05.000Z
|
spring-aop/src/main/java/com/baeldung/aspectj/Secured.java
|
adrhc/tutorials
|
84cd9d8fdc23beb4fa552ba9c5fd8d9df292c4c4
|
[
"MIT"
] | 1,577 |
2015-02-21T17:47:03.000Z
|
2022-03-31T14:25:58.000Z
|
spring-aop/src/main/java/com/baeldung/aspectj/Secured.java
|
adrhc/tutorials
|
84cd9d8fdc23beb4fa552ba9c5fd8d9df292c4c4
|
[
"MIT"
] | 55,853 |
2015-01-01T07:52:09.000Z
|
2022-03-31T21:08:15.000Z
| 25.615385 | 45 | 0.813814 | 1,001,041 |
package com.baeldung.aspectj;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Secured {
public boolean isLocked() default false;
}
|
923f20f7a5c553a8286689acd2edf149ed3b3c83
| 1,512 |
java
|
Java
|
Team1JavaCAProject/src/main/java/com/nus/iss/controller/UserSession.java
|
adampngys/SchoolSystem
|
754b9d1168ada347ddf843c847108fc235fadf35
|
[
"MIT"
] | null | null | null |
Team1JavaCAProject/src/main/java/com/nus/iss/controller/UserSession.java
|
adampngys/SchoolSystem
|
754b9d1168ada347ddf843c847108fc235fadf35
|
[
"MIT"
] | null | null | null |
Team1JavaCAProject/src/main/java/com/nus/iss/controller/UserSession.java
|
adampngys/SchoolSystem
|
754b9d1168ada347ddf843c847108fc235fadf35
|
[
"MIT"
] | null | null | null | 19.636364 | 64 | 0.673942 | 1,001,042 |
package com.nus.iss.controller;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
import com.nus.iss.model.CapsUser;
import com.nus.iss.model.Lecturer;
import com.nus.iss.model.Student;
enum roleEnum {
student, lecturer, admin
}
@Component
@Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class UserSession {
private CapsUser user;
private roleEnum role;
private String sessionId = null;
private Student student = null;
private Lecturer lecturer = null;
public Lecturer getLecturer() {
return lecturer;
}
public void setLecturer(Lecturer lecturer) {
this.lecturer = lecturer;
}
public CapsUser getUser() {
return user;
}
public void setUser(CapsUser user) {
this.user = user;
if (user != null) {
// set the role info
if (user.getLec() != null) {
this.role = roleEnum.lecturer;
} else if (user.getStd() != null) {
this.role = roleEnum.student;
} else {
this.role = roleEnum.admin;
}
} else {
this.role = null;
}
}
public roleEnum getRole() {
return role;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
}
|
923f211aefd86a425f808333f276dfe05fd6e553
| 4,659 |
java
|
Java
|
src/main/java/com/genersoft/iot/vmp/gb28181/transmit/cmd/ISIPCommander.java
|
yuebo/wvp-GB28181
|
a7a1ae37410d08cc67acb047f5a0abf228391054
|
[
"MIT"
] | 44 |
2020-09-25T10:05:41.000Z
|
2021-10-30T05:29:31.000Z
|
src/main/java/com/genersoft/iot/vmp/gb28181/transmit/cmd/ISIPCommander.java
|
yuebo/wvp-GB28181
|
a7a1ae37410d08cc67acb047f5a0abf228391054
|
[
"MIT"
] | 5 |
2020-10-24T08:15:21.000Z
|
2020-11-09T06:03:52.000Z
|
src/main/java/com/genersoft/iot/vmp/gb28181/transmit/cmd/ISIPCommander.java
|
yuebo/wvp-GB28181
|
a7a1ae37410d08cc67acb047f5a0abf228391054
|
[
"MIT"
] | 13 |
2020-10-12T06:10:54.000Z
|
2021-12-14T07:07:42.000Z
| 21.569444 | 125 | 0.621163 | 1,001,043 |
package com.genersoft.iot.vmp.gb28181.transmit.cmd;
import com.genersoft.iot.vmp.common.StreamInfo;
import com.genersoft.iot.vmp.gb28181.bean.Device;
/**
* @Description:设备能力接口,用于定义设备的控制、查询能力
* @author: swwheihei
* @date: 2020年5月3日 下午9:16:34
*/
public interface ISIPCommander {
/**
* 云台方向放控制,使用配置文件中的默认镜头移动速度
*
* @param device 控制设备
* @param channelId 预览通道
* @param leftRight 镜头左移右移 0:停止 1:左移 2:右移
* @param upDown 镜头上移下移 0:停止 1:上移 2:下移
* @param moveSpeed 镜头移动速度
*/
public boolean ptzdirectCmd(Device device,String channelId,int leftRight, int upDown);
/**
* 云台方向放控制
*
* @param device 控制设备
* @param channelId 预览通道
* @param leftRight 镜头左移右移 0:停止 1:左移 2:右移
* @param upDown 镜头上移下移 0:停止 1:上移 2:下移
* @param moveSpeed 镜头移动速度
*/
public boolean ptzdirectCmd(Device device,String channelId,int leftRight, int upDown, int moveSpeed);
/**
* 云台缩放控制,使用配置文件中的默认镜头缩放速度
*
* @param device 控制设备
* @param channelId 预览通道
* @param inOut 镜头放大缩小 0:停止 1:缩小 2:放大
*/
public boolean ptzZoomCmd(Device device,String channelId,int inOut);
/**
* 云台缩放控制
*
* @param device 控制设备
* @param channelId 预览通道
* @param inOut 镜头放大缩小 0:停止 1:缩小 2:放大
* @param zoomSpeed 镜头缩放速度
*/
public boolean ptzZoomCmd(Device device,String channelId,int inOut, int moveSpeed);
/**
* 云台控制,支持方向与缩放控制
*
* @param device 控制设备
* @param channelId 预览通道
* @param leftRight 镜头左移右移 0:停止 1:左移 2:右移
* @param upDown 镜头上移下移 0:停止 1:上移 2:下移
* @param inOut 镜头放大缩小 0:停止 1:缩小 2:放大
* @param moveSpeed 镜头移动速度
* @param zoomSpeed 镜头缩放速度
*/
public boolean ptzCmd(Device device,String channelId,int leftRight, int upDown, int inOut, int moveSpeed, int zoomSpeed);
/**
* 前端控制,包括PTZ指令、FI指令、预置位指令、巡航指令、扫描指令和辅助开关指令
*
* @param device 控制设备
* @param channelId 预览通道
* @param cmdCode 指令码
* @param parameter1 数据1
* @param parameter2 数据2
* @param combineCode2 组合码2
*/
public boolean frontEndCmd(Device device, String channelId, int cmdCode, int parameter1, int parameter2, int combineCode2);
/**
* 请求预览视频流
*
* @param device 视频设备
* @param channelId 预览通道
*/
public StreamInfo playStreamCmd(Device device, String channelId);
/**
* 请求回放视频流
*
* @param device 视频设备
* @param channelId 预览通道
* @param startTime 开始时间,格式要求:yyyy-MM-dd HH:mm:ss
* @param endTime 结束时间,格式要求:yyyy-MM-dd HH:mm:ss
*/
public StreamInfo playbackStreamCmd(Device device,String channelId, String startTime, String endTime);
/**
* 视频流停止
*
* @param ssrc ssrc
*/
public void streamByeCmd(String ssrc);
/**
* 语音广播
*
* @param device 视频设备
* @param channelId 预览通道
*/
public boolean audioBroadcastCmd(Device device,String channelId);
/**
* 音视频录像控制
*
* @param device 视频设备
* @param channelId 预览通道
*/
public boolean recordCmd(Device device,String channelId);
/**
* 报警布防/撤防命令
*
* @param device 视频设备
*/
public boolean guardCmd(Device device);
/**
* 报警复位命令
*
* @param device 视频设备
*/
public boolean alarmCmd(Device device);
/**
* 强制关键帧命令,设备收到此命令应立刻发送一个IDR帧
*
* @param device 视频设备
* @param channelId 预览通道
*/
public boolean iFameCmd(Device device,String channelId);
/**
* 看守位控制命令
*
* @param device 视频设备
*/
public boolean homePositionCmd(Device device);
/**
* 设备配置命令
*
* @param device 视频设备
*/
public boolean deviceConfigCmd(Device device);
/**
* 查询设备状态
*
* @param device 视频设备
*/
public boolean deviceStatusQuery(Device device);
/**
* 查询设备信息
*
* @param device 视频设备
* @return
*/
public boolean deviceInfoQuery(Device device);
/**
* 查询目录列表
*
* @param device 视频设备
*/
public boolean catalogQuery(Device device);
/**
* 查询录像信息
*
* @param device 视频设备
* @param startTime 开始时间,格式要求:yyyy-MM-dd HH:mm:ss
* @param endTime 结束时间,格式要求:yyyy-MM-dd HH:mm:ss
*/
public boolean recordInfoQuery(Device device, String channelId, String startTime, String endTime);
/**
* 查询报警信息
*
* @param device 视频设备
*/
public boolean alarmInfoQuery(Device device);
/**
* 查询设备配置
*
* @param device 视频设备
*/
public boolean configQuery(Device device);
/**
* 查询设备预置位置
*
* @param device 视频设备
*/
public boolean presetQuery(Device device);
/**
* 查询移动设备位置数据
*
* @param device 视频设备
*/
public boolean mobilePostitionQuery(Device device);
}
|
923f22f6be6ade4b5c6624f8dad441cba3bd5f4e
| 3,124 |
java
|
Java
|
src/main/java/protocol/dc/nmdc/NMDCHubCommunicator.java
|
AdeebNqo/volkano
|
357c3a40e7dbdf637d26efcedda0c508b0c8a987
|
[
"Apache-1.1"
] | null | null | null |
src/main/java/protocol/dc/nmdc/NMDCHubCommunicator.java
|
AdeebNqo/volkano
|
357c3a40e7dbdf637d26efcedda0c508b0c8a987
|
[
"Apache-1.1"
] | 1 |
2015-04-16T11:47:51.000Z
|
2015-04-21T07:12:12.000Z
|
src/main/java/protocol/dc/nmdc/NMDCHubCommunicator.java
|
AdeebNqo/volkano
|
357c3a40e7dbdf637d26efcedda0c508b0c8a987
|
[
"Apache-1.1"
] | null | null | null | 31.555556 | 98 | 0.537452 | 1,001,044 |
package protocol.dc.nmdc;
import java.io.IOException;
import models.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.*;
import protocol.dc.HubCommunicator;
public class NMDCHubCommunicator extends NMDCCommunicator implements HubCommunicator {
final Queue<String> hubData = new ConcurrentLinkedQueue<String>();
final Queue<String> broadcastData = new ConcurrentLinkedQueue<String>();
public NMDCHubCommunicator(Connection connection) {
setConnection(connection);
ScheduledExecutorService getHubDataService = Executors.newSingleThreadScheduledExecutor();
getHubDataService.scheduleAtFixedRate( new Runnable() {
@Override
public void run() {
try {
String data = getData(getConnection().getInputStream());
if (!data.isEmpty()) {
System.err.println("hub comm, data: "+data);
//TODO: decide whether to insert into hubdata or broadcast data
if (data.startsWith("<")) {
broadcastData.add(data);
} else {
hubData.add(data);
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
}, 0, 50, TimeUnit.MILLISECONDS);
}
public String getHubData() {
//hubdata consumer
String data = hubData.poll();
while(data==null) {
data = hubData.poll();
}
System.err.println("hub says "+data);
return data;
}
@Override
public String getHubData(int timeoutSecs) throws TimeoutException {
ExecutorService executor = Executors.newSingleThreadExecutor();
TimeoutGetDataRunnable getDataAction = new TimeoutGetDataRunnable();
executor.submit(getDataAction);
try {
executor.awaitTermination(timeoutSecs, TimeUnit.SECONDS);
throw new TimeoutException();
} catch (InterruptedException e) {
//swallow it
}
return getDataAction.getData();
}
public String getBroadcastData() {
//broadcast data consumer
String data = broadcastData.poll();
while(data==null) {
data = broadcastData.poll();
}
return data;
}
public void sendDataToHub(String data) throws IOException {
sendData(data);
}
private class TimeoutGetDataRunnable implements Runnable {
String data = "";
@Override
public void run() {
data = hubData.poll();
while(data==null) {
data = hubData.poll();
}
}
public String getData() {
if (data == null) {
data = "";
}
return data;
}
}
}
|
923f23fa77f3f7c3abf8fd23b28f486fc3f1404f
| 475 |
java
|
Java
|
gmall-ums/src/main/java/com/atguigu/gmall/ums/api/service/MemberLoginLogService.java
|
zhangqiperfect/gmall-new
|
bf1264119f57a7d48cfb70251aa21762ccb6b7bc
|
[
"Apache-2.0"
] | 1 |
2019-11-07T14:25:31.000Z
|
2019-11-07T14:25:31.000Z
|
gmall-ums/src/main/java/com/atguigu/gmall/ums/api/service/MemberLoginLogService.java
|
zhangqiperfect/gmall-new
|
bf1264119f57a7d48cfb70251aa21762ccb6b7bc
|
[
"Apache-2.0"
] | 7 |
2020-02-28T01:24:54.000Z
|
2021-09-20T20:53:44.000Z
|
gmall-ums/src/main/java/com/atguigu/gmall/ums/api/service/MemberLoginLogService.java
|
zhangqiperfect/gmall-new
|
bf1264119f57a7d48cfb70251aa21762ccb6b7bc
|
[
"Apache-2.0"
] | null | null | null | 22.619048 | 79 | 0.778947 | 1,001,045 |
package com.atguigu.gmall.ums.api.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.atguigu.gmall.ums.api.entity.MemberLoginLogEntity;
import com.atguigu.core.bean.PageVo;
import com.atguigu.core.bean.QueryCondition;
/**
* 会员登录记录
*
* @author qinhan
* @email [email protected]
* @date 2019-10-28 20:53:31
*/
public interface MemberLoginLogService extends IService<MemberLoginLogEntity> {
PageVo queryPage(QueryCondition params);
}
|
923f24027031e4c237164496dc58bd987adc61e0
| 3,510 |
java
|
Java
|
src/main/java/de/zalando/zmon/scheduler/ng/checks/CheckRepository.java
|
zalando-zmon/zmon-scheduler
|
6e7938023ecf1c6b8c2a94daa332ccb3ca26ecc2
|
[
"Apache-2.0"
] | 8 |
2016-07-28T09:24:54.000Z
|
2019-01-22T22:15:26.000Z
|
src/main/java/de/zalando/zmon/scheduler/ng/checks/CheckRepository.java
|
zalando-zmon/zmon-scheduler
|
6e7938023ecf1c6b8c2a94daa332ccb3ca26ecc2
|
[
"Apache-2.0"
] | 82 |
2016-06-02T06:56:34.000Z
|
2020-03-10T09:45:02.000Z
|
src/main/java/de/zalando/zmon/scheduler/ng/checks/CheckRepository.java
|
zalando-zmon/zmon-scheduler
|
6e7938023ecf1c6b8c2a94daa332ccb3ca26ecc2
|
[
"Apache-2.0"
] | 2 |
2018-05-08T07:30:31.000Z
|
2020-01-13T17:05:39.000Z
| 34.411765 | 124 | 0.603989 | 1,001,046 |
package de.zalando.zmon.scheduler.ng.checks;
import de.zalando.zmon.scheduler.ng.CachedRepository;
import de.zalando.zmon.scheduler.ng.config.SchedulerConfig;
import io.opentracing.Tracer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*;
/**
* Created by jmussler on 4/7/15.
*/
@Component
public class CheckRepository extends CachedRepository<Integer, CheckSourceRegistry, CheckDefinition> {
private final Set<CheckChangeListener> listeners = new HashSet<>();
private final MinIntervalEntityFetcher minIntervalEntityFetcher;
public synchronized void registerListener(CheckChangeListener l) {
listeners.add(l);
}
private void update(Map<Integer, CheckDefinition> oldMap, Map<Integer, CheckDefinition> newMap) {
List<Integer> intervalChanged = new ArrayList<>();
List<Integer> newChecks = new ArrayList<>();
List<Integer> removedChecks = new ArrayList<>();
for (Integer id : oldMap.keySet()) {
if (newMap.containsKey(id)) {
if (!oldMap.get(id).getInterval().equals(newMap.get(id).getInterval())) {
intervalChanged.add(id);
}
} else {
removedChecks.add(id);
}
}
for (Integer id : newMap.keySet()) {
if (!oldMap.containsKey(id)) {
newChecks.add(id);
}
}
for (CheckChangeListener l : listeners) {
for (Integer id : newChecks) {
l.notifyNewCheck(this, id);
}
for (Integer id : removedChecks) {
l.notifyDeleteCheck(this, id);
}
for (Integer id : intervalChanged) {
l.notifyCheckIntervalChange(this, id);
}
}
}
@Override
public synchronized void fill() {
Map<Integer, CheckDefinition> m = new HashMap<>();
minIntervalEntityFetcher.fetch();
MinIntervalEntityFetcher.MinCheckIntervalData minIntervalData = minIntervalEntityFetcher.getCheckInterval();
for (String name : registry.getSourceNames()) {
for (CheckDefinition cd : registry.get(name).getCollection()) {
Integer id = cd.getId();
Long interval = cd.getInterval();
if (interval < minIntervalData.getMinCheckInterval()) {
if (minIntervalData.getWhitelistedChecks().contains(id)) {
if (interval < minIntervalData.getMinWhitelistedCheckInterval()) {
cd.setInterval(minIntervalData.getMinWhitelistedCheckInterval());
}
} else {
cd.setInterval(minIntervalData.getMinCheckInterval());
}
}
m.put(id, cd);
}
}
Map<Integer, CheckDefinition> oldMap = currentMap;
currentMap = m; // switching here to new map instance before notifications
update(oldMap, currentMap);
}
@Override
protected CheckDefinition getNullObject() {
return null;
}
@Autowired
public CheckRepository(CheckSourceRegistry registry, Tracer tracer, MinIntervalEntityFetcher minIntervalEntityFetcher) {
super(registry, tracer);
this.currentMap = new HashMap<>();
this.minIntervalEntityFetcher = minIntervalEntityFetcher;
fill();
}
}
|
923f2405327485e4d2d17b12f1850e4a233b5f25
| 21,717 |
java
|
Java
|
src/main/java/View/MenuVeterinario.java
|
enyasantos/Sistema-Pet-Shop-Java
|
46347da470b44911c0c4efe4e47c10219c27c0dd
|
[
"MIT"
] | null | null | null |
src/main/java/View/MenuVeterinario.java
|
enyasantos/Sistema-Pet-Shop-Java
|
46347da470b44911c0c4efe4e47c10219c27c0dd
|
[
"MIT"
] | null | null | null |
src/main/java/View/MenuVeterinario.java
|
enyasantos/Sistema-Pet-Shop-Java
|
46347da470b44911c0c4efe4e47c10219c27c0dd
|
[
"MIT"
] | null | null | null | 52.711165 | 191 | 0.689276 | 1,001,047 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package View;
import Content.ListarClientes;
import Content.VisualizarOrdemServico;
import Models.Veterinario;
import Models.Registro;
import java.awt.Color;
import javax.swing.JPanel;
/**
*
* @author enya
*/
public class MenuVeterinario extends javax.swing.JFrame {
/**
* Creates new form MenuAdministrados
*/
private Veterinario vet;
private Registro reg;
VisualizarOrdemServico tela;
public MenuVeterinario() {
initComponents();
}
public MenuVeterinario(Veterinario vet, Registro reg) {
initComponents();
this.vet = vet;
this.reg = reg;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
j_content = new javax.swing.JDesktopPane();
panel_menu = new javax.swing.JPanel();
lbl_sair = new javax.swing.JLabel();
lbl_title_happetsy = new javax.swing.JLabel();
lbl_version = new javax.swing.JLabel();
lvl_sistema_gerenciamento = new javax.swing.JLabel();
pnl_ordem_servico = new javax.swing.JPanel();
lbl_visualizar_ordem_servico = new javax.swing.JLabel();
btn_v_ordem_servico = new javax.swing.JPanel();
pnl_gerar_relatorio = new javax.swing.JPanel();
lbl_gerar_relatorio = new javax.swing.JLabel();
btn_gerar_relatorio = new javax.swing.JPanel();
pnl_visualizar_clientes = new javax.swing.JPanel();
lbl_visualizar_clientes = new javax.swing.JLabel();
btn_v_clientes = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout j_contentLayout = new javax.swing.GroupLayout(j_content);
j_content.setLayout(j_contentLayout);
j_contentLayout.setHorizontalGroup(
j_contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 837, Short.MAX_VALUE)
);
j_contentLayout.setVerticalGroup(
j_contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
panel_menu.setBackground(new java.awt.Color(13, 36, 51));
lbl_sair.setFont(new java.awt.Font("SansSerif", 1, 16)); // NOI18N
lbl_sair.setForeground(new java.awt.Color(254, 254, 254));
lbl_sair.setText("Sair");
lbl_sair.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lbl_sairMouseClicked(evt);
}
});
lbl_title_happetsy.setBackground(new java.awt.Color(254, 254, 255));
lbl_title_happetsy.setFont(new java.awt.Font("URW Gothic L", 1, 20)); // NOI18N
lbl_title_happetsy.setForeground(new java.awt.Color(254, 254, 254));
lbl_title_happetsy.setText("H A P P E T S Y");
lbl_version.setFont(new java.awt.Font("URW Gothic L", 0, 12)); // NOI18N
lbl_version.setForeground(new java.awt.Color(188, 193, 195));
lbl_version.setText("v0.1");
lvl_sistema_gerenciamento.setFont(new java.awt.Font("URW Gothic L", 0, 12)); // NOI18N
lvl_sistema_gerenciamento.setForeground(new java.awt.Color(207, 212, 213));
lvl_sistema_gerenciamento.setText("Sistema de gerenciamento");
pnl_ordem_servico.setBackground(new java.awt.Color(13, 36, 51));
lbl_visualizar_ordem_servico.setFont(new java.awt.Font("SansSerif", 1, 16)); // NOI18N
lbl_visualizar_ordem_servico.setForeground(new java.awt.Color(255, 255, 255));
lbl_visualizar_ordem_servico.setText("Visulizar Ordem de Serviço");
lbl_visualizar_ordem_servico.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lbl_visualizar_ordem_servicoMouseClicked(evt);
}
});
btn_v_ordem_servico.setBackground(new java.awt.Color(13, 36, 51));
javax.swing.GroupLayout btn_v_ordem_servicoLayout = new javax.swing.GroupLayout(btn_v_ordem_servico);
btn_v_ordem_servico.setLayout(btn_v_ordem_servicoLayout);
btn_v_ordem_servicoLayout.setHorizontalGroup(
btn_v_ordem_servicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 5, Short.MAX_VALUE)
);
btn_v_ordem_servicoLayout.setVerticalGroup(
btn_v_ordem_servicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 27, Short.MAX_VALUE)
);
javax.swing.GroupLayout pnl_ordem_servicoLayout = new javax.swing.GroupLayout(pnl_ordem_servico);
pnl_ordem_servico.setLayout(pnl_ordem_servicoLayout);
pnl_ordem_servicoLayout.setHorizontalGroup(
pnl_ordem_servicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnl_ordem_servicoLayout.createSequentialGroup()
.addContainerGap()
.addComponent(btn_v_ordem_servico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lbl_visualizar_ordem_servico, javax.swing.GroupLayout.DEFAULT_SIZE, 243, Short.MAX_VALUE)
.addContainerGap(22, Short.MAX_VALUE))
);
pnl_ordem_servicoLayout.setVerticalGroup(
pnl_ordem_servicoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_visualizar_ordem_servico, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(pnl_ordem_servicoLayout.createSequentialGroup()
.addGap(0, 22, Short.MAX_VALUE)
.addComponent(btn_v_ordem_servico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pnl_gerar_relatorio.setBackground(new java.awt.Color(13, 36, 51));
lbl_gerar_relatorio.setFont(new java.awt.Font("SansSerif", 1, 16)); // NOI18N
lbl_gerar_relatorio.setForeground(new java.awt.Color(255, 255, 255));
lbl_gerar_relatorio.setText("Gerar Relatório");
lbl_gerar_relatorio.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lbl_gerar_relatorioMouseClicked(evt);
}
});
btn_gerar_relatorio.setBackground(new java.awt.Color(13, 36, 51));
btn_gerar_relatorio.setPreferredSize(new java.awt.Dimension(5, 0));
javax.swing.GroupLayout btn_gerar_relatorioLayout = new javax.swing.GroupLayout(btn_gerar_relatorio);
btn_gerar_relatorio.setLayout(btn_gerar_relatorioLayout);
btn_gerar_relatorioLayout.setHorizontalGroup(
btn_gerar_relatorioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 5, Short.MAX_VALUE)
);
btn_gerar_relatorioLayout.setVerticalGroup(
btn_gerar_relatorioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
javax.swing.GroupLayout pnl_gerar_relatorioLayout = new javax.swing.GroupLayout(pnl_gerar_relatorio);
pnl_gerar_relatorio.setLayout(pnl_gerar_relatorioLayout);
pnl_gerar_relatorioLayout.setHorizontalGroup(
pnl_gerar_relatorioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnl_gerar_relatorioLayout.createSequentialGroup()
.addContainerGap()
.addComponent(btn_gerar_relatorio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lbl_gerar_relatorio, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pnl_gerar_relatorioLayout.setVerticalGroup(
pnl_gerar_relatorioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnl_gerar_relatorioLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(pnl_gerar_relatorioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(btn_gerar_relatorio, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
.addComponent(lbl_gerar_relatorio, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE))
.addContainerGap())
);
pnl_visualizar_clientes.setBackground(new java.awt.Color(13, 36, 51));
lbl_visualizar_clientes.setFont(new java.awt.Font("SansSerif", 1, 16)); // NOI18N
lbl_visualizar_clientes.setForeground(new java.awt.Color(255, 255, 255));
lbl_visualizar_clientes.setText("Visualizar Clientes");
lbl_visualizar_clientes.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lbl_visualizar_clientesMouseClicked(evt);
}
});
btn_v_clientes.setBackground(new java.awt.Color(13, 36, 51));
btn_v_clientes.setPreferredSize(new java.awt.Dimension(5, 11));
javax.swing.GroupLayout btn_v_clientesLayout = new javax.swing.GroupLayout(btn_v_clientes);
btn_v_clientes.setLayout(btn_v_clientesLayout);
btn_v_clientesLayout.setHorizontalGroup(
btn_v_clientesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 5, Short.MAX_VALUE)
);
btn_v_clientesLayout.setVerticalGroup(
btn_v_clientesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
javax.swing.GroupLayout pnl_visualizar_clientesLayout = new javax.swing.GroupLayout(pnl_visualizar_clientes);
pnl_visualizar_clientes.setLayout(pnl_visualizar_clientesLayout);
pnl_visualizar_clientesLayout.setHorizontalGroup(
pnl_visualizar_clientesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnl_visualizar_clientesLayout.createSequentialGroup()
.addContainerGap()
.addComponent(btn_v_clientes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lbl_visualizar_clientes, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pnl_visualizar_clientesLayout.setVerticalGroup(
pnl_visualizar_clientesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_visualizar_clientes, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
.addComponent(btn_v_clientes, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
);
javax.swing.GroupLayout panel_menuLayout = new javax.swing.GroupLayout(panel_menu);
panel_menu.setLayout(panel_menuLayout);
panel_menuLayout.setHorizontalGroup(
panel_menuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_menuLayout.createSequentialGroup()
.addGroup(panel_menuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pnl_visualizar_clientes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(pnl_gerar_relatorio, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel_menuLayout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(pnl_ordem_servico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(panel_menuLayout.createSequentialGroup()
.addGroup(panel_menuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_menuLayout.createSequentialGroup()
.addGap(31, 31, 31)
.addComponent(lbl_sair))
.addGroup(panel_menuLayout.createSequentialGroup()
.addGap(60, 60, 60)
.addGroup(panel_menuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lvl_sistema_gerenciamento)
.addGroup(panel_menuLayout.createSequentialGroup()
.addComponent(lbl_title_happetsy)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lbl_version)))))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
panel_menuLayout.setVerticalGroup(
panel_menuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(panel_menuLayout.createSequentialGroup()
.addGap(55, 55, 55)
.addGroup(panel_menuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lbl_title_happetsy)
.addComponent(lbl_version))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lvl_sistema_gerenciamento)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 101, Short.MAX_VALUE)
.addComponent(pnl_ordem_servico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pnl_gerar_relatorio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pnl_visualizar_clientes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(48, 48, 48)
.addComponent(lbl_sair)
.addContainerGap(132, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(panel_menu, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0)
.addComponent(j_content))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel_menu, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(j_content)
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void lbl_visualizar_ordem_servicoMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_lbl_visualizar_ordem_servicoMouseClicked
setColor(btn_v_ordem_servico);
resetColor(btn_gerar_relatorio);
resetColor(btn_v_clientes);
tela = new VisualizarOrdemServico(vet, reg);
tela.visualizarOrdem();
j_content.removeAll();
j_content.add(tela).setVisible(true);
}// GEN-LAST:event_lbl_visualizar_ordem_servicoMouseClicked
private void lbl_gerar_relatorioMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_lbl_gerar_relatorioMouseClicked
setColor(btn_gerar_relatorio);
resetColor(btn_v_ordem_servico);
resetColor(btn_v_clientes);
tela = new VisualizarOrdemServico(vet, reg);
tela.GerarRelatorio_OrdemServico();
j_content.removeAll();
j_content.add(tela).setVisible(true);
}// GEN-LAST:event_lbl_gerar_relatorioMouseClicked
private void lbl_visualizar_clientesMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_lbl_visualizar_clientesMouseClicked
setColor(btn_v_clientes);
resetColor(btn_v_ordem_servico);
resetColor(btn_gerar_relatorio);
ListarClientes listarClientes = new ListarClientes(reg);
j_content.removeAll();
j_content.add(listarClientes).setVisible(true);
}// GEN-LAST:event_lbl_visualizar_clientesMouseClicked
private void lbl_sairMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_lbl_sairMouseClicked
this.dispose();
}// GEN-LAST:event_lbl_sairMouseClicked
void resetColor(JPanel panel) {
panel.setBackground(new Color(13, 36, 51));
}
void setColor(JPanel panel) {
panel.setBackground(new Color(254, 254, 254));
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
// <editor-fold defaultstate="collapsed" desc=" Look and feel setting code
// (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the default
* look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MenuVeterinario.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MenuVeterinario.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MenuVeterinario.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MenuVeterinario.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
}
// </editor-fold>
// </editor-fold>
// </editor-fold>
// </editor-fold>
// </editor-fold>
// </editor-fold>
// </editor-fold>
// </editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MenuVeterinario().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JPanel btn_gerar_relatorio;
private javax.swing.JPanel btn_v_clientes;
private javax.swing.JPanel btn_v_ordem_servico;
private javax.swing.JDesktopPane j_content;
private javax.swing.JLabel lbl_gerar_relatorio;
private javax.swing.JLabel lbl_sair;
private javax.swing.JLabel lbl_title_happetsy;
private javax.swing.JLabel lbl_version;
private javax.swing.JLabel lbl_visualizar_clientes;
private javax.swing.JLabel lbl_visualizar_ordem_servico;
private javax.swing.JLabel lvl_sistema_gerenciamento;
private javax.swing.JPanel panel_menu;
private javax.swing.JPanel pnl_gerar_relatorio;
private javax.swing.JPanel pnl_ordem_servico;
private javax.swing.JPanel pnl_visualizar_clientes;
// End of variables declaration//GEN-END:variables
}
|
923f24634326ed32131a3f9c78102f5f32584074
| 1,848 |
java
|
Java
|
src/main/java/io/circleline/message/JCacheApiStatusRepository.java
|
circlelineio/circleline-gw
|
77a28c0ebe1eed7492103acc52a04d15bc17406b
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/io/circleline/message/JCacheApiStatusRepository.java
|
circlelineio/circleline-gw
|
77a28c0ebe1eed7492103acc52a04d15bc17406b
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/io/circleline/message/JCacheApiStatusRepository.java
|
circlelineio/circleline-gw
|
77a28c0ebe1eed7492103acc52a04d15bc17406b
|
[
"Apache-2.0"
] | null | null | null | 27.58209 | 96 | 0.702381 | 1,001,048 |
package io.circleline.message;
import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Default ApiEndpointStatusManager
* <p>
* 기본으로 API의 상태를 로컬메모리에서 관리한다.
* Singlemode에서는 이 Manager를 사용하며
* Clustermode일 경우에는 ClusterApiEndpointStatusManager를 사용한다.
*/
public class JCacheApiStatusRepository implements ApiStatusRepository {
private Cache<ApiEndpoint, ApiStatus> cache;
private Set<ApiEndpoint> apiEndpointSet;
public JCacheApiStatusRepository(List<ApiEndpoint> apiEndpoints) {
apiEndpointSet = apiEndpoints.stream().collect(Collectors.toSet());
}
/**
* 캐쉬를 초기화한다.
*/
@Override
public void initRepository(){
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// TODO 만기설정 확인필요. 0로
// TODO 전략설정 확인필요. 어인떤 값이 어떤 식으로 유지되는지.
MutableConfiguration<ApiEndpoint, ApiStatus> configuration = new MutableConfiguration();
cache = manager.createCache("cache", configuration);
putAllApiStatus(apiEndpointSet);
}
/**
* ApiEndpoint의 상태를 캐쉬에 저장한다.
* @param apiEndpoints
*/
private void putAllApiStatus(Set<ApiEndpoint> apiEndpoints){
apiEndpoints.forEach(a -> cache.put(a,new ApiStatus(a)));
}
@Override
public List<ApiStatus> allApiStatus(){
//TODO 다른 방법 찾기
return new ArrayList(cache.getAll(apiEndpointSet).values());
}
@Override
public ApiStatus getApiStatus(ApiEndpoint apiEndpoint){
return cache.get(apiEndpoint);
}
@Override
public void persist(ApiStatus apiStatus) {
cache.put(apiStatus.getApiEndpoint(), apiStatus);
}
}
|
923f2562d3c90afc315b25dc6ade37e7506c62f6
| 3,326 |
java
|
Java
|
src/main/java/features/UserSessionsTracker.java
|
Hoommus/iscaribot
|
7d5730a29ab1cd46dbdec404686230edb171ff41
|
[
"MIT"
] | 1 |
2020-08-04T19:11:35.000Z
|
2020-08-04T19:11:35.000Z
|
src/main/java/features/UserSessionsTracker.java
|
Hoommus/iscaribot
|
7d5730a29ab1cd46dbdec404686230edb171ff41
|
[
"MIT"
] | null | null | null |
src/main/java/features/UserSessionsTracker.java
|
Hoommus/iscaribot
|
7d5730a29ab1cd46dbdec404686230edb171ff41
|
[
"MIT"
] | null | null | null | 41.061728 | 111 | 0.799158 | 1,001,049 |
package features;
import model.entities.EnhancedGuild;
import model.entities.EnhancedUser;
import net.dv8tion.jda.core.OnlineStatus;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.core.events.user.GenericUserEvent;
import net.dv8tion.jda.core.events.user.UserNameUpdateEvent;
import net.dv8tion.jda.core.events.user.UserOnlineStatusUpdateEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import providers.EnhancedGuildsProvider;
import providers.EnhancedUsersProvider;
import java.time.Instant;
public class UserSessionsTracker extends ListenerAdapter {
private static final Logger LOGGER = LogManager.getLogger(UserSessionsTracker.class);
private static final EnhancedGuildsProvider ENHANCED_GUILDS_PROVIDER = EnhancedGuildsProvider.getInstance();
private static final EnhancedUsersProvider ENHANCED_USERS_PROVIDER = EnhancedUsersProvider .getInstance();
@Override
public void onUserNameUpdate(UserNameUpdateEvent event) {
EnhancedUser enhancedUser = ENHANCED_USERS_PROVIDER.enhance(event.getUser());
}
@Override
public void onUserOnlineStatusUpdate(UserOnlineStatusUpdateEvent event) {
Instant eventTime = Instant.now();
EnhancedUser enhancedUser = ENHANCED_USERS_PROVIDER.enhance(event.getUser());
EnhancedGuild enhancedGuild = ENHANCED_GUILDS_PROVIDER.enhance(event.getGuild());
OnlineStatus current = enhancedGuild.getMember(enhancedUser).getOnlineStatus();
OnlineStatus previous = event.getPreviousOnlineStatus();
if((current == OnlineStatus.ONLINE || current == OnlineStatus.DO_NOT_DISTURB || current == OnlineStatus.IDLE)
&& (previous == OnlineStatus.OFFLINE || previous == OnlineStatus.UNKNOWN))
enhancedUser.setLastGoneOnline(eventTime);
else if(previous == OnlineStatus.OFFLINE || previous == OnlineStatus.UNKNOWN)
enhancedUser.setLastGoneOffline(eventTime);
ENHANCED_USERS_PROVIDER.update(enhancedUser);
LOGGER.debug("Updating user in userOnlineStatus");
}
@Override
public void onGenericUser(GenericUserEvent event) {
super.onGenericUser(event);
}
// @Override
// public void onUserTyping(UserTypingEvent event) {
// Instant eventTime = Instant.now();
// EnhancedUser enhancedUser = ENHANCED_USERS_PROVIDER.enhance(event.getMember().getUser());
// EnhancedGuild enhancedGuild = ENHANCED_GUILDS_PROVIDER.enhance(event.getGuild());
//
// Member member = enhancedGuild.getMember(enhancedUser);
// if(member.getOnlineStatus() == OnlineStatus.OFFLINE)
// enhancedUser.setLastGoneOnline(eventTime);
// ENHANCED_USERS_PROVIDER.update(enhancedUser);
// LOGGER.debug("Updating user in userTyping");
//
// }
@Override
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
Instant eventTime = Instant.now();
Member member = event.getMember();
EnhancedUser enhancedUser = ENHANCED_USERS_PROVIDER.enhance(event.getMember().getUser());
EnhancedGuild enhancedGuild = ENHANCED_GUILDS_PROVIDER.enhance(event.getGuild());
if(member.getOnlineStatus() == OnlineStatus.OFFLINE) {
enhancedUser.setLastGoneOnline(eventTime);
ENHANCED_USERS_PROVIDER.update(enhancedUser);
LOGGER.debug("Updating user in messageReceived");
}
}
}
|
923f2624fcb8f5ac728d1a38180cc168f2067117
| 1,149 |
java
|
Java
|
grainmall-order/src/main/java/com/w1nd/grainmall/order/listener/OrderSeckillListener.java
|
2w1nd/grainmall
|
a1146737f7e22fa46954f98c324b7cc6b31a465f
|
[
"Apache-2.0"
] | 7 |
2022-03-06T03:30:00.000Z
|
2022-03-14T14:29:30.000Z
|
grainmall-order/src/main/java/com/w1nd/grainmall/order/listener/OrderSeckillListener.java
|
2w1nd/grainmall
|
a1146737f7e22fa46954f98c324b7cc6b31a465f
|
[
"Apache-2.0"
] | null | null | null |
grainmall-order/src/main/java/com/w1nd/grainmall/order/listener/OrderSeckillListener.java
|
2w1nd/grainmall
|
a1146737f7e22fa46954f98c324b7cc6b31a465f
|
[
"Apache-2.0"
] | null | null | null | 31.054054 | 103 | 0.760661 | 1,001,050 |
package com.w1nd.grainmall.order.listener;
import com.rabbitmq.client.Channel;
import com.w1nd.common.to.mq.SeckillOrderTo;
import com.w1nd.grainmall.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Slf4j
@Component
@RabbitListener(queues = "order.seckill.order.queue")
public class OrderSeckillListener {
@Autowired
private OrderService orderService;
@RabbitHandler
public void listener(SeckillOrderTo orderTo, Channel channel, Message message) throws IOException {
log.info("准备创建秒杀单的详细信息...");
try {
orderService.createSeckillOrder(orderTo);
channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
} catch (Exception e) {
channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
}
}
}
|
923f276ff30f9d4753c371a1b86d7acc8aefe45e
| 1,503 |
java
|
Java
|
valkyrie-rcp-core/src/main/java/org/valkyriercp/application/support/JOutlookBarNavigatorView.java
|
artri/Valkyrie-RCP
|
6aad6e640b348cda8f3b0841f6e42025233f1eb8
|
[
"Apache-2.0"
] | 6 |
2015-08-05T01:15:16.000Z
|
2020-06-03T08:04:02.000Z
|
valkyrie-rcp-core/src/main/java/org/valkyriercp/application/support/JOutlookBarNavigatorView.java
|
artri/Valkyrie-RCP
|
6aad6e640b348cda8f3b0841f6e42025233f1eb8
|
[
"Apache-2.0"
] | null | null | null |
valkyrie-rcp-core/src/main/java/org/valkyriercp/application/support/JOutlookBarNavigatorView.java
|
artri/Valkyrie-RCP
|
6aad6e640b348cda8f3b0841f6e42025233f1eb8
|
[
"Apache-2.0"
] | 3 |
2015-04-14T21:08:24.000Z
|
2019-03-11T03:14:19.000Z
| 32.673913 | 96 | 0.748503 | 1,001,051 |
/**
* Copyright (C) 2015 Valkyrie RCP
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.valkyriercp.application.support;
import net.miginfocom.swing.MigLayout;
import org.valkyriercp.command.support.CommandGroup;
import org.valkyriercp.command.support.CommandGroupJComponentBuilder;
import org.valkyriercp.command.support.JOutlookBarBuilder;
import javax.swing.*;
public class JOutlookBarNavigatorView extends AbstractNavigatorView {
private CommandGroup navigation;
public JOutlookBarNavigatorView(CommandGroup navigation)
{
super(navigation);
this.navigation = navigation;
}
public CommandGroupJComponentBuilder getNavigationBuilder()
{
return new JOutlookBarBuilder();
}
protected JComponent createControl()
{
JPanel navigationView = new JPanel(new MigLayout("fill"));
navigationView.add(getNavigationBuilder().buildComponent(this.navigation), "grow,push");
return navigationView;
}
}
|
923f2771626f3ec30ab300569007e330c88e75f9
| 1,747 |
java
|
Java
|
back-end/src/main/java/com/lavantru/Register/model/PaymentMethod.java
|
LavanTru/webapp
|
66f5faace9660dd843747edf4a1e1e2e58f7f1b6
|
[
"MIT"
] | null | null | null |
back-end/src/main/java/com/lavantru/Register/model/PaymentMethod.java
|
LavanTru/webapp
|
66f5faace9660dd843747edf4a1e1e2e58f7f1b6
|
[
"MIT"
] | null | null | null |
back-end/src/main/java/com/lavantru/Register/model/PaymentMethod.java
|
LavanTru/webapp
|
66f5faace9660dd843747edf4a1e1e2e58f7f1b6
|
[
"MIT"
] | null | null | null | 26.074627 | 208 | 0.700057 | 1,001,052 |
package com.lavantru.Register.model;
import org.apache.commons.lang.builder.ToStringBuilder;
import java.util.Date;
/**
* <h1>PaymentMethod</h1>
* This object contains the attributes of washee's payment method
*
* @version 1.0
* @since 2020
*/
public class PaymentMethod {
private String cardNo;
private Date expirationDate;
private String securityCode;
private Boolean defaultPaymentMethod;
public PaymentMethod() {
}
public PaymentMethod(String cardNo, Date expirationDate, String securityCode, Boolean defaultPaymentMethod) {
this.cardNo = cardNo;
this.expirationDate = expirationDate;
this.securityCode = securityCode;
this.defaultPaymentMethod = defaultPaymentMethod;
}
public String getCardNo() {
return cardNo;
}
public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}
public Date getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Date expirationDate) {
this.expirationDate = expirationDate;
}
public String getSecurityCode() {
return securityCode;
}
public void setSecurityCode(String securityCode) {
this.securityCode = securityCode;
}
public Boolean getDefaultPaymentMethod() {
return defaultPaymentMethod;
}
public void setDefaultPaymentMethod(Boolean defaultPaymentMethod) {
this.defaultPaymentMethod = defaultPaymentMethod;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("cardNo", cardNo).append("expirationDate", expirationDate).append("securityCode", securityCode).append("defaultPaymentMethod", defaultPaymentMethod).toString();
}
}
|
923f2777937a29f814d25ce1ed6dd6c7fcb6f2b6
| 2,999 |
java
|
Java
|
ruoyi-admin/src/main/java/com/ruoyi/test/domain/userMonitorCompany.java
|
Kooklen/TianyanchaAdminSystem
|
876a0f1ecdf321df07321d0d6cc00b434e6208ad
|
[
"MIT"
] | 1 |
2022-03-25T04:33:30.000Z
|
2022-03-25T04:33:30.000Z
|
ruoyi-admin/src/main/java/com/ruoyi/test/domain/userMonitorCompany.java
|
Kooklen/TianyanchaAdminSystem
|
876a0f1ecdf321df07321d0d6cc00b434e6208ad
|
[
"MIT"
] | null | null | null |
ruoyi-admin/src/main/java/com/ruoyi/test/domain/userMonitorCompany.java
|
Kooklen/TianyanchaAdminSystem
|
876a0f1ecdf321df07321d0d6cc00b434e6208ad
|
[
"MIT"
] | null | null | null | 21.57554 | 71 | 0.602201 | 1,001,053 |
package com.ruoyi.test.domain;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
/**
* userMonitorCompany对象 user_monitor_company
*
* @author kooklen
* @date 2021-12-28
*/
public class userMonitorCompany extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 用户id */
@Excel(name = "用户id")
private Long userid;
/** 用户名 */
@Excel(name = "用户名")
private String username;
/** 公司id */
@Excel(name = "公司id")
private Long companyid;
/** 记录号 */
private Long recordnumber;
/** 公司名 */
@Excel(name = "公司名")
private String companyname;
/** 监控时间 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "监控时间", width = 30, dateFormat = "yyyy-MM-dd")
private Date monitortime;
/** 公司状态 */
@Excel(name = "公司状态")
private Long state;
/** 是否正在监控 */
@Excel(name = "是否正在监控")
private Long ismonitor;
public void setUserid(Long userid)
{
this.userid = userid;
}
public Long getUserid()
{
return userid;
}
public void setUsername(String username)
{
this.username = username;
}
public String getUsername()
{
return username;
}
public void setCompanyid(Long companyid)
{
this.companyid = companyid;
}
public Long getCompanyid()
{
return companyid;
}
public void setRecordnumber(Long recordnumber)
{
this.recordnumber = recordnumber;
}
public Long getRecordnumber()
{
return recordnumber;
}
public void setCompanyname(String companyname)
{
this.companyname = companyname;
}
public String getCompanyname()
{
return companyname;
}
public void setMonitortime(Date monitortime)
{
this.monitortime = monitortime;
}
public Date getMonitortime()
{
return monitortime;
}
public void setState(Long state)
{
this.state = state;
}
public Long getState()
{
return state;
}
public void setIsmonitor(Long ismonitor)
{
this.ismonitor = ismonitor;
}
public Long getIsmonitor()
{
return ismonitor;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("userid", getUserid())
.append("username", getUsername())
.append("companyid", getCompanyid())
.append("recordnumber", getRecordnumber())
.append("companyname", getCompanyname())
.append("monitortime", getMonitortime())
.append("state", getState())
.append("ismonitor", getIsmonitor())
.toString();
}
}
|
923f27bee06d25c3db299e1e7a4903eca14d91c9
| 1,114 |
java
|
Java
|
Second semestre/Programming/lab7/common/src/main/java/person/PersonValidatorImpl.java
|
robqqq/ITMO
|
0d33d7b2e1d4baf1ac39e8d688eb38cc23cef03b
|
[
"MIT"
] | 2 |
2021-02-28T11:42:26.000Z
|
2021-04-04T15:34:01.000Z
|
Second semestre/Programming/lab8/common/src/main/java/person/PersonValidatorImpl.java
|
robqqq/ITMO
|
0d33d7b2e1d4baf1ac39e8d688eb38cc23cef03b
|
[
"MIT"
] | null | null | null |
Second semestre/Programming/lab8/common/src/main/java/person/PersonValidatorImpl.java
|
robqqq/ITMO
|
0d33d7b2e1d4baf1ac39e8d688eb38cc23cef03b
|
[
"MIT"
] | 3 |
2021-04-09T13:06:37.000Z
|
2021-06-15T22:15:17.000Z
| 21.423077 | 69 | 0.654399 | 1,001,054 |
package person;
import java.time.LocalDateTime;
public class PersonValidatorImpl implements PersonValidator{
@Override
public boolean validateName(String name) {
return name != null && !name.equals("");
}
@Override
public boolean validateId(int id){
return id > 0;
}
@Override
public boolean validateCoordinates(Coordinates coordinates) {
return coordinates != null;
}
@Override
public boolean validateCreationDate(LocalDateTime creationDate) {
return creationDate != null;
}
@Override
public boolean validateHeight(Long height) {
return height > 0;
}
@Override
public boolean validateBirthday(LocalDateTime birthday) {
return birthday != null;
}
@Override
public boolean validateEyeColor(EyeColor eyeColor) {
return eyeColor != null;
}
@Override
public boolean validateHairColor(HairColor hairColor) {
return hairColor != null;
}
@Override
public boolean validateLocation(Location location) {
return location != null;
}
}
|
923f28420bdcd52117a58571a990e1d21243f6e4
| 1,036 |
java
|
Java
|
src/test/java/johny/javaalgorithms/algorithms/QuickSortTest.java
|
johnythomas/JavaAlgorithms
|
2da02f2a76cacdcbfdac4034f02e8c4b83a22cf6
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/johny/javaalgorithms/algorithms/QuickSortTest.java
|
johnythomas/JavaAlgorithms
|
2da02f2a76cacdcbfdac4034f02e8c4b83a22cf6
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/johny/javaalgorithms/algorithms/QuickSortTest.java
|
johnythomas/JavaAlgorithms
|
2da02f2a76cacdcbfdac4034f02e8c4b83a22cf6
|
[
"Apache-2.0"
] | null | null | null | 26.564103 | 60 | 0.533784 | 1,001,055 |
package johny.javaalgorithms.algorithms;
import org.junit.Assert;
import org.junit.Test;
public class QuickSortTest {
@Test
public void quicksortTest() {
int arr[] = new int[]{4, 3, 5, 2, 1, 3, 2, 3};
QuickSort q = new QuickSort();
q.quickSort(arr, 0, arr.length - 1);
int sortedArr[] = new int[]{1, 2, 2, 3, 3, 3, 4, 5};
for (int i = 0; i < arr.length; i++) {
Assert.assertEquals(sortedArr[i], arr[i]);
}
}
@Test
public void quicksortTestForEmptyArray() {
int arr[] = new int[]{};
QuickSort q = new QuickSort();
q.quickSort(arr, 0, arr.length - 1);
}
@Test
public void quicksortTestForAllElementsSameArray() {
int arr[] = new int[]{1, 1, 1, 1, 1};
QuickSort q = new QuickSort();
q.quickSort(arr, 0, arr.length - 1);
int sortedArr[] = new int[]{1, 1, 1, 1, 1};
for (int i = 0; i < arr.length; i++) {
Assert.assertEquals(sortedArr[i], arr[i]);
}
}
}
|
923f284e9d1f28ad9b5e4718af6a280e088c4c80
| 3,534 |
java
|
Java
|
common/src/main/java/org/apache/rocketmq/common/protocol/route/BrokerData.java
|
AlmousZhang/incubator-rocketmq
|
dca0192c38089441e84a17043dd992c6a3c26d07
|
[
"ECL-2.0",
"Apache-2.0"
] | 361 |
2017-05-10T11:21:39.000Z
|
2022-03-30T11:24:31.000Z
|
common/src/main/java/org/apache/rocketmq/common/protocol/route/BrokerData.java
|
AlmousZhang/incubator-rocketmq
|
dca0192c38089441e84a17043dd992c6a3c26d07
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
common/src/main/java/org/apache/rocketmq/common/protocol/route/BrokerData.java
|
AlmousZhang/incubator-rocketmq
|
dca0192c38089441e84a17043dd992c6a3c26d07
|
[
"ECL-2.0",
"Apache-2.0"
] | 304 |
2017-05-11T01:55:07.000Z
|
2022-03-31T06:11:11.000Z
| 27.866142 | 93 | 0.614298 | 1,001,056 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* $Id: BrokerData.java 1835 2013-05-16 02:00:50Z [email protected] $
*/
package org.apache.rocketmq.common.protocol.route;
import org.apache.rocketmq.common.MixAll;
import java.util.HashMap;
import java.util.Map;
/**
* Broker数据
*/
public class BrokerData implements Comparable<BrokerData> {
/**
* 集群名
*/
private String cluster;
/**
* Broker名
*/
private String brokerName;
/**
* broker角色编号 和 broker地址 Map
*/
private HashMap<Long/* brokerId */, String/* broker address */> brokerAddrs;
/**
* 获取 Broker地址
* 优先级: Master > {@link #brokerAddrs}第一个
*
* @return Broker地址
*/
public String selectBrokerAddr() {
String value = this.brokerAddrs.get(MixAll.MASTER_ID);
if (null == value) {
for (Map.Entry<Long, String> entry : this.brokerAddrs.entrySet()) {
return entry.getValue();
}
}
return value;
}
public HashMap<Long, String> getBrokerAddrs() {
return brokerAddrs;
}
public void setBrokerAddrs(HashMap<Long, String> brokerAddrs) {
this.brokerAddrs = brokerAddrs;
}
public String getCluster() {
return cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((brokerAddrs == null) ? 0 : brokerAddrs.hashCode());
result = prime * result + ((brokerName == null) ? 0 : brokerName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BrokerData other = (BrokerData) obj;
if (brokerAddrs == null) {
if (other.brokerAddrs != null)
return false;
} else if (!brokerAddrs.equals(other.brokerAddrs))
return false;
if (brokerName == null) {
if (other.brokerName != null)
return false;
} else if (!brokerName.equals(other.brokerName))
return false;
return true;
}
@Override
public String toString() {
return "BrokerData [brokerName=" + brokerName + ", brokerAddrs=" + brokerAddrs + "]";
}
@Override
public int compareTo(BrokerData o) {
return this.brokerName.compareTo(o.getBrokerName());
}
public String getBrokerName() {
return brokerName;
}
public void setBrokerName(String brokerName) {
this.brokerName = brokerName;
}
}
|
923f2aadea573854778f582e10407cf5e1be4668
| 1,327 |
java
|
Java
|
abstracto-application/abstracto-modules/assignable-roles/assignable-roles-int/src/main/java/dev/sheldan/abstracto/assignableroles/exception/AssignableRolePlaceChannelDoesNotExistException.java
|
Sheldan/abstracto
|
cef46737c5f34719c80c71aa9cd68bc53aea9a68
|
[
"MIT"
] | 5 |
2020-05-27T14:18:51.000Z
|
2021-03-24T09:23:09.000Z
|
abstracto-application/abstracto-modules/assignable-roles/assignable-roles-int/src/main/java/dev/sheldan/abstracto/assignableroles/exception/AssignableRolePlaceChannelDoesNotExistException.java
|
Sheldan/abstracto
|
cef46737c5f34719c80c71aa9cd68bc53aea9a68
|
[
"MIT"
] | 5 |
2020-05-29T21:53:53.000Z
|
2021-05-26T12:19:16.000Z
|
abstracto-application/abstracto-modules/assignable-roles/assignable-roles-int/src/main/java/dev/sheldan/abstracto/assignableroles/exception/AssignableRolePlaceChannelDoesNotExistException.java
|
Sheldan/abstracto
|
cef46737c5f34719c80c71aa9cd68bc53aea9a68
|
[
"MIT"
] | null | null | null | 39.029412 | 119 | 0.762622 | 1,001,057 |
package dev.sheldan.abstracto.assignableroles.exception;
import dev.sheldan.abstracto.assignableroles.model.exception.AssignableRolePlaceChannelDoesNotExistExceptionModel;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.core.templating.Templatable;
/**
* Exception thrown in case the {@link dev.sheldan.abstracto.core.models.database.AChannel channel} in which a
* {@link dev.sheldan.abstracto.assignableroles.model.database.AssignableRolePlace place} is defined, does not exist
*/
public class AssignableRolePlaceChannelDoesNotExistException extends AbstractoRunTimeException implements Templatable {
private final AssignableRolePlaceChannelDoesNotExistExceptionModel model;
public AssignableRolePlaceChannelDoesNotExistException(Long channelId, String placeName) {
super("Assignable role place channel does not exist");
this.model = AssignableRolePlaceChannelDoesNotExistExceptionModel
.builder()
.channelId(channelId)
.placeName(placeName)
.build();
}
@Override
public String getTemplateName() {
return "assignable_role_place_channel_does_not_exist_exception";
}
@Override
public Object getTemplateModel() {
return this.model;
}
}
|
923f2bd4c68ec9060a5fc99a6ac25324247e1d2d
| 6,075 |
java
|
Java
|
wls-exporter-core/src/main/java/com/oracle/wls/exporter/PassThroughAuthenticationServlet.java
|
tomas-langer/weblogic-monitoring-exporter
|
cf9327282f4df2acdab68086dacac6942a7665bb
|
[
"UPL-1.0",
"Apache-2.0"
] | null | null | null |
wls-exporter-core/src/main/java/com/oracle/wls/exporter/PassThroughAuthenticationServlet.java
|
tomas-langer/weblogic-monitoring-exporter
|
cf9327282f4df2acdab68086dacac6942a7665bb
|
[
"UPL-1.0",
"Apache-2.0"
] | 1 |
2021-01-28T03:50:49.000Z
|
2021-01-28T03:52:50.000Z
|
wls-exporter-core/src/main/java/com/oracle/wls/exporter/PassThroughAuthenticationServlet.java
|
tomas-langer/weblogic-monitoring-exporter
|
cf9327282f4df2acdab68086dacac6942a7665bb
|
[
"UPL-1.0",
"Apache-2.0"
] | null | null | null | 44.669118 | 184 | 0.718519 | 1,001,058 |
// Copyright (c) 2017, 2020, Oracle and/or its affiliates.
// Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
package com.oracle.wls.exporter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Objects;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.oracle.wls.exporter.domain.MBeanSelector;
import com.oracle.wls.exporter.domain.QueryType;
import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import static javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED;
/**
* An abstract servlet which performs authentication by forwarding all pertinent headers between the client
* and the WLS RESTful Management services, thus using that service's security.
*/
abstract public class PassThroughAuthenticationServlet extends HttpServlet {
private final WebClientFactory webClientFactory;
private UrlBuilder urlBuilder;
PassThroughAuthenticationServlet(WebClientFactory webClientFactory) {
this.webClientFactory = webClientFactory;
}
String getAuthenticationUrl() {
return urlBuilder.createUrl(QueryType.RUNTIME_URL_PATTERN);
}
String getQueryUrl(MBeanSelector selector) {
return urlBuilder.createUrl(selector.getQueryType().getUrlPattern());
}
void reportFailure(RestPortConnectionException e) {
urlBuilder.reportFailure(e);
}
WebClient createWebClient(HttpServletRequest req) {
LiveConfiguration.setServer(req);
urlBuilder = LiveConfiguration.createUrlBuilder(req);
final WebClient webClient = webClientFactory.createClient();
webClient.addHeader("X-Requested-By", "rest-exporter");
forwardRequestHeaders(req, webClient);
return webClient;
}
private void forwardRequestHeaders(HttpServletRequest req, WebClient webClient) {
webClient.setAuthentication(req.getHeader(ServletConstants.AUTHENTICATION_HEADER));
final String sessionCookie = getSessionCookie(req);
if (sessionCookie != null)
webClient.setSessionCookie(sessionCookie);
else if (Objects.equals(webClient.getAuthentication(), ExporterSession.getAuthentication()))
webClient.setSessionCookie(ExporterSession.getSessionCookie());
}
private String getSessionCookie(HttpServletRequest req) {
for (Enumeration<String> each = req.getHeaders(ServletConstants.COOKIE_HEADER); each.hasMoreElements();) {
String sessionCookie = ExporterSession.getSessionCookie(each.nextElement());
if (sessionCookie != null) return sessionCookie;
}
return null;
}
/**
* Performs a servlet action, wrappering it with authentication handling.
*
* This involves creating an object which can make http calls to the RESTful services, configuring it to
* include the authentication header, if any, received from client. Any authentication errors from
* the services will be returned to the client.
*
* @param req the servlet request
* @param resp the servlet response
* @param authenticatedService an which actually performs calls to the RESTful services using the supplied client
*
* @throws IOException if an error occurs in the web client
* @throws ServletException if some other fatal error occurs
*/
void doWithAuthentication(HttpServletRequest req, HttpServletResponse resp, AuthenticatedService authenticatedService) throws IOException, ServletException {
try {
WebClient webClient = createWebClient(req);
performRequest(webClient, req, resp, authenticatedService);
urlBuilder.reportSuccess();
} catch (ForbiddenException e) {
resp.sendError(SC_FORBIDDEN, "Not authorized");
} catch (AuthenticationChallengeException e) {
resp.setHeader("WWW-Authenticate", e.getChallenge());
resp.sendError(SC_UNAUTHORIZED, "Authentication required");
} catch (ServerErrorException e) {
resp.sendError(e.getStatus());
} catch (RestPortConnectionException e) {
resp.setStatus(SC_INTERNAL_SERVER_ERROR);
reportUnableToContactRestApi(resp, e.getUri());
} finally {
final HttpSession session = req.getSession(false);
if (session != null) session.invalidate();
}
}
private void performRequest(WebClient webClient, HttpServletRequest req, HttpServletResponse resp, AuthenticatedService authenticatedService) throws IOException, ServletException {
do {
authenticatedService.execute(webClient, req, resp);
webClient.forwardResponseHeaders(resp);
} while (webClient.isRetryNeeded());
}
private void reportUnableToContactRestApi(HttpServletResponse resp, String uri) throws IOException {
try (ServletOutputStream out = resp.getOutputStream()) {
out.println("# Unable to contact the REST API at " + uri + ". May be using the wrong port.");
out.println("#");
out.println("# This most commonly occurs when the exporter is accessed via a load balancer");
out.println("# configured on a different port than the managed server.");
out.println("#");
out.println("# You can correct this by giving the exporter WAR an initial configuration with the");
out.println("# restPort field set to the managed server's plain text port.");
}
}
/**
* An interface describing the service wrapped by #doWithAuthentication
*/
interface AuthenticatedService {
void execute(WebClient webClient, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException;
}
}
|
923f2d7c5a152b69e490430e6a88b76db3d072d4
| 512 |
java
|
Java
|
maven-serialization-plugin/src/test/java/com/blocksberg/vsc/testmodel/good/Bar.java
|
convoi/maven-serialization-plugin
|
4364a88fa7cf66e0f8e6cd20e7a9d5aa66e1e164
|
[
"Apache-2.0"
] | null | null | null |
maven-serialization-plugin/src/test/java/com/blocksberg/vsc/testmodel/good/Bar.java
|
convoi/maven-serialization-plugin
|
4364a88fa7cf66e0f8e6cd20e7a9d5aa66e1e164
|
[
"Apache-2.0"
] | null | null | null |
maven-serialization-plugin/src/test/java/com/blocksberg/vsc/testmodel/good/Bar.java
|
convoi/maven-serialization-plugin
|
4364a88fa7cf66e0f8e6cd20e7a9d5aa66e1e164
|
[
"Apache-2.0"
] | null | null | null | 17.066667 | 42 | 0.632813 | 1,001,059 |
package com.blocksberg.vsc.testmodel.good;
import java.io.Serializable;
import java.util.Date;
/**
* //TODO class description
*/
public class Bar implements Serializable {
private String string;
private String date;
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public String getDate() {
return date;
}
public void setDate(Date date) {
this.date = date.toString();
}
}
|
923f2e8f083e2051de8e2dea4a4f7c06fee6bb3f
| 3,772 |
java
|
Java
|
src/main/java/my/devwings/contactpolicy/MainView.java
|
mydevwings/vaadin-with-left-menu
|
5945c85e4411e802c38b679c78cc25ae5ff7948d
|
[
"Unlicense"
] | null | null | null |
src/main/java/my/devwings/contactpolicy/MainView.java
|
mydevwings/vaadin-with-left-menu
|
5945c85e4411e802c38b679c78cc25ae5ff7948d
|
[
"Unlicense"
] | 4 |
2021-03-10T09:07:55.000Z
|
2021-10-06T12:39:49.000Z
|
src/main/java/my/devwings/contactpolicy/MainView.java
|
mydevwings/vaadin-with-left-menu
|
5945c85e4411e802c38b679c78cc25ae5ff7948d
|
[
"Unlicense"
] | 1 |
2020-03-01T10:17:02.000Z
|
2020-03-01T10:17:02.000Z
| 37.72 | 104 | 0.715536 | 1,001,060 |
package my.devwings.contactpolicy;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.HasComponents;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.icon.Icon;
import com.vaadin.flow.component.applayout.AppLayout;
import com.vaadin.flow.component.applayout.DrawerToggle;
import com.vaadin.flow.component.tabs.Tab;
import com.vaadin.flow.component.tabs.TabVariant;
import com.vaadin.flow.component.tabs.Tabs;
import com.vaadin.flow.component.tabs.TabsVariant;
import com.vaadin.flow.router.RouteConfiguration;
import com.vaadin.flow.router.RouterLink;
import com.vaadin.flow.server.PWA;
import com.vaadin.flow.theme.Theme;
import com.vaadin.flow.theme.lumo.Lumo;
import my.devwings.contactpolicy.views.matrixcontactspolicy.MatrixcontactspolicyView;
import my.devwings.contactpolicy.views.matrixcrosschecks.MatrixCrossChecksView;
import my.devwings.contactpolicy.views.settingsforcontactspolicy.SettingsforcontactspolicyView;
import my.devwings.contactpolicy.views.settingsformatrixcrosschecks.SettingsformatrixcrosschecksView;
import my.devwings.contactpolicy.views.thesaurus.ThesaurusView;
import my.devwings.contactpolicy.views.users.UsersView;
/**
* The main view is a top-level placeholder for other views.
*/
@JsModule("./styles/shared-styles.js")
@PWA(name = "contacts-policy", shortName = "contacts-policy")
@Theme(value = Lumo.class, variant = Lumo.LIGHT)
public class MainView extends AppLayout {
private final Tabs menu;
public MainView() {
setPrimarySection(Section.DRAWER);
addToNavbar(true, new DrawerToggle());
menu = createMenuTabs();
addToDrawer(menu);
}
private static Tabs createMenuTabs() {
final Tabs tabs = new Tabs();
tabs.setOrientation(Tabs.Orientation.VERTICAL);
tabs.addThemeVariants(TabsVariant.LUMO_MINIMAL);
tabs.setId("tabs");
tabs.add(getAvailableTabs());
return tabs;
}
private static Tab[] getAvailableTabs() {
final List<Tab> tabs = new ArrayList<>();
tabs.add(createTab("Matrix contacts policy", MatrixcontactspolicyView.class));
tabs.add(createTab("Matrix Cross Checks", MatrixCrossChecksView.class));
tabs.add(createTab("Settings for contacts policy", SettingsforcontactspolicyView.class));
tabs.add(createTab("Settings for matrix cross checks", SettingsformatrixcrosschecksView.class));
tabs.add(createTab("Thesaurus", ThesaurusView.class));
tabs.add(createTab("Users", UsersView.class));
return tabs.toArray(new Tab[tabs.size()]);
}
private static Tab createTab(String title,
Class<? extends Component> viewClass) {
return createTab(populateLink(new RouterLink(null, viewClass), title));
}
private static Tab createTab(Component content) {
final Tab tab = new Tab();
tab.add(content);
return tab;
}
private static <T extends HasComponents> T populateLink(T a, String title) {
a.add(title);
return a;
}
@Override
protected void afterNavigation() {
super.afterNavigation();
selectTab();
}
private void selectTab() {
String target = RouteConfiguration.forSessionScope()
.getUrl(getContent().getClass());
Optional<Component> tabToSelect = menu.getChildren().filter(tab -> {
Component child = tab.getChildren().findFirst().get();
return child instanceof RouterLink
&& ((RouterLink) child).getHref().equals(target);
}).findFirst();
tabToSelect.ifPresent(tab -> menu.setSelectedTab((Tab) tab));
}
}
|
923f2ea4494cf572446fee71e34bfea66fd29726
| 2,555 |
java
|
Java
|
libJzWifi/src/main/java/chipsea/wifiplug/lib/model/TimerSettingParser.java
|
crystal82/xihai_jjzz
|
852b3a9a961f446c1558034c0ab147ea2999286d
|
[
"Apache-2.0"
] | null | null | null |
libJzWifi/src/main/java/chipsea/wifiplug/lib/model/TimerSettingParser.java
|
crystal82/xihai_jjzz
|
852b3a9a961f446c1558034c0ab147ea2999286d
|
[
"Apache-2.0"
] | null | null | null |
libJzWifi/src/main/java/chipsea/wifiplug/lib/model/TimerSettingParser.java
|
crystal82/xihai_jjzz
|
852b3a9a961f446c1558034c0ab147ea2999286d
|
[
"Apache-2.0"
] | null | null | null | 21.837607 | 79 | 0.603523 | 1,001,061 |
package chipsea.wifiplug.lib.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import chipsea.wifiplug.lib.util.BytesUtil;
/**
* @Description 定时设置解析器
* @author lixun
* @CreateDate 2016/5/31
*/
public class TimerSettingParser {
/**
* 根据设备上报的二进制流解析出对应的定时设置
* @param payload 二进制流
* @return 定时设置列表
*/
public static List<TimerSetting> parse(byte[] payload){
List<TimerSetting> lstRet=new ArrayList<TimerSetting>();
if(payload==null){
return lstRet;
}
if(payload.length>8){
for(int i=0;i<payload.length;i=i+9){
TimerSetting timer=new TimerSetting();
if((payload[i] & 0x80)==0x80){
timer.isOpen=true;
}
timer.indexId= (byte)(payload[i] & 0x7f);
timer.loopSetting=payload[i+1];
if((payload[i+1] & 1)==1){
timer.isLoop=true;
String sSet=BytesUtil.byteToBit(payload[i+1]);
if(sSet.substring(6, 7).equals("1")){
timer.isMon=true;
}
if(sSet.substring(5, 6).equals("1")){
timer.isTue=true;
}
if(sSet.substring(4, 5).equals("1")){
timer.isWed=true;
}
if(sSet.substring(3, 4).equals("1")){
timer.isThurs=true;
}
if(sSet.substring(2, 3).equals("1")){
timer.isFri=true;
}
if(sSet.substring(1, 2).equals("1")){
timer.isSat=true;
}
if(sSet.substring(0, 1).equals("1")){
timer.isSun=true;
}
timer.year=0;
timer.month=0;
timer.day=0;
timer.hour=payload[i+5];
timer.minute=payload[i+6];
}else{
timer.isLoop=false;
timer.year=payload[i+2] + 2000;
timer.month=payload[i+3];
timer.day=payload[i+4];
timer.hour=payload[i+5];
timer.minute=payload[i+6];
}
timer.cmdReturn=new CmdReturn();
timer.cmdReturn.port=payload[i+7];
timer.cmdReturn.cmd=payload[i+8];
lstRet.add(timer);
}
}
return lstRet;
}
public static HashMap<Byte,ControlCmdEnum> cmdReturn2Map(CmdReturn cmdReturn){
HashMap<Byte,ControlCmdEnum> dicCommand=new HashMap<Byte,ControlCmdEnum>();
String sPort=BytesUtil.byteToBit(cmdReturn.port);
String sCmd=BytesUtil.byteToBit(cmdReturn.cmd);
for(int i=0;i<8;i++){
if(sPort.substring(i, i+1).equals("1"))
{
ControlCmdEnum cmdEnum;
if(sCmd.substring(i, i+1).equals("1")){
cmdEnum=ControlCmdEnum.Open;
}else{
cmdEnum=ControlCmdEnum.Close;
}
dicCommand.put((byte)(8-i),cmdEnum);
}
}
return dicCommand;
}
}
|
923f2f16cce0d330578bb62d4b95ad3f5c64604c
| 3,141 |
java
|
Java
|
DP/300. Longest Increasing Subsequence.java
|
Kai-Qian/Leetcode
|
f1e89ce754d2d31508ce40dcd20996a34ad3f933
|
[
"MIT"
] | 1 |
2015-12-18T22:44:22.000Z
|
2015-12-18T22:44:22.000Z
|
DP/300. Longest Increasing Subsequence.java
|
Kai-Qian/Leetcode
|
f1e89ce754d2d31508ce40dcd20996a34ad3f933
|
[
"MIT"
] | null | null | null |
DP/300. Longest Increasing Subsequence.java
|
Kai-Qian/Leetcode
|
f1e89ce754d2d31508ce40dcd20996a34ad3f933
|
[
"MIT"
] | null | null | null | 33.414894 | 185 | 0.446991 | 1,001,062 |
/*
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
*/
public class Solution {
//http://www.felix021.com/blog/read.php?1587
public int lengthOfLIS(int[] nums) {
int len = nums.length;
if(nums == null || len == 0) {
return 0;
}
int[] b = new int[len];
int position;
int max = 1;
b[0] = nums[0];
for(int i = 1; i < len; i++) {
position = findInsertPosition(b, nums[i], max);
b[position] = nums[i];
if(max < position + 1) {
max = position + 1;
}
}
return max;
}
public int findInsertPosition(int[] b, int key, int right) {
int len = b.length;
// for(int i = 0; i < right; i++) {
// System.out.println("b--->" + i + " " + b[i]);
// }
int left = 0;
//right -= 1;//如果用left<right 以及right = mid就不用right=len - 1,用right = len
// int right = len - 1;因为b.length一直都是之前设定的len,所以不能用right = len - 1来做,要传入非0 的元素的长度
int mid = left + (right - left) / 2;
while(left < right) {
if(b[mid] < key) {
left = mid + 1;
} else {
right = mid;
}
mid = left + (right - left) / 2;
}
// System.out.println("left--->" + left);
return left;
}
// public int findInsertPosition(int[] b, int key, int right) {
// int len = b.length;
// // for(int i = 0; i < right; i++) {
// // System.out.println("b--->" + i + " " + b[i]);
// // }
// int left = 0;
// right -= 1;//如果用left<=right 以及right = mid - 1就用right=len - 1
// // int right = len - 1;因为b.length一直都是之前设定的len,所以不能用right = len - 1来做,要传入非0 的元素的长度
// int mid = left + (right - left) / 2;
// while(left <= right) {
// if(b[mid] < key) {
// left = mid + 1;
// } else {
// right = mid - 1;
// }
// mid = left + (right - left) / 2;
// }
// // System.out.println("left--->" + left);
// return left;
// }
/*
http://www.360doc.com/content/13/0601/00/8076359_289597587.shtml#
*/
// public int lengthOfLIS(int[] nums) {
// int len = nums.length;
// int[] d = new int[len];
// int max = 0;
// for(int i = 0; i < len; i++) {
// d[i] = 1;
// for(int j = 0; j < i; j++) {
// if(nums[i] > nums[j] && d[j] + 1 > d[i]) {
// d[i] = d[j] + 1;
// }
// }
// if(d[i] > max) {
// max = d[i];
// }
// }
// return max;
// }
}
|
923f2f737f90741031210dff1e7bedd8a8cda311
| 12,542 |
java
|
Java
|
src/optimization/LBFGSLinearRegression.java
|
vietansegan/segan
|
27f5127f3a3055c8eda64d9cf2547172fa67170d
|
[
"Apache-2.0"
] | 13 |
2015-07-28T07:09:59.000Z
|
2020-06-22T11:45:53.000Z
|
src/optimization/LBFGSLinearRegression.java
|
vietansegan/segan
|
27f5127f3a3055c8eda64d9cf2547172fa67170d
|
[
"Apache-2.0"
] | 1 |
2015-10-16T22:44:52.000Z
|
2015-10-25T20:28:03.000Z
|
src/optimization/LBFGSLinearRegression.java
|
vietansegan/segan
|
27f5127f3a3055c8eda64d9cf2547172fa67170d
|
[
"Apache-2.0"
] | 14 |
2015-01-13T00:51:12.000Z
|
2022-03-28T09:08:04.000Z
| 37.663664 | 104 | 0.52081 | 1,001,063 |
package optimization;
import cc.mallet.optimize.LimitedMemoryBFGS;
import core.AbstractLinearModel;
import java.io.BufferedWriter;
import java.io.File;
import java.util.ArrayList;
import util.IOUtils;
import util.MiscUtils;
import util.SparseVector;
import util.evaluation.Measurement;
import util.evaluation.RegressionEvaluation;
/**
*
* @author vietan
*/
public class LBFGSLinearRegression extends AbstractLinearModel {
private final double mu;
private final double sigma;
private final double rho;
public LBFGSLinearRegression(String basename,
double mu, double sigma, double rho) {
super(basename);
this.mu = mu;
this.sigma = sigma;
this.rho = rho;
}
@Override
public String getName() {
return this.name
+ "_r-" + MiscUtils.formatDouble(rho)
+ "_m-" + MiscUtils.formatDouble(mu)
+ "_s-" + MiscUtils.formatDouble(sigma);
}
public double getMu() {
return this.mu;
}
public double getSigma() {
return this.sigma;
}
public void trainAdaptive(int[][] docWords, ArrayList<Integer> docIndices,
double[] docResponses, int V) {
if (docIndices == null) {
docIndices = new ArrayList<>();
for (int dd = 0; dd < docWords.length; dd++) {
docIndices.add(dd);
}
}
int D = docIndices.size();
double[] responses = new double[D];
double[] rhos = new double[D];
SparseVector[] designMatrix = new SparseVector[D];
for (int ii = 0; ii < D; ii++) {
int dd = docIndices.get(ii);
responses[ii] = docResponses[dd];
designMatrix[ii] = new SparseVector(V);
double val = 1.0 / docWords[dd].length;
for (int nn = 0; nn < docWords[dd].length; nn++) {
designMatrix[ii].change(docWords[dd][nn], val);
}
rhos[ii] = this.rho / docWords[dd].length;
}
if (verbose) {
System.out.println("Training ...");
System.out.println("--- # instances: " + designMatrix.length + ". " + responses.length);
System.out.println("--- # features: " + designMatrix[0].getDimension() + ". " + V);
}
RidgeLinearRegressionOptimizable optimizable = new RidgeLinearRegressionOptimizable(
responses, new double[V], designMatrix, rhos, mu, sigma);
LimitedMemoryBFGS optimizer = new LimitedMemoryBFGS(optimizable);
try {
optimizer.optimize();
} catch (Exception ex) {
ex.printStackTrace();
}
this.weights = new double[V];
for (int kk = 0; kk < V; kk++) {
this.weights[kk] = optimizable.getParameter(kk);
}
}
public void train(int[][] docWords, ArrayList<Integer> docIndices,
double[] docResponses, int V) {
if (docIndices == null) {
docIndices = new ArrayList<>();
for (int dd = 0; dd < docWords.length; dd++) {
docIndices.add(dd);
}
}
int D = docIndices.size();
double[] responses = new double[D];
SparseVector[] designMatrix = new SparseVector[D];
for (int ii = 0; ii < D; ii++) {
int dd = docIndices.get(ii);
responses[ii] = docResponses[dd];
designMatrix[ii] = new SparseVector(V);
double val = 1.0 / docWords[dd].length;
for (int nn = 0; nn < docWords[dd].length; nn++) {
designMatrix[ii].change(docWords[dd][nn], val);
}
}
train(designMatrix, responses, V);
}
public void train(SparseVector[] designMatrix, double[] responses, int K) {
if (verbose) {
System.out.println("Training ...");
System.out.println("--- # instances: " + designMatrix.length + ". " + responses.length);
System.out.println("--- # features: " + designMatrix[0].getDimension() + ". " + K);
}
RidgeLinearRegressionOptimizable optimizable = new RidgeLinearRegressionOptimizable(
responses, new double[K], designMatrix, rho, mu, sigma);
LimitedMemoryBFGS optimizer = new LimitedMemoryBFGS(optimizable);
try {
optimizer.optimize();
} catch (Exception ex) {
ex.printStackTrace();
}
this.weights = new double[K];
for (int kk = 0; kk < K; kk++) {
this.weights[kk] = optimizable.getParameter(kk);
}
}
public void train(SparseVector[] designMatrix, double[] responses, double[] initParams) {
if (verbose) {
System.out.println("Training ...");
System.out.println("--- # instances: " + designMatrix.length + ". " + responses.length);
System.out.println("--- # features: " + designMatrix[0].getDimension());
}
RidgeLinearRegressionOptimizable optimizable = new RidgeLinearRegressionOptimizable(
responses, initParams, designMatrix, rho, mu, sigma);
LimitedMemoryBFGS optimizer = new LimitedMemoryBFGS(optimizable);
try {
optimizer.optimize();
} catch (Exception ex) {
ex.printStackTrace();
}
this.weights = new double[initParams.length];
for (int kk = 0; kk < initParams.length; kk++) {
this.weights[kk] = optimizable.getParameter(kk);
}
}
public double[] test(int[][] docWords, ArrayList<Integer> docIndices, int V) {
if (docIndices == null) {
docIndices = new ArrayList<>();
for (int dd = 0; dd < docWords.length; dd++) {
docIndices.add(dd);
}
}
int D = docIndices.size();
SparseVector[] designMatrix = new SparseVector[D];
for (int ii = 0; ii < D; ii++) {
int dd = docIndices.get(ii);
designMatrix[ii] = new SparseVector(V);
double val = 1.0 / docWords[dd].length;
for (int nn = 0; nn < docWords[dd].length; nn++) {
designMatrix[ii].change(docWords[dd][nn], val);
}
}
return test(designMatrix);
}
public double[] test(SparseVector[] designMatrix) {
if (verbose) {
System.out.println("Testing ...");
System.out.println("--- # instances: " + designMatrix.length);
System.out.println("--- # features: " + designMatrix[0].getDimension());
}
double[] predictions = new double[designMatrix.length];
for (int d = 0; d < predictions.length; d++) {
predictions[d] = designMatrix[d].dotProduct(weights);
}
return predictions;
}
public void tune(File outputFile,
int[][] trDocWords,
ArrayList<Integer> trDocIndices,
double[] trDocResponses,
int[][] deDocWords,
ArrayList<Integer> deDocIndices,
double[] deDocResponses,
int K) {
if (trDocIndices == null) {
trDocIndices = new ArrayList<>();
for (int dd = 0; dd < trDocWords.length; dd++) {
trDocIndices.add(dd);
}
}
int Dtr = trDocIndices.size();
double[] trResponses = new double[Dtr];
SparseVector[] trDesignMatrix = new SparseVector[Dtr];
for (int ii = 0; ii < Dtr; ii++) {
int dd = trDocIndices.get(ii);
trResponses[ii] = trDocResponses[dd];
trDesignMatrix[ii] = new SparseVector(K);
double val = 1.0 / trDocWords[dd].length;
for (int nn = 0; nn < trDocWords[dd].length; nn++) {
trDesignMatrix[ii].change(trDocWords[dd][nn], val);
}
}
if (deDocIndices == null) {
deDocIndices = new ArrayList<>();
for (int dd = 0; dd < deDocWords.length; dd++) {
deDocIndices.add(dd);
}
}
int Dde = deDocIndices.size();
double[] deResponses = new double[Dde];
SparseVector[] deDesignMatrix = new SparseVector[Dde];
for (int ii = 0; ii < Dde; ii++) {
int dd = deDocIndices.get(ii);
deResponses[ii] = deDocResponses[dd];
deDesignMatrix[ii] = new SparseVector(K);
double val = 1.0 / deDocWords[dd].length;
for (int nn = 0; nn < deDocWords[dd].length; nn++) {
deDesignMatrix[ii].change(deDocWords[dd][nn], val);
}
}
tune(outputFile, trDesignMatrix, trResponses, deDesignMatrix, deResponses, K, null, null);
}
public void tune(File outputFile,
SparseVector[] trDesignMatrix, double[] trResponses,
SparseVector[] deDesignMatrix, double[] deResponses, int K,
ArrayList<Double> rhoList, ArrayList<Double> sigmaList) {
if (verbose) {
System.out.println("Tuning ...");
System.out.println("--- Output file: " + outputFile);
System.out.println("--- Train: # instances: " + trDesignMatrix.length);
System.out.println("--- Dev: # instances: " + deDesignMatrix.length);
System.out.println("--- # features: " + trDesignMatrix[0].getDimension() + ". " + K);
}
if (rhoList == null) {
rhoList = new ArrayList<>();
rhoList.add(0.1);
rhoList.add(0.25);
rhoList.add(0.5);
rhoList.add(1.0);
}
if (sigmaList == null) {
sigmaList = new ArrayList<>();
sigmaList.add(0.1);
sigmaList.add(0.5);
sigmaList.add(1.0);
sigmaList.add(2.5);
sigmaList.add(5.0);
sigmaList.add(10.0);
sigmaList.add(15.0);
sigmaList.add(50.0);
}
double m = 0.0;
try {
boolean header = true;
BufferedWriter writer = IOUtils.getBufferedWriter(outputFile);
for (double r : rhoList) {
for (double s : sigmaList) {
if (verbose) {
System.out.println("*** rho = " + r + ". mu = " + m
+ ". sigma = " + s);
}
RidgeLinearRegressionOptimizable optimizable = new RidgeLinearRegressionOptimizable(
trResponses, new double[K], trDesignMatrix, r, m, s);
LimitedMemoryBFGS optimizer = new LimitedMemoryBFGS(optimizable);
try {
optimizer.optimize();
} catch (Exception ex) {
ex.printStackTrace();
}
double[] ws = new double[K];
for (int kk = 0; kk < K; kk++) {
ws[kk] = optimizable.getParameter(kk);
}
double[] preds = new double[deDesignMatrix.length];
for (int dd = 0; dd < preds.length; dd++) {
preds[dd] = deDesignMatrix[dd].dotProduct(ws);
}
RegressionEvaluation eval = new RegressionEvaluation(deResponses, preds);
eval.computeCorrelationCoefficient();
eval.computeMeanSquareError();
eval.computeMeanAbsoluteError();
eval.computeRSquared();
eval.computePredictiveRSquared();
ArrayList<Measurement> measurements = eval.getMeasurements();
measurements.add(new Measurement("N", preds.length));
if (header) {
writer.write("Rho\tSigma");
for (Measurement measurement : measurements) {
writer.write("\t" + measurement.getName());
}
writer.write("\n");
header = false;
}
writer.write(r + "\t" + s);
for (Measurement measurement : measurements) {
writer.write("\t" + measurement.getValue());
}
writer.write("\n");
}
}
writer.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Exception while outputing to " + outputFile);
}
}
}
|
923f2fb26402e4dee0c1a49acc6e8b7dce09a7b2
| 656 |
java
|
Java
|
src/com/adam/test/RunningSum.java
|
martrics/leetcode
|
9e0afbd1b14817c57880cf050a35b8dd951846eb
|
[
"MIT"
] | null | null | null |
src/com/adam/test/RunningSum.java
|
martrics/leetcode
|
9e0afbd1b14817c57880cf050a35b8dd951846eb
|
[
"MIT"
] | null | null | null |
src/com/adam/test/RunningSum.java
|
martrics/leetcode
|
9e0afbd1b14817c57880cf050a35b8dd951846eb
|
[
"MIT"
] | null | null | null | 27.333333 | 51 | 0.478659 | 1,001,064 |
package com.adam.test;
public class RunningSum {
public static void main(String[] args){
int[] nums = new int[]{3,1,2,10,1};
Solution solution = new Solution();
int[] result = solution.runningSum(nums);
for(int val : result){
System.out.println(val);
}
}
static class Solution {
public int[] runningSum(int[] nums) {
int[] result = new int[nums.length];
result[0] = nums[0];
for(int i = 1; i < nums.length; i++){
result[i] = result[i-1] + nums[i];
}
return result;
}
}
}
|
923f306096c1b0856041a9fa56e8208c3e6b4226
| 3,249 |
java
|
Java
|
open-metadata-implementation/access-services/analytics-modeling/analytics-modeling-server/src/main/java/org/odpi/openmetadata/accessservices/analyticsmodeling/synchronization/model/AnalyticsAsset.java
|
NishaNagasimha/egeria
|
247f61d59f5eca645c77d6e99b59a38f925cae7e
|
[
"CC-BY-4.0"
] | null | null | null |
open-metadata-implementation/access-services/analytics-modeling/analytics-modeling-server/src/main/java/org/odpi/openmetadata/accessservices/analyticsmodeling/synchronization/model/AnalyticsAsset.java
|
NishaNagasimha/egeria
|
247f61d59f5eca645c77d6e99b59a38f925cae7e
|
[
"CC-BY-4.0"
] | 1,129 |
2020-11-18T11:40:23.000Z
|
2022-03-01T01:27:37.000Z
|
open-metadata-implementation/access-services/analytics-modeling/analytics-modeling-server/src/main/java/org/odpi/openmetadata/accessservices/analyticsmodeling/synchronization/model/AnalyticsAsset.java
|
NishaNagasimha/egeria
|
247f61d59f5eca645c77d6e99b59a38f925cae7e
|
[
"CC-BY-4.0"
] | null | null | null | 20.96129 | 90 | 0.707602 | 1,001,065 |
/* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.openmetadata.accessservices.analyticsmodeling.synchronization.model;
import java.util.ArrayList;
import java.util.List;
import org.odpi.openmetadata.accessservices.analyticsmodeling.synchronization.beans.Asset;
public class AnalyticsAsset extends Asset {
private String uid; // external unique identifiers
private String location; // external location of the asset
private String type; // type defines asset content
private List<String> sourceGuid; // GUIDs of external metadata objects
private List<AssetReference> reference;
private List<MetadataContainer> container;
private List<MetadataItem> item;
private List<MetadataContainer> visualization;
public void addContainer(MetadataContainer child) {
if (container == null) {
container = new ArrayList<>();
}
container.add(child);
}
public MetadataContainer removeContainer(int index) {
if (container != null && container.size() > index) {
return container.remove(index);
}
return null;
}
public MetadataContainer getContainer(int index) {
if (container != null && container.size() > index) {
return container.get(index);
}
return null;
}
public void addItem(MetadataItem item) {
if (this.item == null) {
this.item = new ArrayList<>();
}
this.item.add(item);
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public List<String> getSourceGuid() {
return sourceGuid;
}
public void setSourceGuid(List<String> sourceGuid) {
this.sourceGuid = sourceGuid;
}
public void addSourceGuid(String guid) {
if (sourceGuid == null) {
sourceGuid = new ArrayList<>();
}
sourceGuid.add(guid);
}
public List<AssetReference> getReference() {
return reference;
}
public void setReference(List<AssetReference> reference) {
this.reference = reference;
}
public void addReference(AssetReference theReference) {
if (reference == null) {
reference = new ArrayList<>();
}
reference.add(theReference);
}
public List<MetadataContainer> getContainer() {
return container;
}
public void setContainer(List<MetadataContainer> container) {
this.container = container;
}
public List<MetadataItem> getItem() {
return item;
}
public void setItem(List<MetadataItem> items) {
this.item = items;
}
/**
* @return the visualization
*/
public List<MetadataContainer> getVisualization() {
return visualization;
}
/**
* @param visualization the visualization to set
*/
public void setVisualization(List<MetadataContainer> visualization) {
this.visualization = visualization;
}
/**
* @return the location
*/
public String getLocation() {
return location;
}
/**
* @param location the location to set
*/
public void setLocation(String location) {
this.location = location;
}
public boolean isVisualization() {
return visualization != null;
}
public boolean hasMetadataModule() {
return (container != null && !container.isEmpty())
|| (item != null && !item.isEmpty());
}
}
|
923f325a3f9836ef8afdbabebeb940d0423af25a
| 1,846 |
java
|
Java
|
src/main/java/com/nway/platform/wform/component/impl/SingleSelectComponent.java
|
zdtjss/wform
|
ddca10ca99cf6ea4f100a3d3e09f0036cfdee12c
|
[
"Apache-2.0"
] | 2 |
2018-01-16T09:32:27.000Z
|
2018-11-14T09:31:03.000Z
|
src/main/java/com/nway/platform/wform/component/impl/SingleSelectComponent.java
|
zdtjss/wform
|
ddca10ca99cf6ea4f100a3d3e09f0036cfdee12c
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/nway/platform/wform/component/impl/SingleSelectComponent.java
|
zdtjss/wform
|
ddca10ca99cf6ea4f100a3d3e09f0036cfdee12c
|
[
"Apache-2.0"
] | 4 |
2018-01-04T10:30:48.000Z
|
2019-05-19T14:06:16.000Z
| 22.512195 | 114 | 0.725352 | 1,001,066 |
package com.nway.platform.wform.component.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import com.nway.platform.wform.component.BaseComponent;
import com.nway.platform.wform.component.Initializable;
import com.nway.platform.wform.design.db.datatype.DataType;
import com.nway.platform.wform.design.service.PageAccess;
@Component("singleSelect")
public class SingleSelectComponent implements BaseComponent, Initializable {
@Autowired
private DataType dataType;
@Autowired
private PageAccess formPageAccess;
@Autowired
private JdbcTemplate jdbcTemplate;
public Object getValue(Object value) {
return value;
}
@Override
public Object init(String pageId, String fieldName) {
Map<String, Object> map = new HashMap<String, Object>();
Map<String, Map<String, String>> fieldAttrsMap = formPageAccess.listFieldAttr(pageId);
if (fieldAttrsMap != null) {
Map<String, String> attrMap = fieldAttrsMap.get(fieldName);
String sql = attrMap.get("sql");
if (sql != null) {
map = reform(jdbcTemplate.queryForList(sql));
}
String dic = attrMap.get("dic");
if (dic != null) {
map = reform(jdbcTemplate.queryForList("SELECT CODE key,VALUE FROM T_DICTIONARY WHERE PARENT_CODE = ?", dic));
}
}
return map;
}
private Map<String, Object> reform(List<Map<String, Object>> orgin) {
Map<String, Object> kvMap = new HashMap<String, Object>();
for(Map<String, Object> per : orgin) {
kvMap.put(per.get("KEY").toString(), per.get("VALUE"));
}
return kvMap;
}
@Override
public String getDataType(int capacity) {
return dataType.getForString(capacity);
}
}
|
923f336a5dfa93584f3637add39f64c5f98f76e8
| 946 |
java
|
Java
|
src/com/decylus/study/t200/k260/Solution.java
|
decylus/leetcode-study
|
74f4ea7e3d55ad2dc7cc4ebbf3945e9224c2e17a
|
[
"MIT"
] | null | null | null |
src/com/decylus/study/t200/k260/Solution.java
|
decylus/leetcode-study
|
74f4ea7e3d55ad2dc7cc4ebbf3945e9224c2e17a
|
[
"MIT"
] | null | null | null |
src/com/decylus/study/t200/k260/Solution.java
|
decylus/leetcode-study
|
74f4ea7e3d55ad2dc7cc4ebbf3945e9224c2e17a
|
[
"MIT"
] | null | null | null | 22.52381 | 69 | 0.523256 | 1,001,067 |
package com.decylus.study.t200.k260;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Created on 2019-11-03.
*
* @author jiawei
*/
public class Solution {
public int[] singleNumber(int[] nums) {
Set<Integer> numsList = new HashSet<>(nums.length/2 + 2);
for (int num : nums){
if (numsList.contains(num)){
numsList.remove(num);
}else{
numsList.add(num);
}
}
int[] result = new int[2];
int i = 0;
for (Integer integer : numsList) {
result[i] = integer;
i++;
}
return result;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] result = solution.singleNumber(new int[]{1,2,1,3,2,5});
for (int i : result) {
System.out.println(i);
}
}
}
|
923f3395e7ebef98b1e8255f772388a4dca8b6c1
| 5,160 |
java
|
Java
|
ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/handlers/configuration/ConfigurationHandlerDescription.java
|
chrisr3/felix-dev
|
f3597cc709d1469d36314b3bff9cb1e609b6cdab
|
[
"Apache-2.0"
] | 73 |
2020-02-28T19:50:03.000Z
|
2022-03-31T14:40:18.000Z
|
ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/handlers/configuration/ConfigurationHandlerDescription.java
|
chrisr3/felix-dev
|
f3597cc709d1469d36314b3bff9cb1e609b6cdab
|
[
"Apache-2.0"
] | 50 |
2020-03-02T10:53:06.000Z
|
2022-03-25T13:23:51.000Z
|
ipojo/runtime/core/src/main/java/org/apache/felix/ipojo/handlers/configuration/ConfigurationHandlerDescription.java
|
chrisr3/felix-dev
|
f3597cc709d1469d36314b3bff9cb1e609b6cdab
|
[
"Apache-2.0"
] | 97 |
2020-03-02T10:40:18.000Z
|
2022-03-25T01:13:32.000Z
| 33.745098 | 131 | 0.638001 | 1,001,068 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.felix.ipojo.handlers.configuration;
import java.util.List;
import org.apache.felix.ipojo.architecture.HandlerDescription;
import org.apache.felix.ipojo.architecture.PropertyDescription;
import org.apache.felix.ipojo.metadata.Attribute;
import org.apache.felix.ipojo.metadata.Element;
import org.apache.felix.ipojo.util.Property;
/**
* Configuration handler description.
*
* @author <a href="mailto:[email protected]">Felix Project Team</a>
*/
public class ConfigurationHandlerDescription extends HandlerDescription {
/**
* The property descriptions.
*/
private PropertyDescription[] m_properties;
/**
* The Managed Service PID.
* <code>null</code> if not set.
*/
private String m_pid;
/**
* The configuration handler.
*/
private final ConfigurationHandler m_conf;
/**
* Creates the description object for the configuration handler description.
* @param handler the configuration handler.
* @param props the list of properties.
* @param pid the managed service pid or <code>null</code> if not set.
*/
public ConfigurationHandlerDescription(ConfigurationHandler handler, List/*<Property>*/ props, String pid) {
super(handler);
m_conf = handler;
m_properties = new PropertyDescription[props.size()];
for (int i = 0; i < props.size(); i++) {
m_properties[i] = new PropertyDescription((Property) props.get(i));
}
m_pid = pid;
}
/**
* The handler information.
* @return the handler description.
* @see org.apache.felix.ipojo.architecture.HandlerDescription#getHandlerInfo()
*/
public Element getHandlerInfo() {
Element elem = super.getHandlerInfo();
if (m_pid != null) {
elem.addAttribute(new Attribute("managed.service.pid", m_pid));
}
for (int i = 0; i < m_properties.length; i++) {
String name = m_properties[i].getName();
Object value = m_properties[i].getValue();
Element property = new Element("property", "");
elem.addElement(property);
if (name != null) {
property.addAttribute(new Attribute("name", name));
}
if (value != null) {
if (value == Property.NO_VALUE) {
property.addAttribute(new Attribute("value", "NO_VALUE"));
} else {
property.addAttribute(new Attribute("value", value.toString()));
}
}
}
return elem;
}
/**
* Gets the properties.
* @return the property set.
*/
public PropertyDescription[] getProperties() {
return m_properties;
}
/**
* Gets a property by name.
* @param name the property name
* @return the property description with the given name, {@code null} if there is no property with the given name.
* @since 1.11.0
*/
public PropertyDescription getPropertyByName(String name) {
for (PropertyDescription desc :m_properties) {
if (name.equals(desc.getName())) {
return desc;
}
}
return null;
}
/**
* Gets the managed service pid.
* @return the managed service pid of <code>null</code>
* if not set.
*/
public String getManagedServicePid() {
return m_pid;
}
/**
* Add the given listener to the configuration handler's list of listeners.
*
* @param listener the {@code ConfigurationListener} object to be added
* @throws NullPointerException if {@code listener} is {@code null}
*/
public void addListener(ConfigurationListener listener) {
m_conf.addListener(listener);
}
/**
* Remove the given listener from the configuration handler's list of listeners.
*
* @param listener the {@code ConfigurationListener} object to be removed
* @throws NullPointerException if {@code listener} is {@code null}
* @throws java.util.NoSuchElementException if {@code listener} wasn't present the in configuration handler's list of listeners
*/
public void removeListener(ConfigurationListener listener) {
m_conf.removeListener(listener);
}
}
|
923f33aa4d3c9f35d2208aad56789831a2d3d80a
| 823 |
java
|
Java
|
framework/src/main/java/org/robobinding/binder/ViewBindingLifecycle.java
|
icse18-refactorings/RoboBinding
|
d5e213d012b2a845fe809c1c6c58ec83ef94b82e
|
[
"Apache-2.0"
] | 1,020 |
2015-01-03T16:39:05.000Z
|
2021-11-25T10:21:46.000Z
|
framework/src/main/java/org/robobinding/binder/ViewBindingLifecycle.java
|
icse18-refactorings/RoboBinding
|
d5e213d012b2a845fe809c1c6c58ec83ef94b82e
|
[
"Apache-2.0"
] | 81 |
2015-01-08T01:09:16.000Z
|
2019-08-20T06:22:12.000Z
|
framework/src/main/java/org/robobinding/binder/ViewBindingLifecycle.java
|
icse18-refactorings/RoboBinding
|
d5e213d012b2a845fe809c1c6c58ec83ef94b82e
|
[
"Apache-2.0"
] | 232 |
2015-01-06T09:46:13.000Z
|
2021-07-07T02:11:27.000Z
| 27.433333 | 87 | 0.770352 | 1,001,069 |
package org.robobinding.binder;
import org.robobinding.BindingContext;
import org.robobinding.binder.ViewHierarchyInflationErrorsException.ErrorFormatter;
/**
*
* @since 1.0
* @version $Revision: 1.0 $
* @author Cheng Wei
*/
public class ViewBindingLifecycle {
private final ErrorFormatter errorFormatter;
public ViewBindingLifecycle(ErrorFormatter errorFormatter) {
this.errorFormatter = errorFormatter;
}
public void run(InflatedView inflatedView, BindingContext bindingContext) {
/*BindingContext bindingContext = bindingContextFactory.create(presentationModel);*/
inflatedView.bindChildViews(bindingContext);
inflatedView.assertNoErrors(errorFormatter);
if (bindingContext.shouldPreInitializeViews()) {
inflatedView.preinitializeViews(bindingContext);
}
}
}
|
923f342a0d92aa9234bf518386834af8a667195e
| 9,755 |
java
|
Java
|
backend/manager/modules/restapi/types/src/main/java/org/ovirt/engine/api/restapi/types/QuotaMapper.java
|
emesika/ovirt-engine
|
db6458e688eeb385b683a0c9c5530917cd6dfe5f
|
[
"Apache-2.0"
] | 347 |
2015-01-20T14:13:21.000Z
|
2022-03-31T17:53:11.000Z
|
backend/manager/modules/restapi/types/src/main/java/org/ovirt/engine/api/restapi/types/QuotaMapper.java
|
emesika/ovirt-engine
|
db6458e688eeb385b683a0c9c5530917cd6dfe5f
|
[
"Apache-2.0"
] | 128 |
2015-05-22T19:14:32.000Z
|
2022-03-31T08:11:18.000Z
|
backend/manager/modules/restapi/types/src/main/java/org/ovirt/engine/api/restapi/types/QuotaMapper.java
|
emesika/ovirt-engine
|
db6458e688eeb385b683a0c9c5530917cd6dfe5f
|
[
"Apache-2.0"
] | 202 |
2015-01-04T06:20:49.000Z
|
2022-03-08T15:30:08.000Z
| 46.232227 | 157 | 0.634854 | 1,001,070 |
package org.ovirt.engine.api.restapi.types;
import org.ovirt.engine.api.model.Cluster;
import org.ovirt.engine.api.model.DataCenter;
import org.ovirt.engine.api.model.Quota;
import org.ovirt.engine.api.model.QuotaClusterLimit;
import org.ovirt.engine.api.model.QuotaStorageLimit;
import org.ovirt.engine.api.model.StorageDomain;
import org.ovirt.engine.api.restapi.utils.GuidUtils;
import org.ovirt.engine.core.common.businessentities.QuotaCluster;
import org.ovirt.engine.core.common.businessentities.QuotaStorage;
import org.ovirt.engine.core.compat.Guid;
public class QuotaMapper {
@Mapping(from = Quota.class, to = org.ovirt.engine.core.common.businessentities.Quota.class)
public static org.ovirt.engine.core.common.businessentities.Quota map(Quota model, org.ovirt.engine.core.common.businessentities.Quota template) {
org.ovirt.engine.core.common.businessentities.Quota entity = (template==null) ? new org.ovirt.engine.core.common.businessentities.Quota() : template;
if (model.isSetId()) {
entity.setId(GuidUtils.asGuid(model.getId()));
}
if (model.isSetName()) {
entity.setQuotaName(model.getName());
}
if (model.isSetDescription()) {
entity.setDescription(model.getDescription());
}
if (model.isSetDataCenter()) {
entity.setStoragePoolId(GuidUtils.asGuid(model.getDataCenter().getId()));
}
if (model.isSetClusterHardLimitPct()) {
entity.setGraceClusterPercentage(model.getClusterHardLimitPct());
}
if (model.isSetStorageHardLimitPct()) {
entity.setGraceStoragePercentage(model.getStorageHardLimitPct());
}
if (model.isSetClusterSoftLimitPct()) {
entity.setThresholdClusterPercentage(model.getClusterSoftLimitPct());
}
if (model.isSetStorageSoftLimitPct()) {
entity.setThresholdStoragePercentage(model.getStorageSoftLimitPct());
}
return entity;
}
@Mapping(from = org.ovirt.engine.core.common.businessentities.Quota.class, to = Quota.class)
public static Quota map(org.ovirt.engine.core.common.businessentities.Quota template, Quota model) {
Quota ret = (model==null) ? new Quota() : model;
if (template.getId()!=null) {
ret.setId(template.getId().toString());
}
if (template.getQuotaName()!=null) {
ret.setName(template.getQuotaName());
}
if (template.getDescription()!=null) {
ret.setDescription(template.getDescription());
}
if (template.getStoragePoolId()!=null) {
if (ret.getDataCenter()==null) {
ret.setDataCenter(new DataCenter());
}
ret.getDataCenter().setId(template.getStoragePoolId().toString());
}
ret.setClusterHardLimitPct(template.getGraceClusterPercentage());
ret.setStorageHardLimitPct(template.getGraceStoragePercentage());
ret.setClusterSoftLimitPct(template.getThresholdClusterPercentage());
ret.setStorageSoftLimitPct(template.getThresholdStoragePercentage());
return ret;
}
@Mapping(from = org.ovirt.engine.core.common.businessentities.Quota.class, to = QuotaStorageLimit.class)
public static QuotaStorageLimit map(org.ovirt.engine.core.common.businessentities.Quota entity,
QuotaStorageLimit template) {
QuotaStorageLimit model = template != null ? template : new QuotaStorageLimit();
Guid guid = GuidUtils.asGuid(model.getId());
// global
if (guid.equals(entity.getId())) {
map(model, entity.getGlobalQuotaStorage(), null, entity.getStoragePoolId().toString(), entity.getId()
.toString());
} else { // specific
if (entity.getQuotaStorages() != null) {
for (QuotaStorage quotaStorage : entity.getQuotaStorages()) {
if (quotaStorage.getStorageId() != null && quotaStorage.getStorageId().equals(guid)) {
map(model, quotaStorage, quotaStorage.getStorageId().toString(), entity.getStoragePoolId()
.toString(), entity.getId().toString());
}
}
}
}
return model;
}
private static void map(QuotaStorageLimit model,
QuotaStorage quotaStorage,
String storageDomainId,
String dataCenterId,
String quotaId) {
model.setQuota(new Quota());
model.getQuota().setId(quotaId);
model.getQuota().setDataCenter(new DataCenter());
model.getQuota().getDataCenter().setId(dataCenterId);
if (storageDomainId != null) {
model.setStorageDomain(new StorageDomain());
model.getStorageDomain().setId(storageDomainId);
}
if (quotaStorage.getStorageSizeGB() != null) {
model.setLimit(quotaStorage.getStorageSizeGB());
}
if (quotaStorage.getStorageSizeGBUsage() != null) {
model.setUsage(quotaStorage.getStorageSizeGBUsage());
}
}
@Mapping(from = QuotaStorageLimit.class, to = org.ovirt.engine.core.common.businessentities.Quota.class)
public static org.ovirt.engine.core.common.businessentities.Quota map(QuotaStorageLimit model,
org.ovirt.engine.core.common.businessentities.Quota template) {
org.ovirt.engine.core.common.businessentities.Quota entity =
template != null ? template : new org.ovirt.engine.core.common.businessentities.Quota();
QuotaStorage quotaStorage = new QuotaStorage();
if (model.isSetLimit()) {
quotaStorage.setStorageSizeGB(model.getLimit());
}
// specific SD
if(model.isSetStorageDomain() && model.getStorageDomain().isSetId()) {
quotaStorage.setStorageId(GuidUtils.asGuid(model.getStorageDomain().getId()));
entity.getQuotaStorages().add(quotaStorage);
} else { // global
entity.setGlobalQuotaStorage(quotaStorage);
}
return entity;
}
@Mapping(from = org.ovirt.engine.core.common.businessentities.Quota.class, to = QuotaClusterLimit.class)
public static QuotaClusterLimit map(org.ovirt.engine.core.common.businessentities.Quota entity,
QuotaClusterLimit template) {
QuotaClusterLimit model = template != null ? template : new QuotaClusterLimit();
Guid guid = GuidUtils.asGuid(model.getId());
// global
if (guid.equals(entity.getId())) {
map(model, entity.getGlobalQuotaCluster(), null, entity.getStoragePoolId().toString(), entity.getId()
.toString());
} else { // specific
if (entity.getQuotaClusters() != null) {
for (QuotaCluster quotaCluster : entity.getQuotaClusters()) {
if (quotaCluster.getClusterId() != null && quotaCluster.getClusterId().equals(guid)) {
map(model, quotaCluster, quotaCluster.getClusterId().toString(), entity.getStoragePoolId()
.toString(), entity.getId().toString());
}
}
}
}
return model;
}
private static void map(QuotaClusterLimit template,
QuotaCluster quotaCluster,
String clusterId,
String dataCenterId,
String quotaId) {
template.setQuota(new Quota());
template.getQuota().setId(quotaId);
template.getQuota().setDataCenter(new DataCenter());
template.getQuota().getDataCenter().setId(dataCenterId);
if (clusterId != null) {
template.setCluster(new Cluster());
template.getCluster().setId(clusterId);
}
if (quotaCluster.getMemSizeMB() != null) {
// show GB instead of MB (ignore -1)
double value = quotaCluster.getMemSizeMB() == -1 ? quotaCluster.getMemSizeMB().doubleValue()
: quotaCluster.getMemSizeMB().doubleValue() / 1024.0;
template.setMemoryLimit(value);
}
if (quotaCluster.getMemSizeMBUsage() != null) {
template.setMemoryUsage(quotaCluster.getMemSizeMBUsage() / 1024.0);
}
if (quotaCluster.getVirtualCpu() != null) {
template.setVcpuLimit(quotaCluster.getVirtualCpu());
}
if (quotaCluster.getVirtualCpuUsage() != null) {
template.setVcpuUsage(quotaCluster.getVirtualCpuUsage());
}
}
@Mapping(from = QuotaClusterLimit.class, to = org.ovirt.engine.core.common.businessentities.Quota.class)
public static org.ovirt.engine.core.common.businessentities.Quota map(QuotaClusterLimit model,
org.ovirt.engine.core.common.businessentities.Quota template) {
org.ovirt.engine.core.common.businessentities.Quota entity =
template != null ? template : new org.ovirt.engine.core.common.businessentities.Quota();
QuotaCluster quotaCluster = new QuotaCluster();
if (model.isSetVcpuLimit()) {
quotaCluster.setVirtualCpu(model.getVcpuLimit());
}
if (model.isSetMemoryLimit()) {
double limit = model.getMemoryLimit();
quotaCluster.setMemSizeMB( (limit < 0) ? -1 : (long) (limit * 1024) );
}
// specific cluster
if (model.isSetCluster() && model.getCluster().isSetId()) {
quotaCluster.setClusterId(GuidUtils.asGuid(model.getCluster().getId()));
entity.getQuotaClusters().add(quotaCluster);
} else { // global
entity.setGlobalQuotaCluster(quotaCluster);
}
return entity;
}
}
|
923f347cdc59b8e3e102d9fad510157ecde0efb4
| 223 |
java
|
Java
|
src/main/java/com/mkmonkey/sell/enums/CodeEnum.java
|
mk-monkey/ordersystem
|
bffb3c70a3f2282c6b8a859f673ca13532f8c89a
|
[
"Apache-2.0"
] | 1 |
2018-02-25T13:29:14.000Z
|
2018-02-25T13:29:14.000Z
|
src/main/java/com/mkmonkey/sell/enums/CodeEnum.java
|
mk-monkey/ordersystem
|
bffb3c70a3f2282c6b8a859f673ca13532f8c89a
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/mkmonkey/sell/enums/CodeEnum.java
|
mk-monkey/ordersystem
|
bffb3c70a3f2282c6b8a859f673ca13532f8c89a
|
[
"Apache-2.0"
] | null | null | null | 15.928571 | 32 | 0.672646 | 1,001,071 |
package com.mkmonkey.sell.enums;
import lombok.Getter;
/**
* @Class Name: CodeEnum
* @Description: TODO
* @Company bgy: MK monkey
* @create: 2018-02-24 03:08
**/
public interface CodeEnum {
Integer getCode();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.