text stringlengths 14 410k | label int32 0 9 |
|---|---|
public static void validateUsername(String username) throws ProtocolException {
if(username.length() < 3){
throw new ProtocolException("Username too short: needs to be 3 characters or longer.");
}
if(username.length() > 16){
throw new ProtocolException("Username too long: needs to be 16 characters or less.");
}
if(!Pattern.matches("[a-zA-Z0-9-_+]+", username)){
throw new ProtocolException("Username contains invalid characters. May only contain "
+ "a-z, A-Z, 0-9, -, _, +.");
}
} | 3 |
static boolean haveImage (int w, int h, Color c, int ox, int oy, int d)
{ if (StaticImage==null) return false;
return (w==W && h==H && ox==Ox && oy==Oy && D==d && C.getRGB()==c.getRGB());
} | 6 |
public static Cons yieldInCursorClauses(Cons intree, boolean dontoptimizeP, Object [] MV_returnarray) {
{ Stella_Object vartree = intree.rest.value;
Symbol keyvar = null;
Symbol valuevar = null;
Surrogate collectionbasetype = null;
{ Stella_Object collectiontree = null;
StandardObject collectiontype = null;
{ Object [] caller_MV_returnarray = new Object[1];
collectiontree = Stella_Object.walkCollectionTree(intree.rest.rest.value, dontoptimizeP, caller_MV_returnarray);
collectiontype = ((StandardObject)(caller_MV_returnarray[0]));
}
intree.thirdSetter(null);
collectionbasetype = StandardObject.typeSpecToBaseType(collectiontype);
if (dontoptimizeP &&
(!Surrogate.safeSubtypeOfP(collectionbasetype, Stella.SGT_STELLA_ABSTRACT_ITERATOR))) {
{ Object [] caller_MV_returnarray = new Object[1];
collectiontree = Stella_Object.walkCollectionTree(Cons.list$(Cons.cons(Stella.SYM_STELLA_ALLOCATE_ITERATOR, Cons.cons(collectiontree, Cons.cons(Stella.NIL, Stella.NIL)))), true, caller_MV_returnarray);
collectiontype = ((StandardObject)(caller_MV_returnarray[0]));
}
collectionbasetype = StandardObject.typeSpecToBaseType(collectiontype);
}
if (Stella_Object.safePrimaryType(vartree) == Stella.SGT_STELLA_CONS) {
{ Cons vartree000 = ((Cons)(vartree));
if (!(vartree000.length() == 2)) {
{ Object old$PrintreadablyP$000 = Stella.$PRINTREADABLYp$.get();
try {
Native.setBooleanSpecial(Stella.$PRINTREADABLYp$, true);
Stella.signalTranslationError();
if (!(Stella.suppressWarningsP())) {
Stella.printErrorContext(">> ERROR: ", Stella.STANDARD_ERROR);
{
Stella.STANDARD_ERROR.nativeStream.println();
Stella.STANDARD_ERROR.nativeStream.println(" Illegal number of variables in IN clause: `" + Stella_Object.deUglifyParseTree(intree) + "'.");
}
;
}
} finally {
Stella.$PRINTREADABLYp$.set(old$PrintreadablyP$000);
}
}
{ Cons _return_temp = Stella.NIL;
MV_returnarray[0] = Stella.NIL;
MV_returnarray[1] = Stella.NIL;
MV_returnarray[2] = Stella.SYM_STELLA_FALSE;
return (_return_temp);
}
}
keyvar = ((Symbol)(vartree000.value));
valuevar = ((Symbol)(vartree000.rest.value));
}
}
else {
valuevar = ((Symbol)(vartree));
}
if (collectionbasetype == Stella.SGT_STELLA_INTEGER_INTERVAL) {
return (Cons.yieldInCursorClausesForIntegerInterval(((Cons)(collectiontree)), collectiontype, keyvar, valuevar, MV_returnarray));
}
else if (collectionbasetype == Stella.SGT_STELLA_ARGUMENT_LIST) {
return (Stella_Object.yieldInCursorClausesForArgumentList(collectiontree, collectiontype, keyvar, valuevar, MV_returnarray));
}
else {
if (Surrogate.useVectorStyleIterationP(collectionbasetype)) {
return (Stella_Object.yieldInCursorClausesForVector(collectiontree, collectiontype, keyvar, valuevar, MV_returnarray));
}
else {
return (Stella_Object.yieldInCursorClausesForGeneralCollection(collectiontree, collectiontype, keyvar, valuevar, MV_returnarray));
}
}
}
}
} | 8 |
public boolean refreshStatus() {
// - Get the status
Icon icon;
String info = null;
switch (lfs.getStatus()) {
case LessFileStatus.UP_TO_DATE:
icon = OK;
break;
case LessFileStatus.ERROR:
icon = ERROR;
break;
case LessFileStatus.UNKNOWN:
case LessFileStatus.PROCESSING:
icon = WAIT;
break;
default:
throw new BugError("Invalid status: " + lfs.getStatus());
}
info = lfs.getInfoMessage();
// - Check if change
if (lastStatusIcon == icon && lastInfoMessage != null && lastInfoMessage.equals(info))
return false;
this.lastInfoMessage = info;
this.lastStatusIcon = icon;
// - Update components
infoMessageLabel.setText(info);
statusLabel.setIcon(icon);
return true;
} | 7 |
@Override
public int allocateClusters(int tailCluster, int count) throws IOException {
int headCluster = -1;
int tailOffset = tailCluster;
while (count > 0 && freeListHead >= 0) {
int fatEntry = fs.getFatEntry(freeListHead);
if ((fatEntry & CLUSTER_STATUS) == CLUSTER_FREE || fatEntry == CLUSTER_FREE_EOC) {
if (headCluster == -1)
headCluster = freeListHead;
// "God, save EOC on power down!"
// mark as EOC
--fs.freeClusterCount;
fs.putFatEntry(freeListHead, CLUSTER_EOC);
if (tailOffset != -1) {
// mark as ALLOCATED with forward index
fs.putFatEntry(tailOffset, CLUSTER_ALLOCATED | freeListHead);
}
tailOffset = freeListHead;
freeListHead = (fatEntry == CLUSTER_FREE_EOC)
? -1
: (fatEntry & CLUSTER_INDEX);
--count;
if (count == 0)
return headCluster;
} else {
fs.LogError("Wrong value in free list.");
break;
}
}
fs.setDirtyState("[freeClusterCount] has wrong value.", false);
// rollback allocation.
if (tailCluster == -1)
freeClusters(headCluster, true);
else
freeClusters(tailCluster, false);
throw new IOException("Disk full.");
} | 9 |
@Override
public void run(){
Scanner sc = new Scanner(System.in);
ArrayList<MenuItem> menu = menuManager.getMenu();
while(true){
System.out.print("1. Add New Alacarte to Menu \n"
+ "2. Add New Set to Menu\n3. Delete MenuItem from the Menu\n4. Update the Alacarte\n"
+"5. Update the Set on the Menu\n6. Show all MenuItems \n7. Back\nChoose which you want:" );
int choice = inputInteger();
switch (choice){
case 1 :
System.out.print("The name of the new Alacarte:\t");
String name = sc.nextLine();
System.out.print("The description of the new Alacarte:\t");
String description = sc.nextLine();
System.out.print("The category of the new Alacarte:\t");
String category = sc.next();
System.out.print("The price of the new Alacarte:\t");
double price = inputDouble();
sc.nextLine();
menuManager.addAlaCartetoMenu(name, description, category, price);
break;
case 2 :
createSet(menuManager);
break;
case 3:
deleteMenuItem(menuManager);
break;
case 4 :
updateAlacarte(menu);
break;
case 5 :
updateSet(menu);
break;
case 6:
System.out.println(menuManager.menuToString());
break;
default:
return;
}
}
} | 7 |
private String createAuction() {
if (user.isOnline()) {
int duration = 0;
String describtion = "";
try {
duration = Integer.parseInt(stringParts[1]);
if (duration <= 0) {
return "Error: The duration has to be > 0!";
}
for (int i = 2; i < stringParts.length; i++) {
describtion += " " + stringParts[i];
}
describtion = describtion.substring(1);
} catch (ArrayIndexOutOfBoundsException e) {
return answer = "Error: Please enter the create command like this: " +
"!create <duration> + <describtion>";
} catch (StringIndexOutOfBoundsException e) {
return answer = "Error: Please enter the create command like this: " +
"!create <duration> + <describtion>";
} catch (NumberFormatException e) {
return answer = "Error: The Server does not allow this time- format!";
}
Auction auction = new Auction(user, duration, describtion, udpPort, userManagement, mClientHandler);
auction = userManagement.createAuction(auction);
// RMI AUCTION_STARTED
Timestamp logoutTimestamp = new Timestamp(System.currentTimeMillis());
long timestamp = logoutTimestamp.getTime();
try {
mClientHandler.processEvent(new AuctionEvent(AuctionEvent.AUCTION_STARTED, timestamp, auction.getId()));
} catch (RemoteException e) {
logger.error("Failed to connect to the Analytics Server");
} catch (WrongEventTypeException e) {
logger.error("Wrong type of Event");
} catch (NullPointerException e) {
}
String response = "An auction '" + auction.describtion +
"' with id " + auction.getId() +
" has been created and will end on " +
auction.getEndOfAuctionStringTimestamp() + " CET.";
logger.info(response);
return response;
}
return "You have to log in first!";
} | 9 |
@Override
public boolean execute(final MOB mob, List<String> commands, int metaFlags)
throws java.io.IOException
{
if(mob.soulMate()!=null)
dispossess(mob,CMParms.combine(commands).endsWith("!"));
else
if(!mob.isMonster())
{
final Session session=mob.session();
if(session!=null)
{
if((session.getLastPKFight()>0)
&&((System.currentTimeMillis()-session.getLastPKFight())<(5*60*1000))
&&(!CMSecurity.isASysOp(mob)))
{
mob.tell(L("You must wait a few more minutes before you are allowed to quit."));
return false;
}
session.prompt(new InputCallback(InputCallback.Type.CONFIRM, "N", 30000)
{
@Override
public void showPrompt()
{
session.promptPrint(L("\n\rQuit -- are you sure (y/N)?"));
}
@Override public void timedOut() {}
@Override
public void callBack()
{
if(this.confirmed)
{
final CMMsg msg=CMClass.getMsg(mob,null,CMMsg.MSG_QUIT,null);
final Room R=mob.location();
if((R!=null)&&(R.okMessage(mob,msg)))
{
CMLib.map().sendGlobalMessage(mob,CMMsg.TYP_QUIT, msg);
session.stopSession(false,false, false); // this should call prelogout and later loginlogoutthread to cause msg SEND
CMLib.commands().monitorGlobalMessage(R, msg);
}
}
}
});
}
}
return false;
} | 9 |
public List<?>[] getStates()
{
ArrayList<Integer> ids = new ArrayList<Integer>();
ArrayList<TaggedStorageChunk> chunks = new ArrayList<TaggedStorageChunk>();
try
{
DataInputStream in = new DataInputStream(new ByteArrayInputStream(data));
int size = in.readInt();
for(int i = 0;i<size;i++)
{
try
{
String entityClass = in.readUTF();
InputStream in1 = new ByteArrayInputStream(Base64.decodeBase64(in.readUTF()));
byte[] bytes = IO.read(in1);
in1.close();
TaggedStorageChunk chunk = BlockyMain.saveSystem.readChunk(bytes);
String s = chunk.getChunkName().replaceFirst("Entity_", "");
ids.add(Integer.parseInt(s.substring(s.lastIndexOf("_")+1)));
chunks.add(chunk);
}
catch(Exception e)
{
if(e instanceof EOFException)
{
}
else
e.printStackTrace();
}
}
in.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return new List[]{ids, chunks};
} | 5 |
protected void processSingleClick(MouseEvent e) {
Node node = textArea.node;
JoeTree tree = node.getTree();
if (e.isShiftDown()) {
tree.selectRangeFromMostRecentNodeTouched(node);
} else if (e.isControlDown()) {
if (node.isSelected() && (tree.getSelectedNodes().size() != 1)) {
tree.removeNodeFromSelection(node);
} else if (tree.getSelectedNodesParent() == node.getParent()) {
tree.addNodeToSelection(node);
}
} else if (!node.isSelected()) {
tree.setSelectedNodesParent(node.getParent());
tree.addNodeToSelection(node);
}
} | 6 |
public static String formatName(String name) {
if (name.length() > 0) {
char characters[] = name.toCharArray();
for (int c = 0; c < characters.length; c++)
if (characters[c] == '_') {
characters[c] = ' ';
if (c + 1 < characters.length && characters[c + 1] >= 'a'
&& characters[c + 1] <= 'z')
characters[c + 1] = (char) ((characters[c + 1] + 65) - 97);
}
if (characters[0] >= 'a' && characters[0] <= 'z')
characters[0] = (char) ((characters[0] + 65) - 97);
return new String(characters);
} else {
return name;
}
} | 8 |
private void spellCheck() {
String word = this.currentWord.toString();
if (!word.equals("")
&& SpellChecker.getInstance().isMisspelled(word)) {
if (this.spllingErrorHandler != null) {
this.spllingErrorHandler
.handleSpellingError(this.currentWord.toString(),
this.uiGlyphs
.toArray(new UiGlyph[this.uiGlyphs
.size()]));
}
}
this.currentWord = new StringBuffer();
this.currentGlyphs.clear();
} | 3 |
public Tree orExpressionPro(){
Tree firstConditionalExpression = null, secondConditionalExpression = null;
Symbol operator = null;
if((firstConditionalExpression = andExpressionPro()) != null){
if((operator = accept(Symbol.Id.PUNCTUATORS,"\\|\\|")) != null){
if((secondConditionalExpression = orExpressionPro()) != null){
return new BinaryExpression(firstConditionalExpression,
operator, secondConditionalExpression);
}
return null;
}
return firstConditionalExpression;
}
return null;
} | 3 |
public void addQLDropTargets(DropTargetFactory dtf){
for(JButton btn : quick_btns){
btn.setDropTarget(dtf.makeDropTarget());
}
} | 1 |
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void collecter(APreprocessingEngine aPPEngine) {
try {
File[] lesFichiers = repertoireInput.listFiles();
if (lesFichiers != null) {
for (int i = 0; i < lesFichiers.length; i++) {
String leContenu = new String();
BufferedReader reader = new BufferedReader(new FileReader(
lesFichiers[i].getAbsolutePath()));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
if (stringBuilder.length() > 0) {
stringBuilder.setLength(stringBuilder.length() - 1);
}
leContenu = stringBuilder.toString();
reader.close();
Document docEnCours = new Document(
lesFichiers[i].getAbsolutePath(), leContenu);
aPPEngine.ajouterEnFileDAtente(docEnCours);
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} | 6 |
public void setSpeech(String speech) {
this.speech = speech;
} | 0 |
public static void readCSVFile(String path, String csvSplitBy) {
BufferedReader read;
String line;
try {
read = new BufferedReader(new FileReader(path));
while ((line = read.readLine()) != null) {
String[] data = line.split(csvSplitBy);
QuestionManager.addQuestion(convertToQuestion(data));
}
read.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(QuestionLoader.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(QuestionLoader.class.getName()).log(Level.SEVERE, null, ex);
}
} | 3 |
public static void main(String[] args) throws JSONException {
/* Thread t = new Thread();
t.start();*/
for(int i=1;i<10000;){
JSONArray data = getData(i);
String res = data.getString(0);
JSONObject o = new JSONObject(res);
//System.out.println(o);
JSONObject o1 = new JSONObject(o.get("response").toString());
System.out.println(o1.toString());
JSONObject obj = new JSONObject(o1.toString());
String [] names = obj.getNames(obj);
String rs = names[0];
if(rs.equalsIgnoreCase("result")){
System.out.println(obj.toString());
i=i+200;
}
else
break;
}
//Map<String,String> map = new HashMap<String,String>();
//ObjectMapper mapper = new ObjectMapper();
} | 2 |
public void reapply(){
if( factory != null ){
factory.setDiagram( view.getDiagram() );
}
} | 1 |
@Override
public double execute(Date start, Date end) {
int duration = TimeCalculator.duration(start, end);
duration = duration % this.minuteUnit > 0 ? (duration / this.minuteUnit + 1)
: duration / this.minuteUnit;
double price = 0;
if (duration == 1) {
price = this.firstMinutePrice;
} else if (duration <= this.firstNMinute) {
price = this.pricePerMinuteBeforeN * duration;
} else if (duration > this.firstNMinute) {
price = this.pricePerMinuteAfterN * duration;
}
return DecimalCleaner.round(price, 3);
} | 4 |
public static void main(String[] args) {
int[][] adjacencyMatrix;
Scanner in = new Scanner(System.in);
// get first line and get the number of cases to test.
int caseCount = Integer.parseInt(in.nextLine());
int loopCount = 0;
while (caseCount - loopCount > 0) {
String line = in.nextLine();
// extract numbers, this is the node count and edge count.
Scanner sc = new Scanner(line);
int vertexCount = sc.nextInt();
int edgeCount = sc.nextInt();
// Create the matrix, and clear the contents.
adjacencyMatrix = new int[vertexCount][vertexCount];
for (int i = 0; i < vertexCount; i++) {
for (int j = 0; j < vertexCount; j++) {
adjacencyMatrix[i][j] = 0;
}
}
// Read in all the edges.
while (edgeCount-- > 0) {
// Get our next edge...
line = in.nextLine();
// extract numbers, this is the node count and edge count.
sc = new Scanner(line);
int source = sc.nextInt();
int destination = sc.nextInt();
int weight = sc.nextInt();
adjacencyMatrix[source][destination] = weight;
}
// Print out the matrix.
System.out.printf("%d\n ", ++loopCount);
// Print the row header.
for(int i = 0; i < vertexCount; i++){
System.out.printf("%5d", i);
}
System.out.println();
// Print the matrix contents
for (int i = 0; i < vertexCount; i++) {
System.out.printf("%4d", i); // Row number
for (int j = 0; j < vertexCount; j++) {
System.out.printf("%5d",adjacencyMatrix[i][j]); // Cell
}
System.out.println();
}
}
} | 7 |
public double value()
{
ArrayList<Object> argsValues = new ArrayList<Object>();
for (Block arg: args)
{
argsValues.add(arg.value());
}
try
{
return (Double) method.invoke(null, argsValues.toArray());
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (java.lang.reflect.InvocationTargetException e) {
}
return 0;
} | 4 |
public ResultSet queryResult(String query) {
final Connection connection = getConnection();
try {
if (connection == null) {
Utilities.outputError("Could not connect to database '" + m_databaseName + "'");
return null;
}
if (m_statement != null) {
m_statement.close();
m_statement = null;
}
m_statement = connection.createStatement();
ResultSet result = m_statement.executeQuery(query);
if (result == null) {
m_statement.close();
m_statement = null;
connection.close();
}
return result;
} catch (SQLException e) {
e.printStackTrace();
try {
m_statement.close();
connection.close();
} catch (SQLException ce) {}
}
return null;
} | 5 |
private void doEditUser(HttpServletRequest request, HttpServletResponse response,boolean isEditUser) throws ServletException, IOException {
String userId = StringUtil.toString(request.getParameter("userId"));
if(!StringUtil.isEmpty(userId)) {
User user = null;
try {
user = manager.findUserByColumnName(userId,"id");
if(user != null) {
request.setAttribute("isEdit",isEditUser);
request.setAttribute("currentUserObj",user);
request.getRequestDispatcher("/admin/user/viewUser.jsp").forward(request,response);
return;
}
} catch (SQLException e) {
logger.error("查看用户失败",e);
request.getRequestDispatcher("/admin/error.jsp").forward(request,response);
return;
}
}
} | 3 |
private Image getImage(String filename) {
// to read from file
ImageIcon icon = new ImageIcon(filename);
// try to read from URL
if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) {
try {
URL url = new URL(filename);
icon = new ImageIcon(url);
} catch (Exception e) { /* not a url */ }
}
// in case file is inside a .jar
if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) {
URL url = Draw.class.getResource(filename);
if (url == null) throw new RuntimeException("image " + filename + " not found");
icon = new ImageIcon(url);
}
return icon.getImage();
} | 6 |
public void saveModel() {
try {
if (m_fileChooser == null) {
// i.e. after de-serialization
m_fileChooser =
new JFileChooser(new File(System.getProperty("user.dir")));
ExtensionFileFilter ef = new ExtensionFileFilter("model", "Serialized weka clusterer");
m_fileChooser.setFileFilter(ef);
}
int returnVal = m_fileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File saveTo = m_fileChooser.getSelectedFile();
String fn = saveTo.getAbsolutePath();
if (!fn.endsWith(".model")) {
fn += ".model";
saveTo = new File(fn);
}
ObjectOutputStream os =
new ObjectOutputStream(new BufferedOutputStream(
new FileOutputStream(saveTo)));
os.writeObject(m_Clusterer);
if (m_trainingSet != null) {
Instances header = new Instances(m_trainingSet, 0);
os.writeObject(header);
}
os.close();
if (m_log != null) {
m_log.logMessage("[Clusterer] Saved clusterer " + getCustomName());
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(Clusterer.this,
"Problem saving clusterer.\n",
"Save Model",
JOptionPane.ERROR_MESSAGE);
if (m_log != null) {
m_log.logMessage("[Clusterer] Problem saving clusterer. "
+ getCustomName() + ex.getMessage());
}
}
} | 7 |
@Override
public void run() {
try {
//1. creating a server socket
providerSocket = new ServerSocket(2004, 10);
//2. Wait for connection
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
//3. get Input and Output streams
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
sendMessage("Connection successful");
//4. The two parts communicate via the input and output streams
do {
try {
message = (String) in.readObject();
System.out.println("client>" + message);
if (message.equals("bye")) {
sendMessage("bye");
}
} catch (ClassNotFoundException e) {
System.err.println("Data received in unknown format");
}
} while (!message.equals("bye"));
} catch (IOException ioException) {
//ioException.printStackTrace();
} finally {
closeConnection();
}
} | 4 |
public Tuple<GameCharacter, Item> battleMenu(GameCharacter hero) {
System.out.println("\n" + hero.getName() + "'s turn!");
System.out.println("1.) Attack somebody.");
System.out.println("2.) Use an item.");
System.out.println("3.) View your party.");
System.out.println("4.) View enemy party.");
int choice = userChoice("menu", 4);
GameCharacter target = null;
Item itemToUse = null;
switch(choice) {
case 0:
break;
case 1:
System.out.println("\nSelect who you wish to attack.");
printParty(monsters);
target = chooseTarget(userChoice("monsters", 0), "monsters");
break;
case 2:
System.out.println("\nSelect an item to use.");
itemToUse = getItem(hero);
if(itemToUse != null){
if(itemToUse.getType() == Items.DAMAGE){
System.out.println("\nSelect a target.");
printParty(monsters);
target = chooseTarget(userChoice("monsters", 0), "monsters");
}
else if(itemToUse.getType() == Items.HEALING){
System.out.println("\nSelect a hero.");
printParty(heroes);
target = chooseTarget(userChoice("heroes", 0), "heroes");
}
}
break;
case 3:
System.out.println("\nCurrent party:\n");
printParty(heroes);
break;
case 4:
System.out.println("\nMonster party:");
printParty(monsters);
break;
default:
System.out.println("\nIncorrect input.");
}
return new Tuple<GameCharacter, Item>(target, itemToUse);
} | 8 |
public boolean needShuffle() {
if (count == 50)
return true;
else
return false;
} | 1 |
@Override
public TLValue evaluate() {
TLValue a = lhs.evaluate();
TLValue b = rhs.evaluate();
// number + number
if(a.isNumber() && b.isNumber()) {
return new TLValue(a.asDouble() / b.asDouble());
}
throw new RuntimeException("illegal expression: " + this);
} | 2 |
public static void deleteFile(File file)
{
if (file.isDirectory())
{
File[] children = file.listFiles();
if (children != null)
{
for (File child : children)
deleteFile(child);
}
children = file.listFiles();
if (children == null || children.length == 0)
{
if (!file.delete())
System.out.println("Error: Could not delete folder: " + file.getPath());
}
}
else if (file.isFile())
{
if (!file.delete())
System.out.println("Error: Could not delete file: " + file.getPath());
}
} | 8 |
private void initialize() {
frmShowProduct = new JFrame();
textField_nr = new JTextField();
textArea_info = new JTextArea();
textField_nr.setHorizontalAlignment(SwingConstants.CENTER);
JButton btnShow = new JButton("show");
frmShowProduct.setTitle("Show Product");
frmShowProduct.setBounds(100, 100, 450, 300);
// frmShowProduct.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textField_nr.setColumns(10);
JLabel lblProductkey = new JLabel("Productnr:");
JLabel lblProductname = new JLabel("Productname:");
textField_name = new JTextField();
textField_name.setColumns(10);
JButton btnSave = new JButton("Save");
GroupLayout groupLayout = new GroupLayout(frmShowProduct.getContentPane());
groupLayout.setHorizontalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(
groupLayout
.createSequentialGroup()
.addGap(39)
.addGroup(
groupLayout
.createParallelGroup(Alignment.LEADING, false)
.addGroup(
groupLayout
.createSequentialGroup()
.addComponent(lblProductname)
.addGap(40)
.addComponent(textField_name, GroupLayout.PREFERRED_SIZE, 136,
GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.RELATED,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnSave))
.addComponent(textArea_info, GroupLayout.PREFERRED_SIZE, 373,
GroupLayout.PREFERRED_SIZE)
.addGroup(
groupLayout
.createSequentialGroup()
.addComponent(lblProductkey, GroupLayout.PREFERRED_SIZE, 100,
GroupLayout.PREFERRED_SIZE)
.addGap(35)
.addComponent(textField_nr, GroupLayout.PREFERRED_SIZE, 80,
GroupLayout.PREFERRED_SIZE)
.addGap(41)
.addComponent(btnShow, GroupLayout.PREFERRED_SIZE, 117,
GroupLayout.PREFERRED_SIZE))).addGap(34)));
groupLayout.setVerticalGroup(groupLayout.createParallelGroup(Alignment.LEADING).addGroup(
groupLayout
.createSequentialGroup()
.addGap(12)
.addGroup(
groupLayout
.createParallelGroup(Alignment.LEADING)
.addGroup(
groupLayout.createSequentialGroup().addGap(5)
.addComponent(lblProductkey))
.addGroup(
groupLayout
.createSequentialGroup()
.addGap(3)
.addComponent(textField_nr, GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addComponent(btnShow))
.addGap(18)
.addComponent(textArea_info, GroupLayout.PREFERRED_SIZE, 169, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(
groupLayout
.createParallelGroup(Alignment.BASELINE)
.addComponent(lblProductname)
.addComponent(btnSave)
.addComponent(textField_name, GroupLayout.PREFERRED_SIZE,
GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)).addGap(23)));
frmShowProduct.getContentPane().setLayout(groupLayout);
btnShow.addActionListener(new ActionListener() { // der Button-Druck
// triggert die
// Produktsuche
public void actionPerformed(ActionEvent e) {
try {
requestProduct();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
btnSave.addActionListener(new ActionListener() { // der Button-Druck
// triggert die
// Produktsuche
public void actionPerformed(ActionEvent e) {
try {
postProduct();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
textField_nr.addKeyListener(this);
textField_name.addKeyListener(this);
} | 2 |
@Override
public HashMap<Integer, ArrayList<SamplePoint>> SpatialTemporalWindowQuery(long midTime, long tRadius, double longitude, double latitude, double sRadius) {
// TODO Auto-generated method stub
HashMap<Integer, ArrayList<SamplePoint>> result = new HashMap<>();
int segmentID;
for (int i=0;i<this.tt.getData().size();i++){
segmentID=this.tt.getData().get(i).getSid();
if (this.st.getData().get(segmentID).getMbr().getTe() < (midTime-tRadius)
|| this.st.getData().get(segmentID).getMbr().getTs() > (midTime+tRadius)){
continue;
}
if(!IsColliding.isCollidingCircleRectangle(longitude,latitude, sRadius,
(this.st.getData().get(segmentID).getMbr().getXhigh()+this.st.getData().get(segmentID).getMbr().getXlow())/2,
(this.st.getData().get(segmentID).getMbr().getYhigh()+this.st.getData().get(segmentID).getMbr().getYlow())/2,
this.st.getData().get(segmentID).getMbr().getXhigh()-this.st.getData().get(segmentID).getMbr().getXlow(),
this.st.getData().get(segmentID).getMbr().getYhigh()-this.st.getData().get(segmentID).getMbr().getYlow())){
continue;
}
for (int j=0;j<this.st.getData().get(segmentID).getData().size();j++){
if(this.st.getData().get(segmentID).getData().get(j).getT()<=(midTime+tRadius)
&& this.st.getData().get(segmentID).getData().get(j).getT()>=(midTime-tRadius)
&& commonMethods.Distance.getDistance(longitude,latitude,this.st.getData().get(segmentID).getData().get(j).getX(),this.st.getData().get(segmentID).getData().get(j).getY())<=sRadius){
if (result.containsKey(this.tt.getData().get(i).getTid())){
result.get(this.tt.getData().get(i).getTid()).add
(new SamplePoint(this.st.getData().get(segmentID).getData().get(j).getX(),
this.st.getData().get(segmentID).getData().get(j).getY(),
this.st.getData().get(segmentID).getData().get(j).getT()));
}else{
ArrayList<SamplePoint> temp = new ArrayList<>();
temp.add(new SamplePoint(this.st.getData().get(segmentID).getData().get(j).getX(),
this.st.getData().get(segmentID).getData().get(j).getY(),
this.st.getData().get(segmentID).getData().get(j).getT()));
result.put(this.tt.getData().get(i).getTid(), temp);
}
}
}
}
return result;
} | 9 |
protected static void stopChatServer(Thread chatServerThread) {
while (chatServerThread.isAlive()) {
chatServerThread.interrupt();
log.info("INTERRUPT chat Server Thread");
try {
// this dummyClient is needed when chatServerThread
// is blocked in serverSocket.accept();
Socket dummyClient = new Socket (help.Default.SERVER_INFO.getIpAddress(),help.Default.SERVER_INFO.getPort());
log.info("CREATE dummy socket");
dummyClient.close();
log.info("CLOSE dummy socket");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.info("Receive UnknownHostException");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.info("Receive IOException");
}
try {
log.info("JOIN chat Server Thread");
chatServerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
log.info("Server Main thread is interrupted when stoping serever chat thread");
}
}
log.info("Server Main thread stop chat server thread");
} | 4 |
public Node checkISBNDel(Node temproot,int isbn){ //find the node(book object with ISBN
boolean b=false;
if(temproot!=null){
if(temproot.leftChld!=null || temproot.rightChld!=null)
parent=temproot; //keep the track of parent of current node
checkISBNDel(temproot.leftChld,isbn); // call recursively and go to left subtree
current=temproot;
b=matchISBN(current,isbn); //check if ISBN is contain
if(b==true){
match=current;
}
checkISBNDel(temproot.rightChld,isbn); // call recursively and go to right subtree
if(temproot.leftChld!=null || temproot.rightChld!=null)
parent=temproot;
}
return match;
} | 6 |
public void deleteSelectedElements() {
for (Element element : selectedElements) {
// Place
if (element instanceof Place) {
((PetriNet) getGraph()).deletePlace(((Place) element).getName());
}
// Transition
if (element instanceof Transition) {
((PetriNet) getGraph()).deleteTransition(((Transition) element).getName());
}
// Node
if (element instanceof Node) {
((PrecedenceGraph) getGraph()).deleteNode(((Node) element).getName());
}
// Place
if (element instanceof Resource) {
((PetriNet) getGraph()).deleteResource(((Resource) element).getName());
}
if (element instanceof Arc) {
((PetriNet) getGraph()).deleteArc(((Arc) element).getName());
}
}
selectedElements.clear();
updateComponentList();
resetForm();
repaint();
} | 6 |
@GET
@Path("events/{id}")
@Produces({MediaType.APPLICATION_JSON })
public EventItf getEvent(@PathParam("id")int idEvent){
System.out.println("Return the event selected by the id");
return JpaTest.eventService.getEvent(idEvent);
} | 0 |
@Override
public ArrayList<Move> generateMovesForThisPiece(Chessboard chessboard) {
int toX = -1, toY = -1;
final ArrayList<Move> moves = new ArrayList<Move>();
final String positionPiece = chessboard.getPositionPiece(this);
final int getX = Helper.getXfromString(positionPiece);
final int getY = Helper.getYfromString(positionPiece);
// 4 direction
for (int direction = 0; direction < 4; direction++)
// Max 8 moves
{
for (int length = 1; length < 9; length++) {
if (direction == 0) {
toX = getX + length;
toY = getY + length;
}
if (direction == 1) {
toX = getX - length;
toY = getY + length;
}
if (direction == 2) {
toX = getX - length;
toY = getY - length;
}
if (direction == 3) {
toX = getX + length;
toY = getY - length;
}
final Move move = checkThis(toX, toY, chessboard);
// Si déplacement est nul, plus possible de ce déplacer dans
// cette direction pour le fou
if (move != null) {
moves.add(move);
if (move.isAttack()) {
break;
}
} else {
break;
}
}
}
return moves;
} | 8 |
public Cons vizGetBinaryRelationsOf(LogicObject concept) {
{ VizInfo self = this;
{ MemoizationTable memoTable000 = null;
Cons memoizedEntry000 = null;
Stella_Object memoizedValue000 = null;
if (Stella.$MEMOIZATION_ENABLEDp$) {
memoTable000 = ((MemoizationTable)(OntosaurusUtil.SGT_ONTOSAURUS_M_VIZ_INFOdVIZ_GET_BINARY_RELATIONS_OF_MEMO_TABLE_000.surrogateValue));
if (memoTable000 == null) {
Surrogate.initializeMemoizationTable(OntosaurusUtil.SGT_ONTOSAURUS_M_VIZ_INFOdVIZ_GET_BINARY_RELATIONS_OF_MEMO_TABLE_000, "(:MAX-VALUES 1000 :TIMESTAMPS (:META-KB-UPDATE))");
memoTable000 = ((MemoizationTable)(OntosaurusUtil.SGT_ONTOSAURUS_M_VIZ_INFOdVIZ_GET_BINARY_RELATIONS_OF_MEMO_TABLE_000.surrogateValue));
}
memoizedEntry000 = MruMemoizationTable.lookupMruMemoizedValue(((MruMemoizationTable)(memoTable000)), concept, ((Context)(Stella.$CONTEXT$.get())), Stella.MEMOIZED_NULL_VALUE, null, -1);
memoizedValue000 = memoizedEntry000.value;
}
if (memoizedValue000 != null) {
if (memoizedValue000 == Stella.MEMOIZED_NULL_VALUE) {
memoizedValue000 = null;
}
}
else {
memoizedValue000 = Logic.applyCachedRetrieve(Cons.list$(Cons.cons(OntosaurusUtil.SYM_LOGIC_pRELATION, Cons.cons(OntosaurusUtil.SYM_ONTOSAURUS_pDOMAIN, Cons.cons(Stella.NIL, Stella.NIL)))), Cons.list$(Cons.cons(OntosaurusUtil.SYM_STELLA_AND, Cons.cons(Cons.list$(Cons.cons(OntosaurusUtil.SYM_PL_KERNEL_KB_NTH_DOMAIN, Cons.cons(OntosaurusUtil.SYM_LOGIC_pRELATION, Cons.cons(IntegerWrapper.wrapInteger(0), Cons.cons(OntosaurusUtil.SYM_ONTOSAURUS_pDOMAIN, Cons.cons(Stella.NIL, Stella.NIL)))))), Cons.cons(Cons.list$(Cons.cons(OntosaurusUtil.SYM_ONTOSAURUS_BINARY_RELATION, Cons.cons(OntosaurusUtil.SYM_LOGIC_pRELATION, Cons.cons(Stella.NIL, Stella.NIL)))), Cons.cons(Stella.NIL, Stella.NIL))))), Cons.consList(Cons.cons(null, Cons.cons(concept, Stella.NIL))), Cons.consList(Cons.cons(OntosaurusUtil.KWD_SINGLETONSp, Cons.cons(Stella.TRUE_WRAPPER, Cons.cons(OntosaurusUtil.KWD_INFERENCE_LEVEL, Cons.cons(OntosaurusUtil.KWD_SHALLOW, Stella.NIL))))), OntosaurusUtil.SYM_ONTOSAURUS_M_VIZ_INFOdVIZ_GET_BINARY_RELATIONS_OF_QUERY_001, new Object[2]);
if (Stella.$MEMOIZATION_ENABLEDp$) {
memoizedEntry000.value = ((memoizedValue000 == null) ? Stella.MEMOIZED_NULL_VALUE : memoizedValue000);
}
}
{ Cons value000 = ((Cons)(memoizedValue000));
return (value000);
}
}
}
} | 6 |
public static boolean closedTermP(Stella_Object self) {
{ MemoizationTable memoTable000 = null;
Cons memoizedEntry000 = null;
Stella_Object memoizedValue000 = null;
if (Stella.$MEMOIZATION_ENABLEDp$) {
memoTable000 = ((MemoizationTable)(Logic.SGT_LOGIC_F_CLOSED_TERMp_MEMO_TABLE_000.surrogateValue));
if (memoTable000 == null) {
Surrogate.initializeMemoizationTable(Logic.SGT_LOGIC_F_CLOSED_TERMp_MEMO_TABLE_000, "(:MAX-VALUES 500 :TIMESTAMPS (:KB-UPDATE))");
memoTable000 = ((MemoizationTable)(Logic.SGT_LOGIC_F_CLOSED_TERMp_MEMO_TABLE_000.surrogateValue));
}
memoizedEntry000 = MruMemoizationTable.lookupMruMemoizedValue(((MruMemoizationTable)(memoTable000)), self, ((Context)(Stella.$CONTEXT$.get())), Stella.MEMOIZED_NULL_VALUE, null, 2);
memoizedValue000 = memoizedEntry000.value;
}
if (memoizedValue000 != null) {
if (memoizedValue000 == Stella.MEMOIZED_NULL_VALUE) {
memoizedValue000 = null;
}
}
else {
memoizedValue000 = (Logic.helpClosedTermP(self, Stella.NIL) ? Stella.TRUE_WRAPPER : Stella.FALSE_WRAPPER);
if (Stella.$MEMOIZATION_ENABLEDp$) {
memoizedEntry000.value = ((memoizedValue000 == null) ? Stella.MEMOIZED_NULL_VALUE : memoizedValue000);
}
}
{ BooleanWrapper value000 = ((BooleanWrapper)(memoizedValue000));
return (BooleanWrapper.coerceWrappedBooleanToBoolean(value000));
}
}
} | 7 |
public int[] checkPrime3(BigInteger n) {
char[] digits = n.toString().toCharArray();
int count0 = 0, count1 = 0, count2 = 0;
int[] c0 = new int[3], c1 = new int[3], c2 = new int[3];
int[] c5 = new int[1];
for (int i = 0; i < digits.length; i++) {
char c = digits[i];
if ('0' == c) {
c0[count0] = i;
count0++;
} else if ('1' == c) {
c1[count1] = i;
count1++;
} else if ('2' == c) {
c2[count2] = i;
count2++;
}
if (count0 >= 3) {
return c0;
}
if (count1 >= 3) {
return c1;
}
if (count2 >= 3) {
return c2;
}
}
return c5;
} | 7 |
public RSInterface[] getSelectedChildren() {
RSInterface parent = getInterface();
RSInterface[] children = new RSInterface[parent.children.size()];
int count = 0;
for (int index = 0; index < children.length; index++) {
RSInterface child = RSInterface.getInterface(parent.children.get(index));
int childX = getX(parent, child);
int childY = getY(parent, child);
int childWidth = child.width;
int childHeight = child.height;
if (inArea(getSelectionArea(), new Rectangle(childX, childY, childWidth, childHeight))) {
children[count] = child;
count++;
}
}
RSInterface[] _children = new RSInterface[count];
for (int index = 0; index < count; index++) {
_children[index] = children[index];
}
return _children;
} | 3 |
public static void main(String[] args) throws Exception {
String mfa = ConfigReader.getCHSDir() + File.separator +
"BroadTrees" + File.separator + "all76.mfa";
String classify = ConfigReader.getCHSDir() + File.separator +
"rbh" + File.separator + "GenomeToClass.txt";
String output = ConfigReader.getCHSDir() + File.separator +
"BroadTrees" + File.separator + "kpneu.mfa";
//get list of CHS klebsiella pneuoniae genomes
Set<Integer> kpneu = new HashSet<Integer>();
BufferedReader br = new BufferedReader(new FileReader(new File(classify)));
String line = br.readLine();//header
for(line=br.readLine(); line!=null; line=br.readLine()) {
String genome = line.split("\t")[0];
if(genome.contains("kleb") && genome.contains("pneu") &&
genome.contains("chs")) {
String[] sp = genome.split("_");
kpneu.add(Integer.parseInt(sp[sp.length-1].replace(".0", "")));
}
}
br.close();
System.out.println("Number genomes: " + kpneu.size());
//filter mfa file
br = new BufferedReader(new FileReader(new File(mfa)));
BufferedWriter out = new BufferedWriter(new FileWriter(new File(output)));
boolean write = true;//if true, is kleb pneu, so write
int num = 0;
for(line=br.readLine(); line!=null; line=br.readLine()) {
if(line.startsWith(">")) {
int genome = Integer.parseInt(line.replace(">", "").split("_")[0]);
write = kpneu.contains(genome);
if(write) {
num++;
}
}
if(write) {
out.write(line + "\n");
}
}
br.close();
out.close();
System.out.println("Number genomes written: " + num);
} | 8 |
private static void bigClosestDepotRouteWithUniformCut(Individual individual)
{
ProblemInstance problemInstance = Individual.problemInstance;
//Assign customer to route
boolean[] clientMap = new boolean[problemInstance.customerCount];
int assigned=0;
individual.bigRoutes = new ArrayList<ArrayList<ArrayList<Integer>>>();
for(int period=0;period<problemInstance.periodCount;period++)
{
individual.bigRoutes.add(new ArrayList<ArrayList<Integer>>());
for(int depot=0;depot<problemInstance.depotCount;depot++)
{
individual.bigRoutes.get(period).add(new ArrayList<Integer>());
}
}
//create big routes
while(assigned<problemInstance.customerCount)
{
int clientNo = Utility.randomIntInclusive(problemInstance.customerCount-1);
if(clientMap[clientNo]) continue;
clientMap[clientNo]=true;
assigned++;
for(int period=0;period<problemInstance.periodCount;period++)
{
if(individual.periodAssignment[period][clientNo]==false)continue;
int depot = RouteUtilities.closestDepot(clientNo);
individual.insertIntoBigClosestDepotRoute(clientNo, depot, period);
}
}
//now cut the routes and distribute to vehicles
for(int period=0; period<problemInstance.periodCount;period++)
{
for(int depot=0; depot<problemInstance.depotCount;depot++)
{
uniformCut(individual,period, depot);
/*int vehicle = problemInstance.vehiclesUnderThisDepot.get(depot).get(0);
ArrayList<Integer >route = routes.get(period).get(vehicle);
route.clear();
route.addAll(bigRoutes.get(period).get(depot));*/
}
}
} | 8 |
@Override
public void mouseDragged(MouseEvent e)
{
if (!e.isConsumed() && start != null)
{
int dx = e.getX() - start.x;
int dy = e.getY() - start.y;
Rectangle r = graphComponent.getViewport().getViewRect();
int right = r.x + ((dx > 0) ? 0 : r.width) - dx;
int bottom = r.y + ((dy > 0) ? 0 : r.height) - dy;
graphComponent.getGraphControl().scrollRectToVisible(
new Rectangle(right, bottom, 0, 0));
e.consume();
}
} | 4 |
static String weekdag(int dag, int maand, int jaar) {
String dagVanDeWeek = "";
int getallenArray[] = {0,3,2,5,0,3,5,1,4,6,2,4};
int uitkomst;
if(maand < 3)
jaar--;
uitkomst = (jaar + jaar/4 - jaar/100 + jaar/400 +
getallenArray[maand - 1] + dag) % 7;
if(uitkomst == 0)
dagVanDeWeek = "zondag";
else if(uitkomst == 1)
dagVanDeWeek = "maandag";
else if(uitkomst == 2)
dagVanDeWeek = "dinsdag";
else if(uitkomst == 3)
dagVanDeWeek = "woensdag";
else if(uitkomst == 4)
dagVanDeWeek = "donderdag";
else if(uitkomst == 5)
dagVanDeWeek = "vrijdag";
else if(uitkomst == 6)
dagVanDeWeek = "zaterdag";
return dagVanDeWeek;
} | 8 |
public List<EmprestimoEstoque> pesquisarPorTodosOsDadosNaoNulos(EmprestimoEstoque emprestimoEstoque) {
List<EmprestimoEstoque> emprestimosEstoques = new LinkedList<>();
Connection connection = conexao.getConnection();
try {
String valorDoComandoUm = comandos.get("pesquisarPorTodosOsDadosNaoNulos" + 1);
String valorDoComandoDois = comandos.get("pesquisarPorTodosOsDadosNaoNulos" + 2);
List<String> where = new LinkedList<>();
List<SetCommand> setCommands = new LinkedList<>();
if (emprestimoEstoque.getCodigo() != null) {
where.add("emprestimo_emprestimo_estoque_codigo = ?");
setCommands.add(new SetInt(where.size(), emprestimoEstoque.getCodigo()));
}
if (emprestimoEstoque.getEstadoDevolucao() != null) {
where.add("LOWER(emprestimo_emprestimo_estoque) = ? ");
setCommands.add(new SetString(where.size(), "%" + emprestimoEstoque.getEstadoDevolucao().toLowerCase() + "%"));
}
StringBuilder query = new StringBuilder(valorDoComandoUm);
if (!where.isEmpty()) {
query.append(" WHERE ").append(where.remove(0));
while (!where.isEmpty()) {
query.append(" AND ").append(where.remove(0));
}
}
query.append(valorDoComandoDois);
PreparedStatement preparedStatement = connection.prepareStatement(query.toString());
query.delete(0, query.length());
while (!setCommands.isEmpty()) {
setCommands.remove(0).set(preparedStatement);
}
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Emprestimo emprestimo = new Emprestimo();
emprestimo.setCodigo(resultSet.getInt("emprestimo_codigo"));
emprestimoEstoque = new EmprestimoEstoque();
emprestimoEstoque.setEmprestimo(emprestimo);
emprestimoEstoque.setEstadoDevolucao(resultSet.getString("emprestimo_emprestimo_estoque_estado_devolucao"));
emprestimoEstoque.setMotivo(resultSet.getString("emprestimo_emprestimo_estoque_motivo"));
emprestimoEstoque.setCodigo(resultSet.getInt("emprestimo_emprestimo_estoque_codigo"));
emprestimoEstoque.setEstoque(new Estoque());
emprestimoEstoque.getEstoque().setMaterial(new Material());
emprestimoEstoque.getEstoque().getMaterial().setCodigo(resultSet.getInt("emprestimo_estoque_material_codigo"));
emprestimosEstoques.add(emprestimoEstoque);
}
} catch (SQLException ex) {
try {
connection.rollback();
} catch (SQLException ex1) {
}
throw new RuntimeException(ex.getMessage());
} catch (NullPointerException ex) {
throw new RuntimeException(ex.getMessage());
} finally {
conexao.fecharConnection();
}
return emprestimosEstoques;
} | 9 |
private static void loadChunkData(CompoundTag levelTag, short[][] sectionBlockIds, byte[][] sectionBlockData, boolean[] sectionsUsed, byte[] biomeIds) {
for (int i = 0; i < MAX_CHUNK_SECTIONS; i++) {
sectionsUsed[i] = false;
}
Tag biomesTag = levelTag.getValue().get("Biomes");
if (biomesTag != null) {
System.arraycopy(((ByteArrayTag) biomesTag).getValue(), 0, biomeIds, 0, 16 * 16);
} else {
for (int i = 0; i < 16 * 16; i++) {
biomeIds[i] = -1;
}
}
for (Tag t : ((ListTag) levelTag.getValue().get("Sections")).getValue()) {
CompoundTag sectionInfo = (CompoundTag) t;
int sectionIndex = ((ByteTag) sectionInfo.getValue().get("Y")).getValue().intValue();
byte[] blockIdsLow = ((ByteArrayTag) sectionInfo.getValue().get("Blocks")).getValue();
byte[] blockData = ((ByteArrayTag) sectionInfo.getValue().get("Data")).getValue();
Tag addTag = sectionInfo.getValue().get("Add");
byte[] blockAdd = null;
if (addTag != null) {
blockAdd = ((ByteArrayTag) addTag).getValue();
}
@SuppressWarnings("MismatchedReadAndWriteOfArray")
short[] destSectionBlockIds = sectionBlockIds[sectionIndex];
@SuppressWarnings("MismatchedReadAndWriteOfArray")
byte[] destSectionData = sectionBlockData[sectionIndex];
sectionsUsed[sectionIndex] = true;
for (int y = 0; y < 16; ++y) {
for (int z = 0; z < 16; ++z) {
for (int x = 0; x < 16; ++x) {
int index = y * 256 + z * 16 + x;
short blockType = (short) (blockIdsLow[index] & 0xFF);
if (blockAdd != null) {
blockType |= getBlockFromNybbleArray(blockAdd, index) << 8;
}
destSectionBlockIds[index] = blockType;
destSectionData[index] = getBlockFromNybbleArray(blockData, index);
}
}
}
}
} | 9 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final MOB target=this.getTarget(mob,commands,givenTarget);
if(target==null)
return false;
if(target==mob)
return false;
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^SYou draw out <T-NAME>s disposition.^?"),verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> draw(s) out your disposition.^?"),verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> draws out <T-NAME>s disposition.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
if(success)
mob.tell(mob,target,null,L("<T-NAME> seem(s) like <T-HE-SHE> is @x1.",CMLib.flags().getAlignmentName(target).toLowerCase()));
else
{
mob.tell(mob,target,null,L("<T-NAME> seem(s) like <T-HE-SHE> is @x1.",Faction.Align.values()[CMLib.dice().roll(1,Faction.Align.values().length-1,0)].toString().toLowerCase()));
}
}
// return whether it worked
return success;
} | 8 |
/* */ public void animate(Graphics g) {
/* 408 */ for (int i = 0; i < effects.size(); i++) {
/* 409 */ Effect e = (Effect)effects.get(i);
/* 410 */ e.update(17);
/* 411 */ if ((e.isElapsed()) || (!e.alive)) {
/* 412 */ effects.remove(i);
/* 413 */ e = null;
/* */ } else {
/* 415 */ g.drawImage(e.getImage(), e.getX() + offsetX, e.getY() +
/* 416 */ offsetY, this);
/* */ }
/* */ }
/* */ } | 3 |
@EventHandler(priority=EventPriority.HIGHEST)
public void onBlockPlace(BlockPlaceEvent event)
{
int iloscGildii = Bufor.iloscGildii;
if (iloscGildii != 0) {
for (int i = 0; i < iloscGildii;i++)
{
if (!(event.isCancelled())) {
String aktualnaGildia = Bufor.listaGildii.get(i);
String lol = Bufor.cuboidy.get(aktualnaGildia);
int x1 = 0;
int z1 = 0;
int x2 = 0;
int z2 = 0;
List<String> items = Arrays.asList(lol.split("\\s*,\\s*"));
x1 = Integer.parseInt(items.get(0));
z1 = Integer.parseInt(items.get(1));
x2 = Integer.parseInt(items.get(2));
z2 = Integer.parseInt(items.get(3));
Location loc1 = new Location(Bukkit.getWorld("world"), x1, 0, z1);
Location loc2 = new Location(Bukkit.getWorld("world"), x2, 257, z2);
Cuboid cuboid = new Cuboid(loc1, loc2);
if (cuboid.contains(event.getBlock().getLocation())) {
if (GuildUtils.czyGraczMaGildie(event.getPlayer().getName())) {
String gildiaGracza = GuildUtils.dajGildieGracza(event.getPlayer().getName());
if (!(aktualnaGildia.equals(gildiaGracza))) {
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.RED+"To teren innej gildii! Nie mozesz tutaj budowac");
}
} else {
event.setCancelled(true);
event.getPlayer().sendMessage(ChatColor.RED+"To teren innej gildii! Nie mozesz tutaj budowac");
}
}
}
}
}
} | 6 |
public static void main(String[] args) {
int solutionsCount = 0;
int maxSolutionsCount = -1;
int optimalPerimeter = -1;
for (int perimeter = 3; perimeter <= PERIMETER_MAX; ++perimeter) {
for (int i = 1; i < perimeter - 1; ++i) {
for (int j = i; j <= perimeter - i; ++j) {
for (int k = j; k <= perimeter - i - j; ++k) {
if ((i + j + k == perimeter)
&& isPythagorenTriple(i, j, k)) {
++solutionsCount;
}
}
}
}
if (maxSolutionsCount < solutionsCount) {
maxSolutionsCount = solutionsCount;
optimalPerimeter = perimeter;
}
solutionsCount = 0;
}
System.out.println("solutions count is " + maxSolutionsCount + " "
+ optimalPerimeter);
} | 7 |
public void downloadUpdate() {
button.setEnabled(false);
downloader = new Thread(new Runnable() {
@Override
public void run() {
double size = updater.getFileSize("http://nazatar.bplaced.net/Mod/Unreal.jar/Unreal.jar");
Update.label_6.setText("" + size);
int test = updater.DownloadUrlPool("Unreal.jar_Downloaded", "Unreal.jar", progressBar);
switch (test) {
case -1:
Update.label_6.setText("ERROR");
JOptionPane.showMessageDialog(null, "Error while downloading.");
break;
case 0:
Update.label_6.setText("ABORTED");
JOptionPane.showMessageDialog(null, "Download aborted");
break;
case 1:
Update.label_6.setText("Finished");
try {
Misc.copyFile(new java.io.File("Unreal.jar_DOWNLOADED"), new java.io.File("Unreal.jar"));
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
;
JOptionPane.showMessageDialog(null, "Download succesfull, please restart the Mod");
System.exit(-1);
break;
}
}
});
downloader.start();
} | 4 |
public DisplayBoard clone()
{
DisplayBoard cloned = new DisplayBoard(width, height);
for(int x = 0; x < width; x++)
{
for(int y=0; y < height; y++)
{
cloned.grid[x][y] = grid [x][y];
cloned.colorGrid[x][y] = colorGrid[x][y];
}
}
return cloned;
} | 2 |
void printHeader(String header) {
w.println("@T, \"" + header + "\"");
w.println(" " + DataIO.KEY_CREATED_AT + ", \"" + new Date() + "\"");
w.println(" " + DataIO.DATE_FORMAT + ", " + dfmt.toPattern());
String dig = System.getProperty("oms3.digest");
if (dig != null) {
w.println(" " + DataIO.KEY_DIGEST + "," + dig);
}
w.print("@H");
for (V v : vars) {
w.print(", " + v.token());
}
w.println();
w.print(" " + DataIO.KEY_TYPE);
for (V v : vars) {
w.print(", " + v.type());
}
w.println();
printHeader = false;
} | 3 |
public Connection getConnection(){
return connection;
} | 0 |
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// add elements 1, ..., N
StdOut.println(N + " random integers between 0 and 99");
DoublyLinkedList<Integer> list = new DoublyLinkedList<Integer>();
for (int i = 0; i < N; i++)
list.add((int) (100 * Math.random()));
StdOut.println(list);
StdOut.println();
ListIterator<Integer> iterator = list.iterator();
// go forwards with next() and set()
StdOut.println("add 1 to each element via next() and set()");
while (iterator.hasNext()) {
int x = iterator.next();
iterator.set(x + 1);
}
StdOut.println(list);
StdOut.println();
// go backwards with previous() and set()
StdOut.println("multiply each element by 3 via previous() and set()");
while (iterator.hasPrevious()) {
int x = iterator.previous();
iterator.set(x + x + x);
}
StdOut.println(list);
StdOut.println();
// remove all elements that are multiples of 4 via next() and remove()
StdOut.println("remove elements that are a multiple of 4 via next() and remove()");
while (iterator.hasNext()) {
int x = iterator.next();
if (x % 4 == 0) iterator.remove();
}
StdOut.println(list);
StdOut.println();
// remove all even elements via previous() and remove()
StdOut.println("remove elements that are even via previous() and remove()");
while (iterator.hasPrevious()) {
int x = iterator.previous();
if (x % 2 == 0) iterator.remove();
}
StdOut.println(list);
StdOut.println();
// add elements via next() and add()
StdOut.println("add elements via next() and add()");
while (iterator.hasNext()) {
int x = iterator.next();
iterator.add(x + 1);
}
StdOut.println(list);
StdOut.println();
// add elements via previous() and add()
StdOut.println("add elements via previous() and add()");
while (iterator.hasPrevious()) {
int x = iterator.previous();
iterator.add(x * 10);
iterator.previous();
}
StdOut.println(list);
StdOut.println();
} | 9 |
static Set<Point> rangePonints(Point from,int k,Map<String,Point> pointMap){
Set<Point> result=new HashSet<>();
for(int i=0;i<=k;++i){
collectPoint(pointMap,result,from,i,0);
collectPoint(pointMap,result,from,-i,0);
collectPoint(pointMap,result,from,0,i);
collectPoint(pointMap,result,from,0,-i);
}
return result;
} | 1 |
public String[] getEquiv(String man)
{
ArrayList<String> matches = new ArrayList<String>();
for(String aMan : manus)
{
if(man.equals(aMan))
{
int i = manus.indexOf(aMan);
matches.add(numbers.get(i));
}
}
return matches.toArray(new String[0]);
} | 2 |
public double getPriceForQuantity( int quantity ) {
double price = 0;
for( Object object : orderList.toArray() ) {
Order order = (Order)object;
if( quantity > 0 ) {
if(quantity >= order.getQuantity()) {
price += order.getPrice();
quantity -= order.getQuantity();
} else if(quantity < order.getQuantity()) {
price += quantity * (order.getPrice() / order.getQuantity());
quantity = 0;
}
}
}
return price;
} | 4 |
private static String sortCharacters(String string) {
if (string == null)
return null;
char[] array = string.toUpperCase().toCharArray();
char leftChar = 'A';
char rightChar = 'Z';
int index = 0;
int left = 0;
int right = array.length - 1;
// 13 passes at most
while (left < right) {
while (index < right) {
if (array[right] == rightChar) // special case if right is already a rightChar
right--;
else if (array[right] == leftChar) { // special case if right is a leftChar
if (index == left)
index++;
array[right] = array[left];
array[left++] = leftChar;
} else { // normal case
if (array[index] == leftChar) {
array[index] = array[left];
array[left++] = leftChar;
} else if (array[index] == rightChar) {
array[index] = array[right];
array[right--] = rightChar;
}
index++;
}
}
index = left;
leftChar++;
rightChar--;
}
return new String(array);
} | 8 |
@Override
protected void read(InputBuffer b) throws IOException, ParsingException {
VariableLengthIntegerMessage vLength = getMessageFactory().parseVariableLengthIntegerMessage(b);
b = b.getSubBuffer(vLength.length());
long length = vLength.getLong();
if (length < 0 || length > Options.getInstance().getInt("protocol.maxInvLength")) {
throw new ParsingException("Too much inventory vectors: " + length);
}
inv = new ArrayList<>((int) length);
for (int i = 0; i < length; i++) {
InventoryVectorMessage ivm = getMessageFactory().parseInventoryVectorMessage(b);
inv.add(ivm);
b = b.getSubBuffer(ivm.length());
}
} | 3 |
void parseDAS(DAS das) throws IOException {
Enumeration tableNames = das.getNames();
while (tableNames.hasMoreElements()) {
String tableName = (String) tableNames.nextElement();
AttributeTable attTable = das.getAttributeTableN(tableName);
if (tableName.equals("NC_GLOBAL") || tableName.equals("HDF_GLOBAL")) {
addAttributeTable(this, attTable, tableName, true);
} else if (tableName.equals("DODS_EXTRA") || tableName.equals("EXTRA_DIMENSION")) {
// handled seperately in DODSNetcdfFile
continue;
} else {
DodsV dodsV = findDodsV(tableName, false); // short name matches the table name
if (dodsV != null) {
addAttributeTable(dodsV, attTable, tableName, true);
} else {
dodsV = findTableDotDelimited(tableName);
if (dodsV != null) {
addAttributeTable(dodsV, attTable, tableName, true);
} else {
if (debugAttributes) System.out.println("DODSNetcdf getAttributes CANT find <" + tableName + "> add to globals");
addAttributeTable(this, attTable, tableName, false);
}
}
}
}
} | 8 |
public void body()
{
// wait for a little while for about 3 seconds.
// This to give a time for GridResource entities to register their
// services to GIS (GridInformationService) entity.
super.gridSimHold(3.0);
LinkedList resList = super.getGridResourceList();
// initialises all the containers
int totalResource = resList.size();
int resourceID[] = new int[totalResource];
String resourceName[] = new String[totalResource];
// a loop to get all the resources available
int i = 0;
for (i = 0; i < totalResource; i++)
{
// Resource list contains list of resource IDs
resourceID[i] = ( (Integer) resList.get(i) ).intValue();
// get their names as well
resourceName[i] = GridSim.getEntityName( resourceID[i] );
}
////////////////////////////////////////////////
// SUBMIT Gridlets
// determines which GridResource to send to
int index = myId_ % totalResource;
if (index >= totalResource) {
index = 0;
}
// sends all the Gridlets
Gridlet gl = null;
boolean success;
for (i = 0; i < list_.size(); i++)
{
gl = (Gridlet) list_.get(i);
write(name_ + "Sending Gridlet #" + i + " to " + resourceName[index]);
// For even number of Gridlets, send without an acknowledgement
// whether a resource has received them or not.
if (i % 2 == 0)
{
// by default - send without an ack
success = super.gridletSubmit(gl, resourceID[index]);
}
// For odd number of Gridlets, send with an acknowledgement
else
{
// this is a blocking call
success = super.gridletSubmit(gl,resourceID[index],0.0,true);
write("ack = " + success + " for Gridlet #" + i);
}
}
////////////////////////////////////////////////////////
// RECEIVES Gridlets back
// hold for few period - few seconds since the Gridlets length are
// quite huge for a small bandwidth
super.gridSimHold(5);
// receives the gridlet back
for (i = 0; i < list_.size(); i++)
{
gl = (Gridlet) super.receiveEventObject(); // gets the Gridlet
receiveList_.add(gl); // add into the received list
write(name_ + ": Receiving Gridlet #" +
gl.getGridletID() + " at time = " + GridSim.clock() );
}
////////////////////////////////////////////////////////
// ping functionality
InfoPacket pkt = null;
int size = 500;
// There are 2 ways to ping an entity:
// a. non-blocking call, i.e.
//super.ping(resourceID[index], size); // (i) ping
//super.gridSimHold(10); // (ii) do something else
//pkt = super.getPingResult(); // (iii) get the result back
// b. blocking call, i.e. ping and wait for a result
pkt = super.pingBlockingCall(resourceID[index], size);
// print the result
write("\n-------- " + name_ + " ----------------");
write(pkt.toString());
write("-------- " + name_ + " ----------------\n");
////////////////////////////////////////////////////////
// shut down I/O ports
shutdownUserEntity();
terminateIOEntities();
// don't forget to close the file
if (report_ != null) {
report_.finalWrite();
}
write(this.name_ + ": sending and receiving of Gridlets" +
" complete at " + GridSim.clock() );
} | 6 |
public String cleanText () {
// Time-saving check.
if (source.indexOf ("<lj") < 0) {
return source;
}
sourceLength = source.length ();
// Create a mirror string which is all lower case, to facilitate tag matching
lcSource = source.toLowerCase ();
destBuf = new StringBuffer (sourceLength);
sourceIndex = 0;
for (;;) {
// Copy all characters up to the next tag of interest.
int tidx = lcSource.indexOf ("<lj", sourceIndex);
int ctidx = lcSource.indexOf ("</lj", sourceIndex);
if (ctidx > 0 && (tidx < 0 || tidx > ctidx)) {
// The next event of interest is a close tag
// TODO process close tag
copyUpToIndex (ctidx);
skipLJCloseTag();
}
else if (tidx > 0) {
// The next event of interest is an open tag
copyUpToIndex (tidx);
if (sourceLength - sourceIndex >= 7 && "<lj-cut".equals(lcSource.substring (sourceIndex, sourceIndex+7))) {
processLJCutTag ();
}
else {
processLJTag ();
}
}
else {
// All done. Copy the rest and return it.
copyUpToIndex (sourceLength);
break;
}
}
return destBuf.toString ();
} | 8 |
public String searchPostDiscussion(String url){
String discussionUrl = "";
if(url.contains(PaginationParameters.getPostsUrlPattern())){
String urlWithoutPattern = url.substring(0, url.indexOf(PaginationParameters.getPostsUrlPattern()));
try {
@SuppressWarnings("resource")
final Scanner scanner = new Scanner(new File(WriteToCsvDiscussionsFile.fileName));
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if(lineFromFile.contains(urlWithoutPattern)) {
discussionUrl = lineFromFile.substring(1, (lineFromFile.indexOf(
WriteToCsvDiscussionsFile.delimiter)-1));
return discussionUrl;
}
}
} catch (IOException e) {
Logger.getLogger(OutputParams.class).debug("Execption while searching Url to Succed URLs file : "
+ e.getMessage());
}
} else {
return url;
}
return discussionUrl;
} | 4 |
@PUT
@Path("/v2.0/subnets/{subnetId}")
@Produces(MediaType.APPLICATION_JSON)
public Response updateSubnet(@PathParam("subnetId") String subnetId, final String request) throws MalformedURLException, IOException{
//Convert input object NetworkData into a String like a Json text
Object sub;
sub = JsonUtility.fromResponseStringToObject(request,Subnet.class);
String input = JsonUtility.toJsonString(sub);
//Connect to a REST service
HttpURLConnection conn=HTTPConnector.HTTPConnect(new URL(this.URLpath+"/"+subnetId), OpenstackNetProxyConstants.HTTP_METHOD_PUT, input);
//Get the response text from the REST service
String response=HTTPConnector.printStream(conn);
Subnet s=(Subnet) JsonUtility.fromResponseStringToObject(response, Subnet.class);
int responseCode=conn.getResponseCode();
HTTPConnector.HTTPDisconnect(conn);
if (responseCode==200){
// SubnetOntology.updateSubnet(s);
}
//Build the response
return Response.status(responseCode).header("Access-Control-Allow-Origin", "*").entity(s).build();
} | 1 |
public IMessage decrypter(IMessage crypte, String key) {
/*
* Cette mthode lit d'abord la cl l'aide de remplirArray, puis
* dcode les caractres un un via des appels repetes encoderChar
*/
long d=new Date().getTime();
this.remplirArray(key);
char[] c=new char[crypte.taille()];
int v=-1;
int y=-1;
int r=0;
String temp="";
for(int i=0;i<crypte.taille();i++) {
if(crypte.getChar(i)==' ') {
v=y;
y=i;
temp="";
for(int q=(v+1);q<y;q++) {
temp+=crypte.getChar(q);
}
c[r]=this.decoder(Integer.parseInt(temp));
r++;
}
}
temp="";
for(int q=(y+1);q<crypte.taille();q++) {
temp+=crypte.getChar(q);
}
c[r]=this.decoder(Integer.parseInt(temp));
char[] aRetourner=new char[r+1];
for(int i=0;i<=r;i++) {
aRetourner[i]=c[i];
}
this.time=new Date().getTime()-d;
return Fabrique.fabriquerMessage(aRetourner);
} | 5 |
public void setWindowOpaque(Window window, boolean isOpaque) {
try {
// prevent setting if not supported
if(!isTranslucencyCapable(window.getGraphicsConfiguration()) ||
!isTranslucencySupported(Translucency.PERPIXEL_TRANSLUCENT, window.getGraphicsConfiguration().getDevice())) {
return;
}
setWindowOpaque.invoke(null, window, isOpaque);
} catch(Exception e) {
e.printStackTrace();
}
} | 3 |
@Override
void removeChild(@SuppressWarnings("unused") Node child)
{
// Remove child
if(this._caso_ == child)
{
this._caso_ = null;
return;
}
if(this._valor_ == child)
{
this._valor_ = null;
return;
}
if(this._comando_.remove(child))
{
return;
}
throw new RuntimeException("Not a child.");
} | 3 |
public boolean beq(String instruction) {
String[] instArray = instruction.split(" ");
Register source1 = getRegister(1, instArray);
Register source2 = getRegister(2, instArray);
int imm = Integer.parseInt(instArray[3]);
if (source1.getValue().equals(source2.getValue())) {
int pcValue = binaryToDecimal(registerFile.PC.getValue());
int newValue = pcValue + imm;
registerFile.PC.setValue(decimalToBinary(newValue));
return true;
}
return false;
} | 1 |
public boolean WC() {
if(WCTimer <= 0) {
if(TreeHP == 0) {
AddGlobalObj(TreeX, TreeY, 1341, 0, 10);
sendMessage("This tree has run out of logs");
ResetWC();
return false;
}
else {
if(!hasAxe()) {
sendMessage("You need an axe to chop down this tree.");
ResetWC();
}
else if(hasAxe()) {
addSkillXP(WCxp, 8);
if(!addItem(logID, logAmount)) {
ResetWC();
return false;
}
else {
sendMessage("You cut and tree, and get some money!");
WCTimer = TreeTimer;
TreeHP--;
return true;
}
}
}
}
return false;
} | 5 |
public synchronized Class<?> compileSource(String name, String code) throws Exception {
Class<?> c = cache.get(name);
if (c == null) {
c = compileSource0(name, code);
cache.put(name, c);
}
return c;
} | 3 |
private boolean jj_3R_36()
{
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(21)) {
jj_scanpos = xsp;
if (jj_scan_token(22)) {
jj_scanpos = xsp;
if (jj_scan_token(23)) {
jj_scanpos = xsp;
if (jj_scan_token(24)) {
jj_scanpos = xsp;
if (jj_scan_token(38)) {
jj_scanpos = xsp;
if (jj_scan_token(39)) return true;
}
}
}
}
}
return false;
} | 6 |
public void setWeightsAsResponses(){
this.weightsEntered = false;
this.weightOption = 1;
if(this.nResponses>0){
this.weights = new double[this.nResponses];
for(int i=0; i<this.nResponses; i++){
this.weights[i] = Math.abs(this.responses[i]);
this.weightsEntered = true;
}
}
} | 2 |
private static double getSigma(int threshold, double[] probabilities) {
double w1 = 0;
double w2 = 0;
for (int i = 0; i < probabilities.length; i++) {
if (i <= threshold) {
w1 += probabilities[i];
} else {
w2 += probabilities[i];
}
}
if (w1 == 0 || w2 == 0) {
return 0;
}
double mu1 = 0;
double mu2 = 0;
for (int i = 0; i < probabilities.length; i++) {
if (i <= threshold) {
mu1 += i * probabilities[i] / w1;
} else {
mu2 += i * probabilities[i] / w2;
}
}
double mu_t = mu1 * w1 + mu2 * w2;
return w1 * Math.pow((mu1 - mu_t), 2) + w2 * Math.pow((mu2 - mu_t), 2);
} | 6 |
public boolean areWeSame(MyLogger myLogger){
boolean bothAreSame = false;
if(this == myLogger)
bothAreSame = true;
return bothAreSame;
} | 1 |
private void remCallObj(Long key) {
sync.remove(key);
} | 0 |
public boolean HasPermission(Player player, String perm) {
if (player instanceof Player) {
// Real player
if (player.hasPermission(perm)) {
return true;
}
} else {
// Console has permissions for everything
return true;
}
return false;
} | 2 |
final int[][] method1036(int i, int j) {
if (i > -94) {
anInt1812 = -1;
}
if (~anInt1808 == ~anInt1810) {
aBoolean1822 = aClass142_Sub29Array1809[j] == null;
aClass142_Sub29Array1809[j] = StrongReferenceHolder.aClass142_Sub29_5003;
return anIntArrayArrayArray1807[j];
}
if (anInt1810 != 1) {
Class142_Sub29 class142_sub29 = aClass142_Sub29Array1809[j];
if (class142_sub29 == null) {
aBoolean1822 = true;
if (~anInt1810 >= ~anInt1821) {
Class142_Sub29 class142_sub29_1 = (Class142_Sub29) aNodeList_1806.getHead();
class142_sub29 = new Class142_Sub29(j, class142_sub29_1.anInt3700);
aClass142_Sub29Array1809[class142_sub29_1.anInt3701] = null;
class142_sub29_1.unlink();
} else {
class142_sub29 = new Class142_Sub29(j, anInt1821);
anInt1821++;
}
aClass142_Sub29Array1809[j] = class142_sub29;
} else {
aBoolean1822 = false;
}
aNodeList_1806.insertTail(class142_sub29);
return anIntArrayArrayArray1807[class142_sub29.anInt3700];
} else {
aBoolean1822 = j != anInt1805;
anInt1805 = j;
return anIntArrayArrayArray1807[0];
}
} | 5 |
@SuppressWarnings("static-access")
public void scanForIPs() {
Thread t = new Thread() {
public void run() {
status.setText("Scanning network for reachable servers");
repaint();
String IPV4 = "";
try {
String currentIP = getLocalAddress().toString().replaceFirst("/", "");
String[] parts = currentIP.split("\\.");
for (int i = 0; i < parts.length; i++) {
if (i != parts.length - 1) IPV4 += parts[i] + ".";
}
} catch (SocketException e) {
System.err.println(" LOBBY] [ERROR]" + e);
}
System.out.println(" LOBBY] [SCAN] Started");
for (int i = 0; i < 256; i++) {
scanning = true;
final String tryIp = IPV4 + i;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
status2.setText(ip = tryIp);
status2.repaint();
}
});
try {
new Thread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
serverReset();
server();
try {
new Thread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (game.socketClient.isConnected()) break;
}
scanning = false;
try {
ip = getLocalAddress().toString();
} catch (SocketException e) {
System.err.println(" LOBBY] [ERROR]" + e);
}
}
};
t.start();
} | 8 |
public ByteVector putByteArray(final byte[] b, final int off, final int len) {
if (length + len > data.length) {
enlarge(len);
}
if (b != null) {
System.arraycopy(b, off, data, length, len);
}
length += len;
return this;
} | 2 |
public static final AttackInfo parseDmgM(final LittleEndianAccessor lea) {
final AttackInfo ret = new AttackInfo();
lea.skip(1);
ret.tbyte = lea.readByte();
ret.targets = (byte) ((ret.tbyte >>> 4) & 0xF);
ret.hits = (byte) (ret.tbyte & 0xF);
ret.skill = lea.readInt();
switch (ret.skill) {
case 5101004: // Corkscrew
case 15101003: // Cygnus corkscrew
case 5201002: // Gernard
case 14111006: // Poison bomb
ret.charge = lea.readInt();
break;
default:
ret.charge = 0;
break;
}
lea.skip(9); // ORDER [4] bytes on v.79, [4] bytes on v.80, [1] byte on v.82
ret.display = lea.readByte(); // Always zero?
ret.animation = lea.readByte();
lea.skip(1); // Weapon class
ret.speed = lea.readByte(); // Confirmed
ret.lastAttackTickCount = lea.readInt(); // Ticks
ret.allDamage = new ArrayList<AttackPair>();
if (ret.skill == 4211006) { // Meso Explosion
return parseMesoExplosion(lea, ret);
}
int oid, damage;
List<Integer> allDamageNumbers;
for (int i = 0; i < ret.targets; i++) {
oid = lea.readInt();
// System.out.println(tools.HexTool.toString(lea.read(14)));
lea.skip(14); // [1] Always 6?, [3] unk, [4] Pos1, [4] Pos2, [2] seems to change randomly for some attack
allDamageNumbers = new ArrayList<Integer>();
for (int j = 0; j < ret.hits; j++) {
damage = lea.readInt();
// System.out.println("Damage: " + damage);
allDamageNumbers.add(Integer.valueOf(damage));
}
lea.skip(4); // CRC of monster [Wz Editing]
ret.allDamage.add(new AttackPair(Integer.valueOf(oid), allDamageNumbers));
}
return ret;
} | 7 |
public boolean canBearOff(Color player){
int count = 0;
if (player == this.getPlayer2()){
for (int i = 1; i < 7; i++){
if (this.getPoint(i).size() > 0) {
count += (BackgammonModel.getColor(this.getPoint(i)) == player) ? this.getPoint(i).size() : 0;
}
}
count += this.getPlayer2Home().size();
} else if (player == this.getPlayer1()){
for (int i = 19; i < 25; i++){
if (this.getPoint(i).size() > 0) {
count += (BackgammonModel.getColor(this.getPoint(i)) == player) ? this.getPoint(i).size() : 0;
}
}
count += this.getPlayer1Home().size();
}
return (count == 15);
} | 8 |
private int minMove(Board prev, int depth, int alpha, int beta)
{
moves++;
if(depth >= maxDepth) return prev.getScore(); // exceeded maximum depth
int minScore = MAX_SCORE;
Board b = new Board(prev);
b.turn(); // min player's turn
for(int j = 0; j < size; j++)
{
for(int i = 0; i < size; i++)
{
if(b.move(i, j))
{
b.turn(); // max player's turn
int score = maxMove(b, depth + 1, alpha, beta);
//printMsg(false, depth, score, i, j); // fixme
if(score < minScore) minScore = score;
if(minScore <= alpha) { /*System.out.println("alpha pruned");*/ return minScore; }
if(minScore < beta) beta = minScore;
b = new Board(prev);
b.turn();
}
}
}
if(minScore == MAX_SCORE) // min player can't make a move
{
b.turn();
if(b.canMove()) return maxMove(b, depth + 1, alpha, beta); // max player can make a move
else return prev.getScore(); // max player can't make a move either - game over
}
return minScore;
} | 9 |
public int inLocalDB(String file_path) {
int index = -1;
DBLikeFileObject element = null;
Iterator<DBLikeFileObject> itr = localDB.iterator();
for (int i = 0; i < localDB.size(); i++) {
element = itr.next();
if (element.getLocalFilePath().equals(file_path)) {
index = i;
}
}
return index;
} | 2 |
private boolean processCommand(Command command)
{
boolean wantToQuit = false;
if(command.isUnknown()) {
System.out.println("I don't know what you mean...");
return false;
}
String commandWord = command.getCommandWord();
if(commandWord.equalsIgnoreCase("help")){
printHelp();
}
if(commandWord.equalsIgnoreCase("go")){
goRoom(command);
}
if(commandWord.equalsIgnoreCase("quit")){
wantToQuit = quit(command);
}
if(commandWord.equalsIgnoreCase("look")){
look();
}
if(commandWord.equalsIgnoreCase("eat")){
eat();
}
return wantToQuit;
} | 6 |
public static String escapeHtmlString(String src) {
if (src == null) {
return src;
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < src.length(); i++) {
char ch = src.charAt(i);
switch (ch) {
case '&':
if (i + 1 <= src.length() && src.charAt(i + 1) == '#') {
sb.append('&');
} else {
sb.append("&");
}
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '"':
sb.append(""");
break;
case '\'':
sb.append("'");
break;
default:
sb.append(ch);
break;
}
}
return sb.toString();
} | 9 |
public static int findNumDays(String fileName)
{
int lineNumber = 0;
String line;
try {
BufferedReader br = new BufferedReader( new FileReader(fileName));
while( (line = br.readLine()) != null)
{
lineNumber++; //counts number of entries in file
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return lineNumber;
} | 3 |
public String GetItemName(int ItemID) {
for (int i = 0; i < server.itemHandler.MaxListedItems; i++) {
if (server.itemHandler.ItemList[i] != null) {
if (server.itemHandler.ItemList[i].itemId == ItemID) {
return server.itemHandler.ItemList[i].itemName;
}
if (ItemID == -1) {
return "Unarmed";
}
}
}
return "!! NOT EXISTING ITEM !!! - ID:"+ItemID;
} | 4 |
private List<Position> getEnclosedPositions(Position from, Position to, Direction dir) {
List<Position> enclosedPositions = new ArrayList<Position>();
Position newPos = from;
while (!newPos.equals(to)) {
enclosedPositions.add(newPos);
newPos = dir.newPosition(newPos);
if (!getGrid().validPosition(newPos))
throw new IllegalArgumentException("The given direction hasn't got a valid straight from to edge");
}
enclosedPositions.add(to);
return enclosedPositions;
} | 2 |
public void removeEdges(QueryVertex v1, QueryVertex v2) {
List<QueryEdge> adj1 = this.edges.get(v1);
for(Iterator<QueryEdge> it = adj1.iterator(); it.hasNext(); ) {
QueryEdge e = it.next();
if(e.getEndPoint().equals(v2))
it.remove();
}
if(adj1.size() == 0) {
this.edges.remove(v1);
}
List<QueryEdge> adj2 = this.edges.get(v2);
for(Iterator<QueryEdge> it = adj2.iterator(); it.hasNext(); ) {
QueryEdge e = it.next();
if(e.getEndPoint().equals(v1))
it.remove();
}
if(adj2.size() == 0) {
this.edges.remove(v2);
}
} | 6 |
public ProfileEditorDialog(LaunchFrame instance, final String editingName, boolean modal) {
super(instance, modal);
setupGui();
getRootPane().setDefaultButton(update);
username.setText(UserManager.getUsername(editingName));
name.setText(editingName);
if (UserManager.getPassword(editingName).isEmpty()) {
password.setEnabled(false);
savePassword.setSelected(false);
} else {
password.setText(UserManager.getPassword(editingName));
savePassword.setSelected(true);
}
saveMojangData.setSelected(UserManager.getSaveMojangData(editingName));
username.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate (DocumentEvent arg0) {
name.setText(username.getText());
}
@Override
public void insertUpdate (DocumentEvent arg0) {
name.setText(username.getText());
}
@Override
public void changedUpdate (DocumentEvent e) {
}
});
savePassword.addActionListener(new ActionListener() {
@Override
public void actionPerformed (ActionEvent event) {
password.setEnabled(savePassword.isSelected());
}
});
update.addActionListener(new ActionListener() {
@Override
public void actionPerformed (ActionEvent arg0) {
if (editingName.equals(name.getText()) || (!UserManager.getUsernames().contains(username.getText()) && !UserManager.getNames().contains(name.getText()))) {
if (savePassword.isSelected()) {
if (password.getPassword().length > 1) {
UserManager.updateUser(editingName, username.getText(), new String(password.getPassword()), name.getText());
}
} else {
UserManager.updateUser(editingName, username.getText(), "", name.getText());
}
UserManager.setSaveMojangData(editingName, saveMojangData.isSelected());
LaunchFrame.writeUsers(name.getText());
setVisible(false);
}
}
});
remove.addActionListener(new ActionListener() {
@Override
public void actionPerformed (ActionEvent arg0) {
UserManager.removeUser(editingName);
LaunchFrame.writeUsers(null);
setVisible(false);
}
});
} | 6 |
public void deposit(BigInteger amount) throws IllegalArgumentException {
if ( (amount == null) || (amount.compareTo(BigInteger.ZERO) <= 0) )
throw new IllegalArgumentException();
setBalance(this.getBalance().add(amount));
} | 2 |
public static int CMM2(int[] dimension, int[][] array, String[][] sequence, int start, int end){
if (start >= end) return 0;
int temp;
for(int i = start; i < end; i++){
if(array[start][i] == Integer.MAX_VALUE)
array[start][i] = CMM2(dimension, array, sequence, start, i);
if(array[i+1][end] == Integer.MAX_VALUE)
array[i+1][end] = CMM2(dimension, array, sequence, i+1, end);
temp = array[start][i] + array[i+1][end] + dimension[start]*dimension[i+1]*dimension[end+1];
if (array[start][end] > temp){
array[start][end] = temp;
sequence[start][end] = "(" + sequence[start][i] + ")" + "(" + sequence[i+1][end] + ")";
}
}
return array[start][end];
} | 5 |
private static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
} | 3 |
public DashboardPanel(MainFrame owner) {
User user = Service.getCurrentUser();
this.owner = owner;
this.repainter = Updater.getInstance();// new Updater(60000);
this.repainter.registerObserver(this);
this.setLayout(new BorderLayout());
pnlDashboardCenter = new JPanel();
pnlDashboardCenter.setLayout(new GridLayout(0, 2, 5, 5));
JScrollPane scpDashboardCenter = new JScrollPane(pnlDashboardCenter);
scpDashboardCenter
.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.add(scpDashboardCenter, BorderLayout.CENTER);
fillStocks();
pnlDashboardRight = new JPanel();
this.add(pnlDashboardRight, BorderLayout.EAST);
pnlDashboardRight.setLayout(new BoxLayout(pnlDashboardRight,
BoxLayout.Y_AXIS));
pnlButtons = new JPanel();
pnlButtons.setLayout(new GridLayout(0, 1));
pnlDashboardRight.add(pnlButtons);
btnCreateStock = new JButton("Create Stock");
btnUpdateStock = new JButton("Update Stock");
btnDeleteStock = new JButton("Delete Stock");
btnOpenStock = new JButton("Open Stock");
if (user.canAccess("Create Stock")) {
btnCreateStock.addActionListener(controller);
pnlButtons.add(btnCreateStock);
}
if (user.canAccess("Update Stock")) {
btnUpdateStock.addActionListener(controller);
pnlButtons.add(btnUpdateStock);
btnUpdateStock.setEnabled(false);
}
if (user.canAccess("Delete Stock")) {
btnDeleteStock.addActionListener(controller);
pnlButtons.add(btnDeleteStock);
btnDeleteStock.setEnabled(false);
}
btnOpenStock.addActionListener(controller);
pnlButtons.add(btnOpenStock);
btnOpenStock.setEnabled(false);
txaStockInfo = new JTextArea("No Stock selected");
txaStockInfo.setEnabled(false);
txaStockInfo.setLineWrap(true);
txaStockInfo.setBackground(Color.LIGHT_GRAY);
scpStockInfo = new JScrollPane(txaStockInfo);
scpStockInfo.setPreferredSize(new Dimension(210, 300));
pnlDashboardRight.add(scpStockInfo);
} | 3 |
double evaluateInstanceLeaveOneOut(Instance instance, double [] instA)
throws Exception {
DecisionTableHashKey thekey;
double [] tempDist;
double [] normDist;
thekey = new DecisionTableHashKey(instA);
// if this one is not in the table
if ((tempDist = (double [])m_entries.get(thekey)) == null) {
throw new Error("This should never happen!");
} else {
normDist = new double [tempDist.length];
System.arraycopy(tempDist,0,normDist,0,tempDist.length);
normDist[(int)instance.classValue()] -= instance.weight();
// update the table
// first check to see if the class counts are all zero now
boolean ok = false;
for (int i=0;i<normDist.length;i++) {
if (Utils.gr(normDist[i],1.0)) {
ok = true;
break;
}
}
// downdate the class prior counts
m_classPriorCounts[(int)instance.classValue()] -=
instance.weight();
double [] classPriors = m_classPriorCounts.clone();
Utils.normalize(classPriors);
if (!ok) { // majority class
normDist = classPriors;
} else {
Utils.normalize(normDist);
}
m_classPriorCounts[(int)instance.classValue()] +=
instance.weight();
if (m_NB != null){
// downdate NaiveBayes
instance.setWeight(-instance.weight());
m_NB.updateClassifier(instance);
double [] nbDist = m_NB.distributionForInstance(instance);
instance.setWeight(-instance.weight());
m_NB.updateClassifier(instance);
for (int i = 0; i < normDist.length; i++) {
normDist[i] = (Math.log(normDist[i]) - Math.log(classPriors[i]));
normDist[i] += Math.log(nbDist[i]);
}
normDist = Utils.logs2probs(normDist);
// Utils.normalize(normDist);
}
if (m_evaluationMeasure == EVAL_AUC) {
m_evaluation.evaluateModelOnceAndRecordPrediction(normDist, instance);
} else {
m_evaluation.evaluateModelOnce(normDist, instance);
}
return Utils.maxIndex(normDist);
}
} | 7 |
public double opt(Function f, double eps)
{
eps *= Math.abs(a-b); // make accuracy relative
double x0 = Math.min(a,b);
head = new Node(null, x0, f.eval(x0));
x0 = Math.max(a,b);
Node nn = new Node(null, x0, f.eval(x0));
head.setNext(nn);
double xMax, yMax;
if ( head.getY() > nn.getY() ) nn = head;
xMax = head.getX();
yMax = head.getY();
double dxMax;
do {
dxMax = 0.0;
double optValue = Double.MAX_VALUE;
Node n0 = head, n1;
while ( (n1 = n0.getNext()) != null ) {
double dx = n1.getX() - n0.getX();
dxMax = Math.max(dxMax, dx);
double dy = 2.0*yMax - n1.getY() - n0.getY();
double value = (eps + dy)/Math.pow(dx,1.5);
if ( value < optValue ) {
optValue = value;
nn = n0;
}
n0 = n1;
}
Node n2 = nn.getNext();
double h = n2.getY() - nn.getY();
double ratio = h > 0.0 ? DIVI : h < 0.0 ? 1.0 - DIVI : 0.5;
x0 = nn.getX() + ratio*(n2.getX() - nn.getX());
double y0 = f.eval(x0);
Node n3 = new Node(n2, x0, y0);
nn.setNext(n3);
if ( y0 > yMax ) {
xMax = x0;
yMax = y0;
}
} while ( dxMax > eps );
return xMax;
} | 7 |
public static long bruteforce() throws IOException{
System.out.println("Brute Force initiated.");
DataBuff Buff = new DataBuff(Main.DataFile);
ArrayList<String> Querry = new ArrayList<String>();
String stringLine = null;
double angle = Math.PI/2;
int indextwt = 0;
int indexque = 0;
String twt = null;
String que = null;
for(int i = 0; i<Main.QuerrySize;i++){
stringLine = Buff.buffer.readLine();
Querry.add(stringLine);
}
System.out.println("Querry saved in memory. Starting to read.");
long startTime = System.currentTimeMillis();
stringLine = Buff.buffer.readLine();
for(int line = Main.QuerrySize; (line<Main.DataSetSize && stringLine!=null);line++){
String[] Lsplitted = stringLine.split("\\s+");
for(String querry : Querry){
String[] Qsplitted = querry.split("\\s+");
double aux = Tools.angle_bruteforce(Lsplitted, Qsplitted);
if(aux<angle){
angle = aux;
indextwt = Buff.buffer.getLineNumber();
indexque = Querry.indexOf(querry);
twt = stringLine;
que = querry;
}
}
if(line%500000==0) System.out.println("Current line: " + line);
stringLine = Buff.buffer.readLine();
}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("Angle: " + angle + "\n" + "Querry at line " + (indexque+1) + ": " + que + "\n" + "Tweet at line " + (indextwt+1) + ": " + twt);
System.out.println("Brute Force terminated.");
Buff.buffer.close();
return totalTime;
} | 6 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.