method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
d24cfbf9-95a8-4fe2-8462-b08e59088515 | 7 | private void send_with_congestion_control(Packet[] packets) throws InterruptedException
{
boolean recebeu = false;
ArrayList<Integer> acks = new ArrayList<Integer>();
this.sliding_window = 1;
for (int curr_packet = 0; curr_packet < packets.length; curr_packet++)
{
//envia uma janela de pacotes
for (int i = 0; i < this.sliding_window; i++)
{
TCP transport = (TCP) packets[curr_packet].getTransport();
acks.add(transport.getACK_number());
send_packet(packets[curr_packet++]);
if (curr_packet == packets.length)
break;
}
curr_packet--;
//verifica se a janela enviada chegou ao destino
Iterator<Integer> ack_itr = acks.iterator();
synchronized (this)
{
wait(100); //timeout
}
recebeu = true;
while(ack_itr.hasNext())
{
int ACK = ack_itr.next();
if (!got_ACK(ACK))
{
recebeu = false;
curr_packet -= this.sliding_window;
}
}
if (curr_packet < -1)
curr_packet = -1;
//dobra o envio de pacotes em caso de sucesso
if (recebeu)
this.sliding_window *= 2;
else
this.sliding_window = 1;
acks.clear();
}
} |
8d707b5f-ea37-4d8d-b48e-bfdef5d3d0dd | 3 | public void visitMonitorStmt(final MonitorStmt stmt) {
if (CodeGenerator.DEBUG) {
System.out.println("code for " + stmt);
}
stmt.visitChildren(this);
genPostponed(stmt);
if (stmt.kind() == MonitorStmt.ENTER) {
method.addInstruction(Opcode.opcx_monitorenter);
stackHeight -= 1;
} else if (stmt.kind() == MonitorStmt.EXIT) {
method.addInstruction(Opcode.opcx_monitorexit);
stackHeight -= 1;
} else {
throw new IllegalArgumentException();
}
} |
8bc64188-8ed2-4ed9-a247-5d7124bec0b5 | 1 | public static void hypothesizeUnit(GrammarEnvironment env, Grammar g) {
UnitProductionRemover remover = new UnitProductionRemover();
if (remover.getUnitProductions(g).length > 0) {
UnitPane up = new UnitPane(env, g);
env.add(up, "Unit Removal", new CriticalTag() {
});
env.setActive(up);
return;
}
hypothesizeUseless(env, g);
} |
526eb44c-2085-4249-9ed0-50147c2f4f24 | 1 | public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
} |
e3c6af88-b2df-4c93-a3c8-784b9c82c527 | 3 | private static String getCryptFilterName(PDFObject param) throws IOException {
String cfName = PDFDecrypterFactory.CF_IDENTITY;
if (param != null) {
final PDFObject nameObj = param.getDictRef("Name");
if (nameObj != null && nameObj.getType() == PDFObject.NAME) {
cfName = nameObj.getStringValue();
}
}
return cfName;
} |
ca2e8e4a-2ca5-4f3e-94ba-0ed15b3d08ad | 0 | public void setId(String id)
{
this.id = id;
} |
24bc0d85-3630-4345-ab93-edb927801ad3 | 9 | public void remove(Integer k) {
Node<Integer, Integer> x = root, y = null;
while (x != null) {
int cmp = k.compareTo(x.key);
if (cmp == 0) {
break;
} else {
y = x;
if (cmp < 0) {
x = x.left;
} else {
x = x.right;
}
}
}
if (x == null) {
return;
}
if (x.right == null) {
if (y == null) {
root = x.left;
} else {
if (x == y.left) {
y.left = x.left;
} else {
y.right = x.left;
}
}
} else {
Node<Integer, Integer> leftMost = x.right;
y = null;
while (leftMost.left != null) {
y = leftMost;
leftMost = leftMost.left;
}
if (y != null) {
y.left = leftMost.right;
} else {
x.right = leftMost.right;
}
x.key = leftMost.key;
x.value = leftMost.value;
}
size--;
} |
0798dc0f-434c-4874-b060-d85b09c38e38 | 0 | protected StringBuffer prepareFile(JoeTree tree, DocumentInfo docInfo) {
//String lineEnding = Preferences.platformToLineEnding(docInfo.getLineEnding());
StringBuffer buf = new StringBuffer();
// write the prelude to data
// TBD
// write the data
//Node node = tree.getRootNode();
//for (int i = 0; i < node.numOfChildren(); i++) {
// buildOutlineElement(node.getChild(i), lineEnding, buf);
//}
//
// write the postlude to data
// TBD
return buf;
} // end method prepareFile |
13e24d28-53d2-4433-8a7c-38008a689d36 | 1 | public void setPrivate(final boolean flag) {
int modifiers = classInfo.modifiers();
if (flag) {
modifiers |= Modifiers.PRIVATE;
} else {
modifiers &= ~Modifiers.PRIVATE;
}
classInfo.setModifiers(modifiers);
this.setDirty(true);
} |
e5a8b705-4bdb-48be-b66a-408049fc7714 | 6 | public boolean parse(Throwable throwable) {
boolean identified = false;
if (throwable.getCause() != null) {
identified |= parse(throwable.getCause());
}
if (throwable instanceof UmbrellaException) {
if (((UmbrellaException) throwable).getCauses() != null) {
for (Throwable subthrowable : ((UmbrellaException) throwable).getCauses()) {
if (!identified) {
identified |= parse(subthrowable);
}
}
}
}
if (!identified) {
identified |= handleLoop(throwable);
}
return identified;
} |
15cdcda1-4544-4b8d-8688-8d1a9de6ca99 | 4 | private void loadEmployerDateFromFile(String employerRepository) {
InputStream is = getInputStreamForFile(employerRepository);
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
try {
XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(is);
while (xmlEventReader.hasNext()) {
XMLEvent xmlEvent = xmlEventReader.nextEvent();
if (xmlEvent.isStartElement()){
StartElement startElement = xmlEvent.asStartElement();
if(startElement.getName().getLocalPart().equals("firstname")){
xmlEvent = xmlEventReader.nextEvent();
builder.withHead(xmlEvent.asCharacters().getData());
}
}
}
} catch (XMLStreamException e) {
e.printStackTrace();
}
} |
26b3043c-25cc-4764-bb08-896c842c009e | 6 | @Override
public void render(Graphics2D g)
{
int textBaseLine = getYI() + fontMetrics.getAscent();
if (showLine)
{
g.setColor(lineColour);
g.drawLine(getXI(), textBaseLine, getXI() + getWidthI(), textBaseLine);
}
if (this.getSelectedText() != "")
{
g.setColor(selectionColour);
g.fillRect(getXI() + fontMetrics.stringWidth(getText().substring(0, getSelectionStart())), getYI(), fontMetrics.stringWidth(getSelectedText()), getHeightI());
}
g.setColor(textColour);
g.setFont(fontMetrics.getFont());
g.drawString(getText(), getXI(), textBaseLine);
if (isEditable() && active && (caretInUse || (System.nanoTime() / 100000000) % 10 < 5))
{
int caretX = fontMetrics.stringWidth(getText().substring(0, getCaretIndex()));
g.drawLine(getXI() + caretX, getYI() + 2, getXI() + caretX, getYI() + getHeightI() - 4);
}
} |
b06bc738-bb1b-4643-9260-8030bcc74866 | 3 | private void doUpdateXinWen(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String xinwenId = StringUtil.toString(request.getParameter("xinwenId"));
if(!StringUtil.isEmpty(xinwenId)) {
ObjectMapper mapper = new ObjectMapper();
Map result = new HashMap();
try {
XinWen oldXinWen = manager.findXWById(xinwenId);
XinWen newXinWen = fetchXinWenInfoFromRequest(request);
User user = (User)request.getSession().getAttribute("fgzb_user");
newXinWen.setUpdatedBy(user.getName());
int flag = manager.updateXW(newXinWen);
if(flag > 0) {
logger.info("#########更新新闻成功,新用户是:"+newXinWen+"\n"+"旧新闻是:"+oldXinWen);
result.put("success",true);
}else{
logger.info("#########更新新闻失败,新用户是:"+newXinWen+"\n"+"旧新闻是:"+oldXinWen);
result.put("success",false);
}
} catch (SQLException e) {
result.put("success",false);
logger.error("更新新闻失败", e);
}finally {
String out =mapper.writeValueAsString(result);
PrintWriter pw = response.getWriter();
pw.print(out);
}
}
} |
925872d1-119d-40ec-9489-9d56b4552a38 | 9 | @Override
public String stringify(int level) {
ArrayList<String> strArray = new ArrayList<String>();
int width = 0;
for (int i = 0; i < length; ++i) {
JSON obj = mapArray.get(i);
String strJSON;
if (obj == null)
strJSON = "null";
else
strJSON = obj.stringify(level + 1);
width += strJSON.length() + 2;
strArray.add(strJSON);
}
if (width == 0)
width = 2;
String delim = "";
String indent = LINE_SEPARATOR;
StringBuilder sb = new StringBuilder("[");
int n = strArray.size();
if (widthForIndent >= 0 && width > widthForIndent) {
for (int i = 0; i < level; ++i)
indent += indentString;
delim += indent;
for (String e : strArray) {
sb.append(delim);
sb.append(indentString);
sb.append(e);
delim = "," + indent;
}
if (n > 0)
sb.append(indent);
} else {
for (String e : strArray) {
sb.append(delim);
sb.append(e);
delim = ", ";
}
}
sb.append("]");
return sb.toString();
} |
26d7c424-cdf8-4899-83e2-2ac7da85ff38 | 2 | private String getDateValue(final Field field, final Object object) {
String resValue = null;
Object value = getRawValue(field, object);
if (value != null && value instanceof Date) {
resValue = DateUtils.format((Date) value, DATE_FORMAT);
}
return resValue;
} |
49ecf551-f774-45ce-a704-c5bec91745c8 | 5 | public void ausschreiben(){
for(int i=0; i < spieler.length; i++){
if(spieler[i].getX(i) - spieler[i].getRange(i) < pos_x && pos_x < spieler[i].getX(i) + spieler[i].getRange(i)
&& spieler[i].getY(i) - spieler[i].getRange(i) < pos_y && pos_y < spieler[i].getY(i) + spieler[i].getRange(i)){
spieler[i].supermarktAusschreibung(kaufkraft);
}
}
} |
1c348cca-4c6f-47fa-8d71-79dad1ea9394 | 8 | public String getTwitchInfo(String message)
{
URL url;
StringBuilder allWords = new StringBuilder();
String[] parts = message.split(" ");
for (String word:parts)
{
if (word.contains("twitch.tv/") && (word.contains("/c/") || word.contains("/b/")))
{
word = word.substring(word.indexOf("http"));
if (word.toLowerCase().startsWith("https"))
word = "http" + word.substring(5);
try {
url = new URL(word);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
allWords.append(str);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
}
String temp = allWords.toString().split("<title>")[1].split("</title>")[0];
String title = "\"" + temp.split(" - ")[1] + "\"";
String uploader = temp.split(" - ")[0];
return "Linked Twitch VOD - " + title + " by " + uploader;
} |
1b7a826d-d90c-4cdb-86f0-5c8d93344b4c | 5 | InventoryGUI(CardGUI c) {
cgui = c;
inv = c.currentGame.player.getItems();
inventorySize = c.currentGame.player.inventorySpace;
this.setLayout(new AbsoluteLayout());
slots = new JLabel[inventorySize];
stackCount = new JLabel[inventorySize];
highLights = new JLabel[inventorySize];
setBackground(new Color(0, 0, 0, 0));
this.setSize(c.getWidth(), c.getHeight());
try {
backGround = ImageIO.read(getClass().getResource("/com/RoguePanda/ZAG/Images/template.png"));
nullItem = ImageIO.read(getClass().getResource("/com/RoguePanda/ZAG/Images/noWeapon.png"));
highLight = ImageIO.read(getClass().getResource("/com/RoguePanda/ZAG/Images/SelectedIcon.png"));
//spriteSheet = ImageIO.read(getClass().getResource("/com/RoguePanda/ZAG/Images/itemSheet0.png"));
} catch (IOException ex) {
Logger.getLogger(InventoryGUI.class.getName()).log(Level.SEVERE, null, ex);
}
//sprite = ImageManipulator.selectFromSheet(spriteSheet, id, 64, 64);
int rowTemp = 0;
int colTemp = 0;
for (int i = 0; i < inventorySize; i++) {
Item item;
Image img = nullItem;
int itemID;
int stackSize = 0;
try {
item = inv.get(i).item;
itemID = item.getID();
img = inv.get(i).sprite;
ItemStack stack = inv.get(i);
stackSize = stack.amount;
} catch (Exception ex) {
itemID = -1;
}
System.out.println(stackSize);
if (itemID == -1) {
slots[i] = new JLabel(new ImageIcon(nullItem));
} else {
slots[i] = new JLabel(new ImageIcon(img));
stackCount[i] = new JLabel();
stackCount[i].setText("<html><p><font color=#FF0000" + "size=\"7\" face=\"Verdana\">" + stackSize + "</font></p></html>");
//highLights[i] = new JLabel(new ImageIcon(highLight));
slots[i].setSize(new Dimension(64, 64));
stackCount[i].setSize(new Dimension(16, 16));
//highLights[i].setSize(new Dimension(64, 64));
addMouseListeners(slots[i], i, 0);
//addMouseListeners(highLights[i], i, 1);
this.add(stackCount[i], new AbsoluteConstraints(56 + 72 * rowTemp, 56 + 72 * colTemp));
this.add(slots[i], new AbsoluteConstraints(8 + 72 * rowTemp, 8 + 72 * colTemp, 64, 64));
//this.add(highLights[i], new AbsoluteConstraints(8 + 72 * rowTemp, 8 + 72 * colTemp, 64, 64));
}
rowTemp++;
if (rowTemp == 8) {
rowTemp = 0;
colTemp++;
}
}
JLabel back = new JLabel(new ImageIcon(backGround));
this.add(back, new AbsoluteConstraints(0, 0, c.getWidth(), c.getHeight()));
} |
95ff16d0-5aba-4903-b508-f1530dfb644a | 2 | private boolean win(){
for(ERow row : ERow.values()){
if(getRow(row) == -2){
//we may win
System.out.println("we may win!");
return getFreeCell(row);
}
}
return false;
} |
fa3b11d0-3ca4-47bf-b7ea-1750efaa4148 | 2 | public void resetPlotOption(int opt){
if(opt<0 || opt>4)throw new IllegalArgumentException("The plot option, " + opt + ", must be greater than or equal to 0 and less than 5");
this.plotOptions = opt;
} |
40672ddf-7c82-4bc4-8108-131345a323c2 | 2 | private void loadConfig(){
if(xmlConfig == null){
xmlConfig = new XMLConfiguration();
try {
xmlConfig.load(PublishConstants.SYSTEM_CONFIG_DIR + PublishConstants.PUBLISH_CONFIG_FILE_NAME);
} catch (ConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
5579fb68-7c0d-4387-abeb-a484a0fcc046 | 3 | private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExcluirActionPerformed
if (cmbProjeto.getSelectedItem().equals("Selecione")) {
JOptionPane.showMessageDialog(null, "Erro selecione o Projeto",
"Gestão de Atividade", JOptionPane.ERROR_MESSAGE);
} else {
if (cmbEncarregado.getSelectedItem().equals("Selecione")) {
JOptionPane.showMessageDialog(null, "Erro selecione o Encarregado",
"Gestão de Atividade", JOptionPane.ERROR_MESSAGE);
} else {
AtividadeBO atividadeBO = new AtividadeBO();
int IDatividade = Integer.parseInt(txtIDatividade.getText());
try {
atividadeBO.deleteAtividade(IDatividade);
JOptionPane.showMessageDialog(null, "Atividade Deletada com Sucesso !!!",
"Gestao de Atividade", JOptionPane.INFORMATION_MESSAGE);
logSegurancaDados log = null;
log = new logSegurancaDados("INFO",
"Exclusão de Atividade realizada com sucesso pelo "
+ UserLogado.getTipo() + " : " + UserLogado.getNome());
this.listarAtividadesGETSAO();
this.btnSalvarAlteracoes.setEnabled(false);
this.btnExcluir.setEnabled(false);
this.limpar();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro ao deletar atividade !!!",
"Gestao de Atividade", JOptionPane.INFORMATION_MESSAGE);
}
}
}
}//GEN-LAST:event_btnExcluirActionPerformed |
c62a3f63-2753-4192-b49d-09b5dada1903 | 3 | public void addBit(int theBit) {
if (!(theBit == 0 || theBit == 1)) {
throw new IllegalArgumentException("argument must be 0 or 1");
}
if (length == 32) {
throw new IllegalStateException("cannot fit additional bits");
}
// Add the new bit to the right of the existing bits, shifting
// the existing bits one place to the left.
bits = (bits << 1) | theBit;
length++;
} |
1bc6f576-cd24-43b0-86ec-4680cd0cebd6 | 3 | public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
JpcapCaptor captor=JpcapCaptor.openFile("test");
while(true) {
Packet readPacket = captor.getPacket();
if(readPacket==null || readPacket==Packet.EOF) break;
System.out.println(readPacket);
captor.close();
}
} |
27dd6a9d-b571-493a-96dc-85f94b4e11a0 | 9 | public boolean isUgly(int num) {
if(num <=0){
return false;
}
if(num ==1){
return true;
}
long tnum = num;
// if (num<0){
// tnum = -tnum;
// }
System.out.println(tnum);
boolean res = true;
int i=0;
List<Integer> l = new LinkedList<>();
int[] arr = {2,3,5};
while(i<arr.length ){
int tmp = arr[i];
if(log)
System.out.println(tmp);
int div = num%tmp;
if(div==0){
while(tnum%tmp==0){
tnum /=tmp;
}
}
if(log)
System.out.println("after "+tmp+" div "+tnum);
if(tnum == 1){
break;
}
i++;
}
if(tnum>1){
res = false;
}
return res;
} |
cd99a887-9ced-4fd4-8362-9a78a5062308 | 9 | public JanelaPrincipal() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 701, 399);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmOpen = new JMenuItem("Carrega Imagem...");
mntmOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
clickLoad();
} catch (Exception ex) {
}
}
});
mnFile.add(mntmOpen);
JMenuItem mntmSave = new JMenuItem("Salva Imagem...");
mntmSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
clickSave();
} catch (Exception ex) {
}
}
});
mnFile.add(mntmSave);
JMenuItem mntmCarregaPastaCom = new JMenuItem(
"Carrega Pasta com Imagens...");
mntmCarregaPastaCom.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
clickCarregaArquivos();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
mnFile.add(mntmCarregaPastaCom);
JMenu mnImagens = new JMenu("Imagens");
menuBar.add(mnImagens);
JMenuItem mntmCarregaProcessa = new JMenuItem(
"Carrega / Processa e Salva em Lote...");
mntmCarregaProcessa.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
clickFazTudo();
} catch (Exception ex) {
// TODO:
}
}
});
mnImagens.add(mntmCarregaProcessa);
JMenu mnProcessamento = new JMenu("Processamento");
menuBar.add(mnProcessamento);
JMenuItem mntmYcbcr = new JMenuItem("YCbCr");
mntmYcbcr.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
clickAlgoritmo( Algoritmos.YCBCR );
} catch( Exception ex ) {
// TODO:
}
//clickYCbCr();
}
});
mnProcessamento.add(mntmYcbcr);
JMenuItem mntmYiqq = new JMenuItem("YIQ-Q");
mntmYiqq.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
clickAlgoritmo( Algoritmos.YIQ );
} catch( Exception ex ) {
// TODO;
}
//clickYIQ();
}
});
mnProcessamento.add(mntmYiqq);
JMenuItem mntmPseudoHue = new JMenuItem("Pseudo Hue");
mntmPseudoHue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
clickAlgoritmo( Algoritmos.PSEUDOHUE );
} catch( Exception ex ) {
// TODO:
}
//clickPseudoHue();
}
});
mnProcessamento.add(mntmPseudoHue);
JMenuItem mntmI = new JMenuItem("I3");
mntmI.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try{
clickAlgoritmo( Algoritmos.I3 );
} catch( Exception ex ) {
// TODO:
}
}
});
mnProcessamento.add(mntmI);
JMenuItem mntmOtsu = new JMenuItem("Otsu");
mntmOtsu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
clickAlgoritmo( Algoritmos.TESTE_OTSU );
} catch( Exception ex ) {
}
}
});
mnProcessamento.add(mntmOtsu);
contentPane = new JDesktopPane();
contentPane.setDragMode(JDesktopPane.LIVE_DRAG_MODE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
} |
9df9d451-15fe-478f-b61d-81d928316bb9 | 8 | @Override
public void update() {
if (!init)
init();
level.update();
mouseOverOptionIndex = -1;
double mouseX = GameInput.mouseX;
double mouseY = GameInput.mouseY;
for (int i = 0; i < menuOptions.length; i++) {
float x = xyWidthHeight[i][X];
float y = xyWidthHeight[i][Y];
float width = xyWidthHeight[i][WIDTH];
float height = xyWidthHeight[i][HEIGHT];
if (mouseX >= x && mouseX < x + width && mouseY >= y && mouseY < y + height) {
mouseOverOptionIndex = i;
break;
}
}
if (GameInput.mouseDeltaUpLeft) {
if (mouseOverOptionIndex != -1) {
int state = menuOptionStates[mouseOverOptionIndex];
StateManager.setState(state);
}
}
} |
8cfbe629-f7ae-4eda-9f3c-5b7dda4e0525 | 2 | @Override
protected DPLotSizingDecision getDecision(
DPBackwardRecursionPeriod[] periods, int setupPeriod,
int nextSetupPeriod, double alpha)
throws ConvolutionNotDefinedException {
//Get the vector of open and realized demand
RealDistribution[] openOrders = new RealDistribution[nextSetupPeriod-setupPeriod];
RealDistribution[] realisedOrders = new RealDistribution[nextSetupPeriod-setupPeriod];
for (int i = 0; i < openOrders.length; i++){
openOrders[i] = periods[setupPeriod+i].period.openDemand(setupPeriod+i, setupPeriod);
realisedOrders[i] = periods[setupPeriod+i].period.realisedDemand(setupPeriod+i, setupPeriod);
}
//Get the open order up to level
RealDistribution openCycleDemand = Convoluter.convolute(openOrders);
double openOrderUpToLevelForOpenDemand = openCycleDemand.inverseCumulativeProbability(alpha);
//Start with the setup cost
double decisionCost = periods[setupPeriod].period.getSetupCost();
//Calculate and add the inventory cost
for (int tau = 0; tau < openOrders.length; tau++){
RealDistribution openDemandDistribution = Convoluter.convolute(openOrders, tau+1);
NegatableDistribution realizedDemandDistribution = (NegatableDistribution) Convoluter.convolute(realisedOrders, tau+1, realisedOrders.length);
RealDistribution effectiveDemandDistribution = Convoluter.convolute(openDemandDistribution, realizedDemandDistribution.negate());
StockFunction stockFunction = new StockFunction(effectiveDemandDistribution);
decisionCost += periods[tau].period.getInventoryHoldingCost()*stockFunction.value(openOrderUpToLevelForOpenDemand);
}
//return
return new DPLotSizingDecision(periods[nextSetupPeriod], decisionCost, openOrderUpToLevelForOpenDemand);
} |
010ed69f-ca9a-462f-a0fa-ae3460922460 | 0 | public ProductionChecker() {
} |
bb07b526-3ee5-4c38-b2d8-943e1f29faec | 0 | public PosControlTransacciones getPosControlTransaccionesFromItemDeMovimiento(PhpposSalesItemsEntity itemMovPos,
long fesCedula,
PhpposSalesEntity movimientoPos,
PosSolicitud solicitud){
PosControlTransacciones transaccion = new PosControlTransacciones();
transaccion.setCtrCantidad(itemMovPos.getQuantityPurchased());
transaccion.setCtrCcResponsable(fesCedula);
transaccion.setCtrEstado(movimientoPos.getEstadoMovimiento());
transaccion.setCtrFecha(Integer.parseInt(f.format(movimientoPos.getSaleTime())));
transaccion.setCtrFormaPago(getTipoPago(movimientoPos.getPaymentType()));
transaccion.setCtrIdElemento(itemMovPos.getItemId());
transaccion.setCtrIdFuncionario(movimientoPos.getCustomerId());
transaccion.setCtrMoaConsec(movimientoPos.getSaleId()); // ID DEL MOVIMIENTO
transaccion.setCtrMoaTipo(getTipoMovimientoPos(movimientoPos.getTipoMovimiento()));
transaccion.setCtrPosId(getIdPos());
transaccion.setCtrValorTotal(
(int)(itemMovPos.getQuantityPurchased() * itemMovPos.getItemUnitPrice())
);
transaccion.setIdSolicitud(solicitud.getIdSolicitud());
return transaccion;
} |
5c58e2e8-0cc4-4a5f-a886-efa650ab5c5f | 7 | private static String locate(CSVParser csv, String name, String... type) throws IOException {
if (name == null) {
// match anything
name = ".+";
}
Pattern p = Pattern.compile(name);
String[] line = null;
while ((line = csv.getLine()) != null) {
if (line[0].startsWith(COMMENT) || !line[0].startsWith(P)) {
// if (line.length != 2 || line[0].startsWith(COMMENT) || !line[0].startsWith(P)) {
continue;
}
for (String s : type) {
if (line[0].equalsIgnoreCase(s) && p.matcher(line[1].trim()).matches()) {
return line[1];
}
}
}
throw new IllegalArgumentException("Not found : " + type + ", " + name);
} |
7691329b-2584-4d57-88ad-2f5ff45094ec | 1 | public static AbilityType getAbility(ActiveWeaponEnchant type) {
switch (type) {
case FIREBALL:
return AbilityType.abil_aim_fire;
}
return null;
} |
27f3c41f-4cf5-4c87-940a-2897d707daed | 3 | protected void takeTier(){
//check how many tiers is taken and take another tier if possible
if(this.tiersTaken < this.enhancementMaxRank && requirementsMetSpend()){
if(DDOCharacter.pointAvailible()){
DDOCharacter.pointsSpent(prestige, apPerTier.get(tiersTaken));
++this.tiersTaken;
this.setImage(tiersTaken);
DDOCharacter.getTree(prestige).setEnhancement(id, this); //force an update
}
}
} |
a1babbf6-7ef4-4926-888b-9b4e277b5c96 | 6 | 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(FrmAreaCircunferencia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FrmAreaCircunferencia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FrmAreaCircunferencia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FrmAreaCircunferencia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FrmAreaCircunferencia().setVisible(true);
}
});
} |
089b5132-6ca6-432f-a304-0039ed087e47 | 7 | @Test
public void test()
{
clock = new Clock();
TimeControl tc = new Quota(30, 1800, 5, IncrementTypes.FISCHER);
clock.setTimeControl(tc);
clock.init();
Thread t = new Thread(new Runnable(){
public void run()
{
while(true)
{
System.out.println("Blancas: " + formatTime(clock.getWhiteTime()) + ", Negras: " + formatTime(clock.getBlackTime()));
try{
Thread.sleep(700);
}catch(Exception ex){
}
}
}
});
t.start();
System.out.println("Se inicia el reloj");
clock.start();
try{
Thread.sleep(3000);
}catch(Exception ex){
}
System.out.println("Se hace switch del reloj");
clock.switchClocks();
try{
Thread.sleep(3000);
}catch(Exception ex){
}
System.out.println("Se hace otra vez switch del reloj");
clock.switchClocks();
try{
Thread.sleep(3000);
}catch(Exception ex){
}
System.out.println("Se pausa el reloj");
clock.pause();
try{
Thread.sleep(10000);
}catch(Exception ex){
}
System.out.println("Se reanuda el reloj");
clock.resume();
try{
Thread.sleep(10000);
}catch(Exception ex){
}
System.out.println("Se pause el reloj");
clock.pause();
t.stop();
} |
c7711356-194e-4b9a-b68c-f110173353be | 3 | public static void close() { //Закрытие окна
if(Core.getIntance().getCurrentController().equals(EForm.MainForm.getController()))
Model.getIntance().empty(); //Если закрывается окно с игрой, то удаляем игру (иначе таймеры продолжат работать)
stage.close();
if(!stages.isEmpty()) { //Если в стеке окон есть ещё окна, то извлекаем их из стека и делаем enable
stage = stages.pop();
if(!controllers.isEmpty())
Core.getIntance().setCurrentController(controllers.pop());
else
ExceptionLog.println("Ошибка: Стэк controllers, работающий синхронно со стэком stages оказаля пустым, в то время, как stages - нет.");
Core.getIntance().getCurrentController().setDisable(false);
Core.getIntance().getCurrentController().update();
}
} |
ca1eb4d3-ca90-401c-b15d-668f4647b3e8 | 2 | @EventHandler
public void onFrameBrake(HangingBreakEvent e) {
if(e.getCause() == RemoveCause.ENTITY){
if(e.getEntity() instanceof ItemFrame){
e.setCancelled(true);
}
}
} |
86f95d28-1220-4bf2-bf8b-f3ab4627a013 | 9 | @Override
public void keyPressed(KeyEvent e) {
System.out.println(e.getKeyCode());
switch(e.getKeyCode()) {
case KeyEvent.VK_UP:
if(Snake.direction != Util.SOUTH)
Snake.direction = 0;
break;
case KeyEvent.VK_LEFT:
if(Snake.direction != Util.EAST)
Snake.direction = 1;
break;
case KeyEvent.VK_DOWN:
if(Snake.direction != Util.NORTH)
Snake.direction = 2;
break;
case KeyEvent.VK_RIGHT:
if(Snake.direction != Util.WEST)
Snake.direction = 3;
break;
case KeyEvent.VK_P:
Util.paused = !Util.paused;
break;
}
} |
ec2c510a-1f8c-4962-9092-be534279e95d | 1 | public boolean editShipWorks(Ship ship)
{
if(myTurnEditing)
return mySea.shipWorks(ship);
else
return theirSea.shipWorks(ship);
} |
28168d9f-1ca9-4f9f-929a-aa44b9f85f26 | 7 | void hideAndShowToolbars(boolean leftOnly) {
boolean hide = bottomPanelVisible || leftPanelVisible;
MouseEvent me;
if (leftOnly || hide == leftPanelVisible) {
me = new MouseEvent(hideLeftPanel, 0, 0, 0, 1, 1, 1, false);
for (MouseListener ml : hideLeftPanel.getMouseListeners()) {
ml.mouseReleased(me);
}
}
if (!leftOnly && hide == bottomPanelVisible) {
me = new MouseEvent(hideBottomLabel, 0, 0, 0, 1, 1, 1, false);
for (MouseListener ml : hideBottomLabel.getMouseListeners()) {
ml.mouseReleased(me);
}
}
} |
2c6ef8e4-5070-4009-870f-5cba32dd8643 | 6 | @Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Tree other = (Tree) obj;
if (root == null) {
if (other.root != null) {
return false;
}
} else if (!root.equals(other.root)) {
return false;
}
return true;
} |
3ed87fbd-267f-423b-b091-3572147fe95e | 6 | public boolean isConnectedOK() {
boolean ok = false;
Connection conn = null;
SQLException ex = null;
try {
conn = DriverManager.getConnection(jdbcUrl,user,password);
if (!conn.isClosed()) {
ok = true;
}
} catch (SQLException e) {
ex = e;
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
if(ex == null) {
ex = e;
}
}
}
if(ex != null) {
throw new RuntimeException(ex);
}
}
return ok;
} |
8a2b3f47-15e5-4616-ab27-714586774f26 | 6 | public static void solve(String[] args) throws IOException{
String fileName = null;
// get the temp file name
for(String arg : args){
if(arg.startsWith("-file=")){
fileName = arg.substring(6);
}
if(arg.startsWith("-type=")){
type = arg.substring(6);
}
}
if(fileName == null)
return;
// read the lines out of the file
int count = 10000;
lines = new Long[count];
BufferedReader input = new BufferedReader(new FileReader(fileName));
int i=0;
try {
String line = null;
while (( line = input.readLine()) != null && i<count){
lines[i++] = Long.parseLong(line);
}
}
finally {
input.close();
}
sort(0,count-1);
/*for(int k=0;k<10000;k++){
System.out.println(lines[k]);
}*/
System.out.println(comparisons);
} |
49622e91-173f-4dc3-b9db-161caf3b2618 | 7 | public boolean calculateEnergyConsumptionGeneration() {
int i = 1;
boolean feasible = false;
System.out.println("EVALUATING SYSTEMS\n");
for (SoftwareSystem system : systems) {
System.out.println("\tSystem " + (i++) + "\n\t\t" + system);
int j = 0;
double totalTime = 0;
Calculator calculator = new Calculator(this);
for (FunctionalRequirement functionalRequirement : functionalRequirements) {
double functionalRequirementTime = 0;
for (SequenceAlternative sequenceAlternative : functionalRequirement.getSequenceAlternatives()) {
double[] consumption = calculator.calculateEnergyConsumptionW(system, functionalRequirement, sequenceAlternative);
if (system.getConsumptionWatt()[j] == -1 || consumption[1] > 0 && consumption[1] < system.getConsumptionWatt()[j]) {
functionalRequirementTime = consumption[0];
system.getConsumptionWatt()[j] = Math.round(consumption[1] * 100) / 100.0;
system.getBestSequenceAlternativesWatt().add(sequenceAlternative);
}
}
totalTime += functionalRequirementTime;
j++;
}
if (totalTime <= 3600) {
feasible = true;
system.setValid(true);
system.calculateTotalsW();
system.printAnalysisResultsSummaryW();
}
System.out.println("\n\n");
}
return feasible;
} |
3542be43-178a-4089-998d-8a6f1f47026a | 1 | @Test
public void tasoAsetaPelaajanAlkusijaintiToimii() {
Piste r = new Piste(20, 20);
t.asetaPelaajanAlkusijainti(r);
Pelaaja pe = new Pelaaja();
pe.setTaso(t);
assertTrue("Pelaajan alkusijainti oli väärä", pe.getX() == 20 && pe.getY() == 20);
assertTrue("GetPelaajanAlkusijainti palautti väärin",
t.getPelaajanAlkusijainti() == r);
} |
d554721b-8783-4982-8270-71c8dc77b335 | 2 | private void send(String pro,String sxo){
/*
* apothikeuei sthn vash thn anafora
*/
String query="insert into anafores(provlima,sxolia,odigos_id) values(?,?,?)";
try {
con.pS=con.conn.prepareStatement(query);
con.pS.setString(1, pro);
con.pS.setString(2, sxo);
con.pS.setInt(3, odigosId);
} catch (SQLException e) {
e.printStackTrace();
}
if(con.makeQuery(query)){
JOptionPane.showMessageDialog(null, "Stalthike!");
sxolia.setText("");
}else{
JOptionPane.showMessageDialog(null, "Something went wrong please try later!");
}
} |
9f14f2e1-bf6c-4a91-8a0a-c8ac607e5683 | 0 | @Override
public void disconnected(DisconnectedEvent e) {
} |
fa587161-c810-4390-afc9-6177e233544a | 5 | private Cell[] getWillFlip(int x, int y){
List<Cell> willFlip = new ArrayList<>();
try {
willFlip.add(puzzlePanels[y][x]);
} catch (ArrayIndexOutOfBoundsException ex) {
throw new RectangularPuzzleIndexOutOfBoundsException();
}
try {
willFlip.add(puzzlePanels[y][x + 1]);
} catch (ArrayIndexOutOfBoundsException ex) {
}
try {
willFlip.add(puzzlePanels[y][x - 1]);
} catch (ArrayIndexOutOfBoundsException ex) {
}
try {
willFlip.add(puzzlePanels[y + 1][x]);
} catch (ArrayIndexOutOfBoundsException ex) {
}
try {
willFlip.add(puzzlePanels[y - 1][x]);
} catch (ArrayIndexOutOfBoundsException ex) {
}
return willFlip.toArray(new Cell[0]);
} |
3b37cf9d-df82-48db-b2ef-7d0236f3b4e2 | 9 | public String addBinary(String a, String b) {
if (a == null && b == null)
return null;
if (a == null)
return b;
if (b== null)
return a;
int lengthA = a.length();
int lengthB = b.length();
int length = Math.max(lengthA, lengthB);
String result = "";
int addition = 0;
for (int i = 0; i < length; i ++) {
int first = lengthA > i ? Character.getNumericValue(a.charAt(lengthA - i - 1)) : 0;
int second = lengthB > i ? Character.getNumericValue(b.charAt(lengthB - i - 1)) : 0;
int tmp = first + second + addition;
if (tmp > 1) {
result = tmp % 2 + result;
addition = 1;
} else {
result = tmp + result;
addition = 0;
}
}
if (addition == 1)
result = addition + result;
return result;
} |
b2ccbdd1-060e-4ec9-b845-783649a5f043 | 3 | public boolean testEgalite() {
for (Case c : this._j2.getCases()) {
if (c.isAPortee() && !c.isEtat()) {
return false;
}
}
return true;
} // testEgalite() |
e42996bd-6121-4aa1-a139-3ec7a3e3071b | 8 | @Override
public void execute(CommandSender sender, String[] args) {
if (!CommandUtil.hasPermission(sender, PERMISSION_NODES)) {
sender.sendMessage(plugin.NO_PERMISSION);
return;
}
if (args.length < 1) {
sender.sendMessage(ChatColor.RED + "/" + plugin.tp + " (playername)");
return;
}
if (args.length == 1) {
ProxiedPlayer playerTo = plugin.getUtilities().getClosestPlayer(args[0]);
if (playerTo == null) {
sender.sendMessage(plugin.PLAYER_NOT_ONLINE);
return;
}
plugin.getUtilities().teleportToPlayer((ProxiedPlayer) sender, playerTo);
return;
}
if (args.length > 1 && CommandUtil.hasPermission(sender, PERMISSION_NODES_P2P)) {
ProxiedPlayer player = plugin.getUtilities().getClosestPlayer(args[0]);
ProxiedPlayer playerTo = plugin.getUtilities().getClosestPlayer(args[1]);
if (player == null || playerTo == null) {
sender.sendMessage(plugin.PLAYER_NOT_ONLINE);
return;
}
plugin.getUtilities().teleportToPlayer(player, playerTo);
return;
} else {
sender.sendMessage(plugin.NO_PERMISSION);
}
} |
976be055-7c7a-4239-adb2-094b788ecde0 | 9 | private State_Abstract createState(String[] tokens) {
// tokens[0] is the instruction for this state
if (!E_Instruction.valid().contains(E_Instruction.valueOf(tokens[0]))) {
Main.error("Error : unknown instruction: " + tokens[0]);
}
// Based on this we create the correct state
switch (E_Instruction.valueOf(tokens[0])) {
case SENSE:
return new State_Sense(tokens);
case MARK:
return new State_Mark(tokens);
case UNMARK:
return new State_Unmark(tokens);
case PICKUP:
return new State_Pickup(tokens);
case DROP:
return new State_Drop(tokens);
case TURN:
return new State_Turn(tokens);
case MOVE:
return new State_Move(tokens);
case FLIP:
return new State_Flip(tokens);
}
return null;
} |
3b16e7e7-3534-4caa-9829-a69c53929294 | 1 | public int getPriority() {
return postfix ? 800 : 700;
} |
2edfcafe-f6aa-43d9-ab08-7c571a8eae85 | 3 | public boolean areAllClientsReady() {
if (clients.size() == 1) return true;
for (Player p : clients) {
if (!p.isReady()) return false;
}
return true;
} |
1a8c59e9-b041-46e3-b544-ba672b4ac394 | 4 | public static java.awt.Color getColorForPlayer(Player p) {
switch (p) {
case RED:
return java.awt.Color.RED;
case BLUE:
return java.awt.Color.CYAN;
case YELLOW:
return java.awt.Color.YELLOW;
case GREEN:
return java.awt.Color.GREEN;
}
return java.awt.Color.WHITE;
} |
70e05836-3f27-4c97-9f1e-cd8c6c29a57d | 5 | public int getIsoinLapsi(int indeksi) {
int isoin = -1;
if (keko.size() == 0) {
return isoin;
}
int ekanLapsenIndeksi = indeksi * this.d + 1;
isoin = ekanLapsenIndeksi;
if (ekanLapsenIndeksi >= keko.size()) {
return -1;
}
for (int i = 1; i < d && ekanLapsenIndeksi + i < keko.size(); i++) {
if (keko.get(ekanLapsenIndeksi + i) > keko.get(isoin)) {
isoin = ekanLapsenIndeksi + i;
}
}
return isoin;
} |
06d2e34b-123f-406b-a384-0ed1962dd89b | 4 | public static int personneX(int travee,int orientation){
int centreX = centrePositionX(travee) ;
switch(orientation){
case Orientation.NORD :
centreX -= 10 ;
break ;
case Orientation.EST :
centreX -= 25 ;
break ;
case Orientation.SUD :
centreX -= 10 ;
break ;
case Orientation.OUEST :
centreX += 5 ;
break ;
}
return centreX ;
} |
34277c55-11c0-4973-8e11-607418015db3 | 2 | private void initializeLogger() {
this.log = Logger.getLogger(this.getClass().getName());
try {
FileHandler fh = new FileHandler(this.getClass().getName()
.replace("class ", "")
+ this.id + ".log");
fh.setFormatter(new SimpleFormatter());
this.log.addHandler(fh);
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this.log.setUseParentHandlers(this.verbose != 0);
this.log.setLevel(Level.ALL);
} |
953010f8-3984-4408-a6fb-3139ec804aa1 | 2 | public void buttonP()
{
if(bMSounds.contains(Main.mse))
{
mSounds = !mSounds;
if(mSounds)
{
sS = "On";
}
else
{
sS = "Off";
}
}
} |
0b79e5cb-68c1-4d47-9244-bca993427ad8 | 8 | public static int findPalindromeMinCut(String input) {
int[][]cost = new int[input.length()][input.length()];
boolean [][] isPalindrome = new boolean[input.length()][input.length()];
//base case all single length elements are palindromes
for( int i=0; i< input.length(); i++) {
isPalindrome[i][i] = true;
cost[i][i] =0;
}
//all double and more length palindromes
for( int l=2; l<=input.length(); l++) {
for( int i=0; i< input.length()-l+1; i++) {
int j= i+l-1;
//for double lengthed strings
if(l==2) {
//just check the two characters for equality
isPalindrome[i][j] = input.charAt(i)==input.charAt(j);
} else {
//for more than 2 chars ..both the ends should be equal and i+1 and j-1 should also be a palindrome
isPalindrome[i][j] = (input.charAt(i)==input.charAt(j)) && isPalindrome[i+1][j-1];
}
if(isPalindrome[i][j]){
cost[i][j] = 0;
} else {
//find all the possible partition and their associated costs
cost[i][j] = Integer.MAX_VALUE;
//iterate for all the k's and find minimum cost
for(int k=i; k<j ; k++) {
if( cost[i][j] > cost[i][k]+ cost[k+1][j] + 1){
cost[i][j] = cost[i][k]+ cost[k+1][j] + 1;
}
}
}
}
}
return cost[0][input.length()-1];
} |
94949397-b4c3-4dab-a1ad-984e94672328 | 9 | public ACodeInterface(String file, JavaScriptObject callbacks) {
this.file = file;
init0(callbacks);
stateChange0("LOADING");
timer = new Timer() {
@Override
public void run() {
if (!paused) {
try {
trace0("Running code...");
// Run only if the interpreter is running
for (int i = 0; i < 100; i++) {
InterpreterState state = interpreter.step();
if (state == InterpreterState.COMPLETED) {
timer.cancel();
trace0("Done.");
refreshScore();
stateChange0("COMPLETED");
} else if (state == InterpreterState.WAITING_FOR_INPUT || state == InterpreterState.WAITING_FOR_QUERY) {
paused = true;
trace0("Need input: " + state);
refreshScore();
stateChange0("INPUT");
}
if (state != InterpreterState.RUNNING) {
trace0("Exiting loop: " + state);
return;
}
}
} catch (Throwable t) {
trace0("Uh-oh, internal error: " + t.getClass() + " " + t.getMessage());
}
}
}
};
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "ADVENTURE.ACODE");
builder.setCallback(new RequestCallback() {
public void onError(Request request, Throwable exception) {
stateChange0("ERROR");
logError("Unable to fetch source: " + exception.getMessage());
}
public void onResponseReceived(Request request, Response response) {
try {
program = ACodeParser.parseProgram(response.getText());
environment = new WebEnvironment();
WorldBuilder kernelStateBuilder = new WorldBuilder(program);
world = kernelStateBuilder.getState();
interpreter = new Interpreter(environment, world, new VirtualMachine());
timer.scheduleRepeating(1);
stateChange0("RUNNING");
} catch (ParseException e) {
stateChange0("ERROR");
logError("Parse exception: " + e.getMessage());
}
}
});
try {
builder.send();
} catch (RequestException e) {
stateChange0("ERROR");
logError("Unable to send request to fetch source: " + e.getMessage());
}
} |
18be4300-a782-43d7-ac19-3068e88445a5 | 9 | @Override
public void removerUsuario(){
if ( this.num_usuarios == 0 ) System.out.println("\nNão existem "
+ "usuários.");
else{
System.out.println("\nQual dos usuários você gostaria de remover? "
+ "[ 1 - " + this.num_usuarios + " ]" );
int i = 1;
for ( Usuario x : this.usuarios ){
System.out.println( i + ")" + x);
i++;
}
System.out.print("\n > ");
Scanner scan = new Scanner(System.in);
int op;
while(true){
if (scan.hasNextInt())
op = scan.nextInt();
else{
System.out.print("Erro. Insira um número.\n\n > ");
scan.next();
continue;
}
break;
}
op -= 1;
if( op < 0 || op > this.num_usuarios - 1 ){
System.out.println("Número inválido.");
}
else{
System.out.print("\nRemover o usuário "
+ usuarios.get(op).getUsername() + "? [ s / n ]"
+ "\n\n > " );
Scanner scan2 = new Scanner(System.in);
String resposta = scan2.nextLine();
if ( !"s".equals(resposta) && !"n".equals(resposta) ){
System.out.println("Resposta inválida.");
}
else{
if ( "s".equals(resposta) ){
this.usuarios.remove(op);
this.num_usuarios--;
System.out.println("\nUsuário removido com sucesso.");
}
else{
System.out.println("\nOk. Saindo...");
}
}
}
}
} |
1f92b37a-259f-4953-9e1c-74e7801f8fd9 | 9 | @Test
public void test_1_Constructor() {
// Initialisation
int size = 10;
Grid g = new Grid(size);
// TEST FOR SIZE (SQUARE)
boolean ok = true;
if(g.getBoard().length != size) {
ok = false;
}
int badSize =size;
int i = 0;
while(ok && (i<g.getBoard().length)) {
if(g.getBoard()[i].length != size) {
badSize = g.getBoard()[i].length;
ok = false;
}
i++;
}
// TEST FOR CONTENT OF GRID
i = 0;
boolean charac = true;
char badChar = '-';
int j = 0;
while(charac && (i<g.getBoard().length)) {
while(charac && (j<g.getBoard()[i].length)) {
if(g.getBoard()[i][j] != Grid.DEFAULT_CHAR) {
badChar = g.getBoard()[i][j];
charac = false;
}
j++;
}
i++;
}
assertEquals("the Grid should be a square",size,badSize);
assertEquals("the Grid should contain - in each case of the Grid ",'-',badChar);
} |
bd864673-c5de-463e-aa82-6e904e57bed3 | 1 | public void update() {
if (active) {
x += vx / Level.speed();
y += vy / Level.speed();
}
} |
6dde4734-daa6-443a-98e1-f203418c3e14 | 5 | private double readFloatBody(final boolean shouldBeNegative)
throws IOException {
long signif;
long exp;
if (trace == API_TRACE_DETAILED) {
debugNote("readFloatBody shouldBeNegative=" + shouldBeNegative);
}
Object obj = readObject();
if (obj instanceof BigInteger) {
BigInteger bi = (BigInteger) obj;
if (bi.bitCount() < 64) {
signif = bi.longValue();
} else {
throw new ArithmeticException("Overflow reading significand of float");
}
} else {
signif = ((Number) obj).longValue();
}
exp = readInt();
if (trace == API_TRACE_DETAILED) {
debugNote("readFloatBody shouldBeNegative=" + shouldBeNegative
+ " signif=" + signif + " exp= " + exp);
}
final Double absoluteValue = (double) signif * Math.pow(2.0, exp);
return (shouldBeNegative) ? (-absoluteValue) : absoluteValue;
} |
24336ea8-e930-4af1-bbbd-2d057eac475b | 2 | public void save(DataOutputStream out) {
try {
for (Blocks b : blocks) {
b.save(out);
}
} catch (IOException e) {
e.printStackTrace();
}
} |
97d53e94-1183-4e31-b700-c0d67e478d5c | 6 | public void buildSituations() {
System.out.println("Building graph database...");
serverSituationHistory = new HashMap<>();
applicationSituationHistory = new HashMap<>();
FakeServer livingServer;
FakeApplication livingApplication;
int stepStartResearch;
int state = ActorComponent.ALIVE;
int counter;
List<ActorComponent> serverSituationStep;
List<ActorComponent> applicationSituationStep;
for (int step = 0; step < bpgHistory.getStepNumber(); step++) {
//serverSituationHistory.put(step, new ArrayList<>());
serverSituationStep = new ArrayList<>();
stepStartResearch = 0;
for (String serverName : bpgHistory.getServerNames()) {
if ((livingServer = (FakeServer) findInStep(serverName, bpgHistory.getServerHistory(), step)) != null) {
state = ActorComponent.ALIVE;
serverSituationStep.add(new ActorComponent(livingServer, state, ActorComponent.CIRCLE, bpgHistory));
} /*else {
counter = stepStartResearch;
while (livingServer == null && counter < stepNumber) {
livingServer = (FakeServer) findInStep(serverName, serverHistory, counter);
counter++;
}
stepStartResearch = counter - 1;
if (counter > step) {
state = ActorComponent.LIMBO;
} else {
state = ActorComponent.DEAD;
}
}*/
//serverSituationHistory.get(step).add(new ActorComponent(livingServer, state));
//serverSituationStep.add(new ActorComponent(livingServer, state));
}
serverSituationHistory.put(step, serverSituationStep);
//applicationSituationHistory.put(step, new ArrayList<>());
applicationSituationStep = new ArrayList<>();
stepStartResearch = 0;
for (String applicationName : bpgHistory.getApplicationNames()) {
if ((livingApplication = (FakeApplication) findInStep(applicationName, bpgHistory.getApplicationHistory(), step)) != null) {
state = ActorComponent.ALIVE;
applicationSituationStep.add(new ActorComponent(livingApplication, state, ActorComponent.SQUARE, bpgHistory));
} /*else {
counter = stepStartResearch;
while (livingApplication == null && counter < stepNumber) {
livingApplication = (FakeApplication) findInStep(applicationName, applicationHistory, counter);
counter++;
}
stepStartResearch = counter - 1;
if (counter > step) {
state = ActorComponent.LIMBO;
} else {
state = ActorComponent.DEAD;
}
}*/
//applicationSituationHistory.get(step).add(new ActorComponent(livingApplication, state));
//applicationSituationStep.add(new ActorComponent(livingApplication, state));
}
applicationSituationHistory.put(step, applicationSituationStep);
if (step % 50 == 0) {
System.out.print("*");
}
}
System.out.println();
} |
fb2c6a56-0918-4bdf-974a-946ce0319bb6 | 1 | @Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Close")) {
this.dispose();
}
} |
df0e9aa2-6c65-47fb-902d-59d35082f975 | 3 | private void jRadioButton1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jRadioButton1KeyPressed
if (evt.getKeyCode() == 40) {
jRadioButton2.setSelected(true);
} else if (evt.getKeyCode() == 37) {
jTextField9.grabFocus();
} else if (evt.getKeyCode() == 38) {
jRadioButton1.setSelected(true);
}
}//GEN-LAST:event_jRadioButton1KeyPressed |
bdfbff01-714d-4599-bdff-464519c995aa | 7 | private void compileColorBoard() {
cells = new int[board.length][board[0].length];
largest = 0;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
Matcher m = compileRegex(reg, board[i][j]);
int amt = 0;
if (m.find()) {
for (int k = 0; k <= m.groupCount(); k++) {
try {
// I still get some sort null pointer exception for some patterns
// so I had to surround it with a try-catch
if (m.group(k) != null) amt += m.group(k).length();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
cells[i][j] = amt;
if (cells[i][j] > largest) largest = cells[i][j];
}
}
} |
48086ce6-139c-4325-9491-cd04b274826d | 2 | private void browseButtonAction() {
loggerMainClass.entry();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.setDialogTitle("Select The Source Directory");
if (fileChooser.showDialog(null, "Select") == JFileChooser.APPROVE_OPTION) {
try {
sourceTextArea.insert(fileChooser.getSelectedFile().getCanonicalPath() + "\n", sourceTextArea.getText().length());
loggerMainClass.exit(LoggerValues.SUCCESSFUL_EXIT);
} catch (IOException ioException) {
loggerMainClass.exit(LoggerValues.UNSUCCESSFUL_EXIT);
ExceptionLogger.ioExceptionLogger(loggerMainClass, ioException);
}
}
} |
74a1d15d-8c7d-4ef0-9fd4-a901a04b2e1d | 5 | public static void main(String[] args) throws CloneNotSupportedException {
IPlaystationNetwork device = new Uncharted();
device.uploadUpdate();
System.out.println("Version: " + IPlaystationNetwork.VERSION);
if(device instanceof Uncharted &&
device instanceof PS3Game &&
device instanceof IPlaystationNetwork)
System.out.println("ES TODO ESO!");
if(device instanceof Playable)
System.out.println("Loding GAME!");
device = new PSPhone(9995);
device.uploadUpdate();
((PSPhone)device).loadAppStore();
((iSmartPhone)device).loadAppStore();
if(!(device instanceof Playable))
System.out.println("Implementa IPSN pero NO es un juego");
IPlaystationNetwork ipsn = new IPlaystationNetwork() {
@Override
public boolean connect() {
System.out.println("Connecting directly from PSN");
return true;
}
@Override
public void uploadUpdate() {
System.out.println("Uploading from PSN");
}
};
ipsn.uploadUpdate();
///cloneable
Uncharted drake = new Uncharted();
drake.clone();
} |
d7458ebb-8433-4729-8293-9eb35f6c4ed1 | 9 | @Override
public Token parse() {
Token test = first.getNext();
if (!test.isOperator(Operator.BRACKET_LEFT))
throw new RuntimeException("Expected '(' after FOR, found: " + test.toString());
test = test.getNext();
if (!test.isOperator()) {
preForAssign = new AssignmentExpression(test, scope);
test = preForAssign.parse();
}
if (!test.isOperator(Operator.COLON))
throw new RuntimeException("Expected Colon Operator, found: " + test.toString());
test = test.getNext();
if (!test.isOperator()) {
conditionTest = new BooleanExpression(test, scope);
test = conditionTest.parse();
}
if (!test.isOperator(Operator.COLON))
throw new RuntimeException("Expected Colon Operator, found: " + test.toString());
test = test.getNext();
if (!test.isOperator(Operator.BRACKET_RIGHT)) {
postForAssign = new AssignmentExpression(test, scope);
test = postForAssign.parse();
}
if (!test.isOperator(Operator.BRACKET_RIGHT))
throw new RuntimeException("Expected ')' after post for loop expression, found: " + test.toString());
test = test.getNext();
if (!test.isNewline())
throw new RuntimeException("Expected Newline, found: " + test.toString());
test = test.getNext();
Keyword[] targets = { Keyword.END };
statements = new StatementGroup(test, targets, scope);
test = statements.parse();
if (!test.isKeyword(Keyword.END))
throw new RuntimeException("Expecting keyword 'END' to close 'IF' statement, found: " + test);
return test.getNext();
} |
ec394860-85d6-4112-9eba-375e717b13ba | 0 | @SuppressWarnings("unchecked")
public List<Order> getAllDoneOrders() {
return (List<Order>)this.em.createNamedQuery("findAllDoneOrders").getResultList();
} |
94c7d79d-ef27-4801-887c-294726019b14 | 8 | public void paint2D(Graphics graphics) {
Graphics2D g2 = (Graphics2D)graphics;
/** set the rendering hints */
g2.setRenderingHints((RenderingHints)hints);
/** if game is over */
if (gameOver) {
/** fill the screen with black color */
g2.setColor(Color.black);
g2.fillRect(0, 0, 17 << BomberMain.shiftCount,
17 << BomberMain.shiftCount);
}
/** if game isn't over yet */
else {
/** fill window with background color */
g2.setColor(backgroundColor);
g2.fillRect(0, 0, 17 << BomberMain.shiftCount,
17 << BomberMain.shiftCount);
/** draw the map */
for (int r = 0; r < 17; r++) for (int c = 0; c < 17; c++) {
/** if there's something in the block */
if (grid[r][c] > NOTHING &&
grid[r][c] != BOMB && grid[r][c] != FIRE_BRICK &&
mapImages[level][grid[r][c]] != null) {
g2.drawImage(mapImages[level][grid[r][c]],
r << BomberMain.shiftCount, c << BomberMain.shiftCount,
BomberMain.size, BomberMain.size, null);
}
/** if the block is empty */
else {
if (mapImages[level][2] != null) {
/** draw the floor */
g2.drawImage(mapImages[level][2],
r << BomberMain.shiftCount, c <<
BomberMain.shiftCount, BomberMain.size,
BomberMain.size, null);
}
}
}
}
} |
fa38247d-d612-4bcb-aded-1f759edcc9c3 | 4 | public void move() {
if(hasBreadcrumb) {
location = tripAdvisor.proceed(location, colonyLocation);
} else if(pileLocation != null) {
location = tripAdvisor.proceed(location, pileLocation);
} else {
location = tripAdvisor.randomWalk();
}
if(isOnAPile()) {
hasBreadcrumb = true;
} else if(isInColony()) {
hasBreadcrumb = false;
}
} |
b6542b81-a447-44b8-83c3-a22d33dc81c4 | 9 | public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = "";
int times = 1;
d: do {
line = br.readLine();
if (line == null || line.length() == 0)
break d;
double[] val = returnDoubles(line);
double[] answer = new double[2];
if(val[0]==0)
break;
switch ((int)val[0]) {
case 1:
answer = s_a(val);
break;
case 2:
answer = s_t(val);
break;
case 3:
answer = vf_t(val);
break;
case 4:
answer = vo_t(val);
break;
}
System.out.printf(Locale.US, "Case %d: %.3f %.3f\n", times++, answer[0], answer[1]);
} while (line != null && line.length() != 0);
} |
209640a4-d898-4153-bda6-34244f26c709 | 8 | private XML buildElement() {
EventNode token = eventReader.next();
if (token.getType() != TokenType.START_TAG) throw new XMLException("Broken XML: first token must be START_TAG");
String qname = token.getValue();
XMLElement element = new XMLElement(qname);
List<Entry<String, String>> attributes = token.getAttributes();
if (attributes != null) {
for (Map.Entry<String, String> entry : attributes) {
String attrQname = entry.getKey();
String attrValue = entry.getValue();
element.appendChild(new XMLAttribute(attrQname, attrValue));
}
}
for (;;) {
EventNode nextToken = eventReader.peek();
switch (nextToken.getType()) {
case END_TAG:
eventReader.next();
return element;
case TEXT:
String text = nextToken.getValue();
element.setNodeValue(text);
eventReader.next();
nextToken = eventReader.next();
if (nextToken.getType() != TokenType.END_TAG) throw new XMLException(
"Broken XML: text node must be in the leaf node");
return element;
case START_TAG:
XML child = buildElement();
element.appendChild(child);
}
}
} |
59065e3f-073f-49cd-8bcf-dc0923575f88 | 2 | public void Menu(String protocolo, BufferedReader in, PrintWriter out){
System.out.println("Entrou menu\n");
String comando[] = protocolo.split("-");
System.out.println(comando[0]);
switch (comando[0]) {
case "Logar":
try {
out.println(Logar(protocolo));
} catch (SQLException ex) {
Logger.getLogger(Controle.class.getName()).log(Level.SEVERE, null, ex);
}
break;
}
} |
013ef9f5-6e2c-4e99-b2ce-c074665cee9a | 0 | public SatisfiedApplication() {
setBounds(10, 50, 836, 739);
setLocationRelativeTo(rootPane);
setModal(true);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBackground(new Color(248, 248, 255));
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
} |
49d08a9b-3f64-4190-bc9a-09b5bb7e5c5b | 3 | public boolean areNondeterministic(Transition t1, Transition t2) {
FSATransition transition1 = (FSATransition) t1;
FSATransition transition2 = (FSATransition) t2;
if (transition1.getLabel().equals(transition2.getLabel()))
return true;
else if (transition1.getLabel().startsWith(transition2.getLabel()))
return true;
else if (transition2.getLabel().startsWith(transition1.getLabel()))
return true;
else
return false;
} |
6bc7dacd-0123-4e7b-aafe-1ea80ef6144b | 9 | public ArrayList<Integer> mergeTwoArrays(ArrayList<Integer> a,
ArrayList<Integer> b) {
if (a.size() != b.size()) {
return null;
}
if (a.size() == 0) {
return new ArrayList<Integer>();
}
ArrayList<Integer> result = new ArrayList<Integer>();
int len = a.size();
int ai = 0;
int bi = 0;
while (ai <= len - 1 && bi <= len - 1) {
if (a.get(ai) <= b.get(bi)) {
result.add(a.get(ai));
ai++;
} else {
result.add(b.get(bi));
bi++;
}
}
boolean aEnd = (ai <= len - 1) ? true : false;
if (aEnd) {
for (int i = ai; i <= len - 1; i++) {
result.add(a.get(i));
}
} else {
for (int j = bi; j <= len - 1; j++) {
result.add(b.get(j));
}
}
return result;
} |
27d736d7-9d4e-408e-bab8-4e71092afb7e | 2 | public int getQueueSize() {
int count = 0;
try {
QueueBrowser browser = context.createBrowser(pointsQueue);
Enumeration elems = browser.getEnumeration();
while (elems.hasMoreElements()) {
elems.nextElement();
count++;
}
} catch (JMSException ex) {
ex.printStackTrace();
}
return count;
} |
f5d443b2-33e4-4c07-8c5d-967c5dea10ba | 0 | @Override
public void signalEndOfData() {
synchronized (taskQueue) {
endOfData = true;
taskQueue.notifyAll();
}
} |
55629a50-e528-4653-81c6-0666db8fd1b7 | 3 | @Override
public void performPhysics(Matter matter, Planet nearbyPlanet) {
Gravity planetGravity = nearbyPlanet.getGravity();
double hitsGroundIn = getHitGroundTime(matter, planetGravity);
double processedTime = 0;
double currentTimeStep = 1;
while (hitsGroundIn < currentTimeStep && !Matter.isEffectivelyResting(matter)) {
double hitGroundVelocity = advanceVelocity(hitsGroundIn, matter.getVerticalVelocity(),
planetGravity.getVelocityDecay());
double afterBounceVelocity = hitGroundVelocity * nearbyPlanet.getGroundBounciness();
processedTime += hitsGroundIn;
notifyListeners(matter, processedTime);
currentTimeStep = currentTimeStep - hitsGroundIn;
matter.setHeight(0);
matter.setVerticalVelocity(afterBounceVelocity);
hitsGroundIn = getHitGroundTime(matter, planetGravity);
}
double height;
double velocity;
if (!Matter.isEffectivelyResting(matter)) {
height = advanceHeight(currentTimeStep, matter.getHeight(), matter.getVerticalVelocity(),
planetGravity.getVelocityDecay());
velocity = advanceVelocity(currentTimeStep, matter.getVerticalVelocity(), planetGravity.getVelocityDecay());
} else {
height = 0;
velocity = 0;
}
matter.setHeight(height);
matter.setVerticalVelocity(velocity);
} |
2882bbd2-4916-43e3-a1b6-48b04b1c63cb | 1 | public void write6bytes(long n) throws IOException {
long b0 = n & 0xff;
long b1 = (n & 0xff00) >> 8;
long b2 = (n & 0xff0000) >> 16;
long b3 = (n & 0xff000000) >>> 24;
long b4 = (n & 0xff00000000L) >> 32;
long b5 = (n & 0xff0000000000L) >> 40;
if (le) {
write(b0); write(b1); write(b2); write(b3); write(b4); write(b5);
} else {
write(b5); write(b4); write(b3); write(b2); write(b1); write(b0);
}
} |
67ec0496-1347-456d-8f20-e0bcaca02dd7 | 9 | private boolean check() {
if (!isBST()) System.out.println("Not in symmetric order");
if (!isSizeConsistent()) System.out.println("Subtree counts not consistent");
if (!isRankConsistent()) System.out.println("Ranks not consistent");
if (!is23()) System.out.println("Not a 2-3 tree");
if (!isBalanced()) System.out.println("Not balanced");
return isBST() && isSizeConsistent() && isRankConsistent() && is23() && isBalanced();
} |
77451881-6a5e-41fc-b783-c02462368460 | 0 | public static WebDriver getDriver() {
return driver;
} |
bc0a503f-6132-431a-8c61-c0389d78354f | 7 | public Poly getPoly(int type) {
switch(type) {
case 0: {
return new Poly(makeL()); //creates an L-piece
}
case 1: {
return new Poly(makeJ()); //creates a J-piece
}
case 2: {
return new Poly(makeS()); //creates an S-piece
}
case 3: {
return new Poly(makeZ()); //creates a Z-piece
}
case 4: {
return new Poly(makeT()); //creates a T-piece
}
case 5: {
return new Poly(makeI()); //creates an I-piece
}
case 6: {
return new Poly(makeO()); //creates an O-piece
}
//default : {
// return new Poly(makeO()); //creates an O-piece
//}
}
return null;
} |
d9c1c132-2e37-4e20-8ae6-7ecbf330ea2b | 3 | public int get_main_data_len(){
int ans = 0;
for(int gr = 0; gr < max_gr; gr ++)
for(int ch = 0; ch < channels; ch ++) {
ans += side_info.gr[gr].ch[ch].part2_3_length;
}
ans = ((ans % 8) > 0)? (ans/8 + 1): (ans / 8);
return ans;
} |
bf999281-cc5f-4e91-8822-863b8db3b783 | 2 | @Override
public final void refreshList() {
entityList.clear();
// Update our entityList to only bother with enemies which contain
// OUR specific SpawnSystemTag.
List<Entity> entitesWithSpawnTags = entityManager.getEntitiesContaining(SpawnSystemTag.class);
// Only keep track of our own spawn tag list
for (Entity entity : entitesWithSpawnTags) {
if (entity.getComponent(SpawnSystemTag.class) == spawnNameTag) {
entityList.add(entity);
}
}
} |
1f28e088-031f-4201-baf6-f87c1e42048f | 6 | public Point getFaceOffset(Face face) {
switch (face) {
case TOP:
return this.getTopFaceOffset();
case BOTTOM:
return this.getBottomFaceOffset();
case FRONT:
return this.getFrontFaceOffset();
case BACK:
return this.getBackFaceOffset();
case LEFT:
return this.getLeftFaceOffset();
case RIGHT:
return this.getRightFaceOffset();
}
return null;
} |
00d7b551-08c1-4108-b1af-b7888defa680 | 1 | public static boolean isMac() { // [deric] 31Sep2001
String osName = System.getProperty("os.name");
if (osName.toLowerCase().startsWith("mac")) {
return true;
} else {
return false;
}
} |
2045c3ca-597f-4392-bcb7-918e1ca55d16 | 7 | private void initText() throws FileNotFoundException, IOException {
java.io.BufferedReader reader;
String line;
String[] splitLine;
for (File f : filenameresolver.listFiles("localisation")) {
if (!f.getName().endsWith(".csv"))
continue; // Could use a FileFilter or FilenameFilter
if (f.length() <= 0) {
continue;
}
reader = new java.io.BufferedReader(new java.io.FileReader(f), Math.min(1024000, (int)f.length()));
try {
while ((line = reader.readLine()) != null) {
if (line.startsWith("#"))
continue;
splitLine = semicolon.split(line); //line.split(";");
if (splitLine.length < 2) {
if (!line.contains(";")) {
// If it contains ";", then it's probably just a line like ;;;;;;;;;;;;
// If not, we need to know what it is.
System.err.println("Malformed line in file " + f.getPath() + ":");
System.err.println(line);
}
continue;
}
text.put(splitLine[0].toLowerCase(), splitLine[1]); // English
}
} finally {
reader.close();
}
}
} |
12ad000d-87ef-4ed7-ab82-8289c383ae2f | 3 | public static ArrayList<Rating> getTestSet(String file) {
ArrayList<Rating> testset = new ArrayList<Rating>();
InputStream fis = null;
BufferedReader br;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
br = new BufferedReader(new InputStreamReader(fis,
Charset.forName("UTF-8")));
try {
String line;
while ((line = br.readLine()) != null) {
// Deal with the line
String fields[] = line.split(",");
Rating r = new Rating();
r.user = Long.parseLong(fields[0]);
r.item = Long.parseLong(fields[1]);
r.rating = Float.parseFloat(fields[2]);
testset.add(r);
}
br.close();
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return testset;
} |
bb50ec65-85ed-47bd-a086-67bce6691383 | 4 | protected void addListeners() {
buttonStart.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String fResult = "# Celsius to Fahrenheit: \n";
String cResult = "# Fahrenheit to Celsius: \n";
try {
fResult += String.valueOf(adapter.celsiusToFahrenheit(textFieldFirstValue.getText()))+ "\n";
}
catch (InvalidParameterException ex) {fResult += ex.getLocalizedMessage() +"\n";}
catch (NumberFormatException ne){fResult += "/ \n";}
try {
cResult += String.valueOf(adapter.fahrenheitToCelsius(textFieldSecondValue.getText()));
}
catch (InvalidParameterException ex) {cResult += ex.getLocalizedMessage() +"\n";}
catch (NumberFormatException ne){cResult += "/ \n ";}
textArea.setText(fResult + cResult);
}
});
} |
f3924fec-5ffb-452b-bfc9-7d917c993cfe | 9 | static byte PistonFix(byte data, String kierunek)
{
if (kierunek.equals("right"))
{
if (data == 2) {
return 5;
}
if (data == 4) {
return 2;
}
if (data == 5) {
return 3;
}
if (data == 3) {
return 4;
}
}
else
{
if (data == 5) {
return 2;
}
if (data == 2) {
return 4;
}
if (data == 3) {
return 5;
}
if (data == 4) {
return 3;
}
}
return data;
} |
fb015366-2db1-4525-b592-13f20a03bb57 | 2 | public boolean isMouseOverCloseButton(Point mousePosition) {
if(mousePosition == null || fButtonShape == null) {
return false;
}
return fButtonShape.contains(mousePosition);
} |
98b8a8af-7e3e-440f-a811-79fd02ec3f15 | 2 | private int findSlot(int hash){
int mask = cap - 1;
int bkt = (hash & mask);
int bhash = hopidx[bkt<<2];
int slot;
if(bhash == 0)
slot = bkt<<2;
else
{
for(;hopidx[(bkt<<2) + 2] != 0; bkt = (bkt + 1) & mask)
;
slot = (bkt<<2) + 2;
}
return slot;
} |
b1d53743-96bc-4168-9aa0-9d021c764d88 | 3 | public static void main(String[] args) throws Exception {
String baseFilename = args[0];
int nShards = Integer.parseInt(args[1]);
String fileType = (args.length >= 3 ? args[2] : null);
/* Create shards */
FastSharder sharder = createSharder(baseFilename, nShards);
if (baseFilename.equals("pipein")) { // Allow piping graph in
sharder.shard(System.in, fileType);
} else {
if (!new File(ChiFilenames.getFilenameIntervals(baseFilename, nShards)).exists()) {
sharder.shard(new FileInputStream(new File(baseFilename)), fileType);
} else {
logger.info("Found shards -- no need to preprocess");
}
}
/* Run GraphChi ... */
GraphChiEngine<Integer, Integer> engine = new GraphChiEngine<Integer, Integer>(baseFilename, nShards);
engine.setEdataConverter(new IntConverter());
engine.setVertexDataConverter(new IntConverter());
engine.setEnableScheduler(true);
engine.run(new ConnectedComponents(), 5);
logger.info("Ready. Going to output...");
/* Process output. The output file has format <vertex-id, component-id> */
LabelAnalysis.computeLabels(baseFilename, engine.numVertices(), engine.getVertexIdTranslate());
logger.info("Finished. See file: " + baseFilename + ".components");
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.