text stringlengths 14 410k | label int32 0 9 |
|---|---|
@Override
public double getTip() {
double tip = 0.00; // always initialize local variables
switch(serviceQuality) {
case GOOD:
tip = bill * goodRate;
break;
case FAIR:
tip = bill * fairRate;
break;
case POOR:
tip = bill * poorRate;
break;
}
return tip;
} | 3 |
public void run()
{
try
{
//do we need the local or the stream from the net?
if(stream.getStatus() && stream.connectToRelayCB) {
options.add("http://127.0.0.1:"+stream.relayServerPortTF);
} else {
options.add(stream.address);
}
//collect the options
options.add(0,mplayerPath);
options.add("-slave");
options.add("-quiet");
options.add("-cache");
options.add(String.valueOf(MPLAYER_CACHE));
//say, we are loading the stream
if (mainGui != null)
{
mainGui.showMessageInTray(trans.getString("audioplayer.loadingStream"));
}
//start the process itself
lg.log("AudioPlayer: Start music with mplayer command: "+mplayerPath+" "+options.toString());
// mplayerProcess = Runtime.getRuntime().exec(mplayerPath+" "+mplayerOptions);
//
mplayerProcess = new ProcessBuilder(options).start();
//create the streams we need to interact
inStream = new BufferedReader(new InputStreamReader(mplayerProcess.getInputStream()));
errStream = new BufferedReader(new InputStreamReader(mplayerProcess.getErrorStream()));
outStream = new BufferedWriter(new OutputStreamWriter(mplayerProcess.getOutputStream()));
String messages = "";
//get the messages from mplayer
while((messages = inStream.readLine()) != null)
{
//if we have a new interpret and title update the gui
if(messages.startsWith("ICY Info: StreamTitle="))
{
mainGui.setTitleForAudioPlayer(stream.name ,messages.substring(messages.indexOf("StreamTitle=\'")+13,messages.lastIndexOf("';")),false);
// mainGui.setTitleForAudioPlayer(stream.name ,,false);
}
}
} catch (IOException e) {
lg.logE("Error while executing mplayer: "+options.toString()+e.getMessage());
} catch (Exception e) {
lg.logE("Error while executing mplayer: "+options.toString()+e.getMessage());
}
} | 7 |
synchronized public static void addOrUpdateRequestAmount(String ip, String timestamp){
Requests req;
EntityManager manager = JPUtil.getInstance().getManager();
manager.getTransaction().begin();
try {
req = manager.createNamedQuery("Requests.findByIp", Requests.class).setParameter("ip", ip).getSingleResult();
req.setRequestCount(req.getRequestCount()+1);
req.setTimeLastRequest(timestamp);
manager.merge(req);
} catch (NoResultException ex) {
req = new Requests(ip, 1, timestamp);
manager.persist(req);
}
manager.getTransaction().commit();
} | 1 |
public void heapify(int indeksi){
int vasen = left(indeksi);
int oikea = right(indeksi);
int pienin;
if(oikea <= heapsize){
if(keko[vasen] < keko[oikea]){
pienin = vasen;
}
else{
pienin = oikea;
}
if(keko[indeksi] > keko[pienin]){
vaihdaAlkioidenPaikkaa(indeksi, pienin);
heapify(pienin);
}
else if(vasen == heapsize && keko[indeksi] > keko[vasen]){
vaihdaAlkioidenPaikkaa(indeksi, vasen);
}
}
} | 5 |
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
if (response instanceof HttpServletResponse && request instanceof HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
// skip auth for static content, middle of auth flow, notify servlet
if (httpRequest.getRequestURI().startsWith("/static") ||
httpRequest.getRequestURI().equals("/oauth2callback") ||
httpRequest.getRequestURI().equals("/notify")) {
LOG.info("Skipping auth check during auth flow");
filterChain.doFilter(request, response);
return;
}
LOG.fine("Checking to see if anyone is logged in");
if (AuthUtil.getUserId(httpRequest) == null
|| AuthUtil.getCredential(AuthUtil.getUserId(httpRequest)) == null
|| AuthUtil.getCredential(AuthUtil.getUserId(httpRequest)).getAccessToken() == null) {
// redirect to auth flow
httpResponse.sendRedirect(WebUtil.buildUrl(httpRequest, "/oauth2callback"));
return;
}
// Things checked out OK :)
filterChain.doFilter(request, response);
} else {
LOG.warning("Unexpected non HTTP servlet response. Proceeding anyway.");
filterChain.doFilter(request, response);
}
} | 8 |
public static int countOccurrencesOf(String str, String sub) {
if (str == null || sub == null || str.length() == 0 || sub.length() == 0) {
return 0;
}
int count = 0;
int pos = 0;
int idx;
while ((idx = str.indexOf(sub, pos)) != -1) {
++count;
pos = idx + sub.length();
}
return count;
} | 5 |
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
String fileName = "teaDataFile.txt";
for (FileItem fi : items) {
if (fi.getFieldName().equals("userFile")) {
System.out.println(fi.getFieldName());
InputStream is = fi.getInputStream();
byte[] barr = new byte[(int) fi.getSize()];
is.read(barr);
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(barr);
fos.close();
is.close();
}
}
tc = new TeaClassifier();
tc.generateTrainingSetFromTxt(fileName);
tree = new TeaTree(tc);
writeDataToModel(model);
} catch (Exception e) {
e.printStackTrace();
}
return "index";
} | 3 |
public void leer() throws FileNotFoundException, IOException, ClassNotFoundException{
ObjectInputStream s=null;
FileInputStream in = null;
try {
in = new FileInputStream(this.file);
s = new ObjectInputStream(in);
try{
while(true){
j = (Juego) s.readObject();
Biblio.put(j.getNombre(),j);
}
}catch (EOFException e) {
in.close();
}
}catch(FileNotFoundException ex) {
return;
}
catch (IOException ex) {
JOptionPane.showMessageDialog(null,"No Abrir/leer el archivo.Datos no cargados.");
return;
}
} | 4 |
public synchronized void release(Connection conn) throws DataException {
try {
// be sure that this connection was committed (so it is at a fresh, new transaction)
conn.commit();
// first remove the connection from the used list
usedConnections.remove(conn);
// next add it back to the free connection list
freeConnections.add(conn);
//Logger.global.info("Released a connection back to the pool. Free size is now: " + freeConnections.size() + "/" + (freeConnections.size() + usedConnections.size()));
}catch (Exception e) {
throw new DataException("An error occurred while releasing a database connection back to the pool", e);
}
}//release | 1 |
public static LinearFilter createF(int i, ColorChannel... channels) {
if (i < 1 || i > 4)
throw new IllegalArgumentException("N�o h� filtros para o valor de i=" + i);
if (i == 1)
return new LinearFilter(DoubleMatrix.createAverages(3, 3,
0, 1, 0,
1, 1, 1,
0, 1, 0), channels);
if (i == 2)
return new LinearFilter(DoubleMatrix.createAverages(3, 3,
1, 1, 1,
1, 1, 1,
1, 1, 1), channels);
if (i == 3)
return new LinearFilter(DoubleMatrix.createAverages(3, 3,
1, 1, 1,
1, 2, 1,
1, 1, 1));
return new LinearFilter(DoubleMatrix.createAverages(3, 3,
1, 2, 1,
2, 4, 2,
1, 2, 1), channels);
} | 5 |
private void isCompetitive(){
int wrongWay = 0;
for(int i=1; i<this.nAnalyteConcns; i++){
if(this.responses[i-1]<this.responses[i])wrongWay++;
if(wrongWay>=this.nAnalyteConcns/2){
if(this.responses[this.nAnalyteConcns]>=this.responses[0]){
throw new IllegalArgumentException("The data appears incompatible with a competitive assay");
}
else{
System.out.println("The data has been queried as that of a competitive assay but the fitting has not been aborted");
}
}
}
} | 4 |
public Queue<String> peonEliteXMLUnit (){
try {
path = new File(".").getCanonicalPath();
FileInputStream file =
new FileInputStream(new File(path + "/xml/papabicho.xml"));
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
System.out.println("************************************");
String expression01 = "/Units/Unit[@class='PeonElite']";
NodeList nodeList;
Node node01 = (Node) xPath.compile(expression01)
.evaluate(xmlDocument, XPathConstants.NODE);
if(null != node01) {
nodeList = node01.getChildNodes();
for (int i = 0;null!=nodeList && i < nodeList.getLength(); i++){
Node nod = nodeList.item(i);
if(nod.getNodeType() == Node.ELEMENT_NODE){
System.out.println(nodeList.item(i).getNodeName()
+ " : " + nod.getFirstChild().getNodeValue());
list.append(nod.getFirstChild().getNodeValue());
}
}
}
System.out.println("************************************");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return list;
} | 9 |
public CheckResultMessage check17(int day) {
return checkReport.check17(day);
} | 0 |
static boolean isFieldInSuper(CtClass clazz, CtClass fclass, String fname) {
if (!clazz.subclassOf(fclass))
return false;
try {
CtField f = clazz.getField(fname);
return f.getDeclaringClass() == fclass;
}
catch (NotFoundException e) {}
return false;
} | 2 |
public byte[] recieveMessage() {
byte[] responce = new byte[68];
for(int i=0;i<responce.length;i++)
responce[i] = 0;
try {
this.from_peer.readFully(responce);
} catch (IOException e) {
// http://docs.oracle.com/javase/tutorial/essential/io/datastreams.html
// We will do nothing with this! The EOF is how it knows to stop
}
return responce;
} | 2 |
@Override
public boolean tick(Tickable ticking, int tickID)
{
if((unInvoked)&&(canBeUninvoked()))
return false;
if((canBeUninvoked())
&&(tickID==Tickable.TICKID_MOB)
&&(tickDown!=Integer.MAX_VALUE))
{
if(tickDown<0)
return !unInvoked;
if((--tickDown)<=0)
{
tickDown=-1;
unInvoke();
return false;
}
}
return true;
} | 7 |
public static void setPath() {
//Get username and OS
String os=System.getProperty("os.name");
String user=System.getProperty("user.name");
//Set path depending on OS
if (os.contains("Mac")) Main.path="/Users/"+user+"/Library/Application Support/Preproste Suplence/";
else if(os.contains("Windows")) Main.path="/C:/Users/"+user+"/AppData/Roaming/Preproste Suplence/";
else if(os.contains("Linux")) Main.path="/home/"+user+"/.Preproste Suplence/";
} | 3 |
private void btnLearnCompleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLearnCompleteActionPerformed
ScienceTool.clearAll();
while (lstTypes.getSelectedIndex() < lstTypes.getModel().getSize() - 1) {
System.out.println("learning " + txtFile.getText());
File file = new File("data/" + txtFile.getText());
if (file.exists()) {
for (LinkKNN knn : knns) {
knn.learnType((String) lstTypes.getSelectedValue());
}
Datasource.getInstance().playRecording(file);
for (LinkKNN knn : knns) {
knn.stopLearning();
}
}
//Switches the Gui
if (lstTypes.getSelectedIndex() < lstTypes.getModel().getSize()) {
lstTypes.setSelectedIndex(lstTypes.getSelectedIndex() + 1);
}
}
jlDatas.updateUI();
jlDatas.setSelectionInterval(0, jlDatas.getModel().getSize());
}//GEN-LAST:event_btnLearnCompleteActionPerformed | 5 |
public void invalidateBlockReceiveRegion(int par1, int par2, int par3, int par4, int par5, int par6)
{
for (int var7 = 0; var7 < this.blocksToReceive.size(); ++var7)
{
WorldBlockPositionType var8 = (WorldBlockPositionType)this.blocksToReceive.get(var7);
if (var8.posX >= par1 && var8.posY >= par2 && var8.posZ >= par3 && var8.posX <= par4 && var8.posY <= par5 && var8.posZ <= par6)
{
this.blocksToReceive.remove(var7--);
}
}
} | 7 |
private LinkedElement<E> findElement(int index) {
if (indexOK(index)) {
LinkedElement<E> elem = first;
int counter = 0;
// Choose a way to find
boolean wayAhead = (total / 2 > index);
if (wayAhead) { // way forward
while (counter < index) {
elem = elem.getNext();
counter++;
}
} else { // way backwards
counter = total - 1;
elem = last;
while (counter > index) {
elem = elem.getPrev();
counter--;
}
}
return elem;
}
return null;
} | 4 |
private void printHelp() {
System.out.println("\nExample of using command line parameters:\n");
System.out.println(" run server instance");
System.out.println(" java -jar Test7bioz.jar -s");
System.out.println(" run client instance");
System.out.println(" java -jar Test7bioz.jar -c");
System.out.println(" run client instance, 10 calls to the server on 192.168.10.1");
System.out.println(" java -jar Test7bioz.jar -c 10 192.168.10.1");
} | 0 |
private Coordinate calculateLowestFreeCoordinateDOWN(Coordinate c, Player p) {
Coordinate result = null;
Node nodeHoveringOver = Node.getNode(Coordinate.getCoordinate(c.getX(), c.getY()));
if(nodeHoveringOver.isActive() && nodeHoveringOver.getOwner().getOwner()==p){
//return null;
}
else{
result = c;
for(int i = c.getY()+1; i<=Coordinate.maxY; i++){
Node n = Node.getNode(Coordinate.getCoordinate(c.getX(), i));
if(n.isActive() && n.getOwner().getOwner()==p){
return result;
}
else{
result = n.getCoordinate();
}
}
}
return result;
} | 5 |
public Responder getHandler(Request request) {
if (!isAURIMatch(request) && isADirectoryFileMatch(getDirectoryFileNames(), request)) return new FileResponder(directory, request.getURI());
if (isAURIMatch(request) && isAValidMethod(request)) return getRoutesMap(request).get(request.getURI()).get(request.getHTTPMethod());
if (isAURIMatch(request) && !isAValidMethod(request)) return new MethodNotAllowedResponder(Constants.SERVER_VIEWS_DIRECTORY);
return new NotFoundResponder(Constants.SERVER_VIEWS_DIRECTORY);
} | 6 |
public void setVenue(String venue) {
this.venue = venue;
} | 0 |
public void setDeleted(boolean deleted) {
this.deleted = deleted;
} | 0 |
@Override
public void actionPerformed(ActionEvent arg0) {
if(TrendFrame.gui_debug) System.out.println("Fetching data...");
// Split to a working thread, control progress bar
new Thread(){
@Override
public void run(){
JFileChooser jfc = new JFileChooser();
int selection = jfc.showOpenDialog(TrendFrame.frame);
if(selection == JFileChooser.APPROVE_OPTION){
File f = jfc.getSelectedFile();
FileReader fr;
BufferedReader reader = null;
try {
fr = new FileReader(f);
} catch (FileNotFoundException e) {
fr = null;
e.printStackTrace();
}
reader = new BufferedReader(fr);
CrimeWatch.details.clear();
String line;
try {
while ((line = reader.readLine()) != null) {
String[] lineData = line.split("#");
CrimeWatch.details.put(Long.parseLong(lineData[0] + "" + lineData[1]), line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Clear the current markers and refresh
TrendFrame.markerLayer.removeAll();
TrendFrame.markerLayer.repaint();
for(long key : CrimeWatch.details.keySet()){
// Add each of the new markers again
String[] line = CrimeWatch.details.get(key).split("#");
Marker m = new Marker(TrendFrame.frame,line[2]);
m.paint(TrendFrame.mapLabel, TrendFrame.mapImage.getImage(), Integer.parseInt(line[0]), Integer.parseInt(line[1]));
if(TrendFrame.gui_debug) System.out.println("Painting marker at (" + line[0] + "," + line[1] + ")");
TrendFrame.mapLabel.repaint();
}
JOptionPane.showMessageDialog(TrendFrame.frame,
"Markers file loaded from disk successfully.",
"Information",
JOptionPane.INFORMATION_MESSAGE);
// After everything is done, rejoin the worker thread to the main thread
try {
this.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
} | 8 |
public Object getValueAt(Object node, int column)
{
File file = getFile(node);
try
{
switch (column)
{
case 0:
return file.getName();
case 1:
return file.isFile() ? new Integer((int) file.length())
: ZERO;
case 2:
return file.isFile() ? "File" : "Directory";
case 3:
return new Date(file.lastModified());
}
}
catch (SecurityException se)
{
}
return null;
} | 7 |
private void startUp() {
long sina_e_time = 0;
long sina_s_time = System.currentTimeMillis();
// long qq_e_time = 0;
// long qq_s_time = System.currentTimeMillis();
while (true) {
if (sina_s_time>=(sina_e_time+10000)) {
if (Container.getContainer().getProperty("sina.crawl")
.equals("true")) {
if (Container.getContainer().getSinaFlog().equals("true")) {
System.out.println("start crawler sina ");
Downloader.getDownloader().submitCrawlSina();
// sina_e_time = Long.valueOf( Container.getContainer().getProperty("sinaEndTime"));
sina_e_time=System.currentTimeMillis();
}
}
}
// if (qq_s_time>=(qq_e_time+10000)) {
// if (Container.getContainer().getProperty("qq.crawl")
// .equals("true")) {
// if (Container.getContainer().getQQFlog().equals("true")) {
// System.out.println("start crawler qq ");
// Downloader.getDownloader().submitCrawlQQ();
// }
//// qq_e_time = Long.valueOf( Container.getContainer().getProperty("qqEndTime"));
// qq_e_time = System.currentTimeMillis();
// }
// }
sina_s_time = System.currentTimeMillis();
// qq_s_time = System.currentTimeMillis();
}
} | 4 |
public void testIsEqual_TOD() {
TimeOfDay test1 = new TimeOfDay(10, 20, 30, 40);
TimeOfDay test1a = new TimeOfDay(10, 20, 30, 40);
assertEquals(true, test1.isEqual(test1a));
assertEquals(true, test1a.isEqual(test1));
assertEquals(true, test1.isEqual(test1));
assertEquals(true, test1a.isEqual(test1a));
TimeOfDay test2 = new TimeOfDay(10, 20, 35, 40);
assertEquals(false, test1.isEqual(test2));
assertEquals(false, test2.isEqual(test1));
TimeOfDay test3 = new TimeOfDay(10, 20, 35, 40, GregorianChronology.getInstanceUTC());
assertEquals(false, test1.isEqual(test3));
assertEquals(false, test3.isEqual(test1));
assertEquals(true, test3.isEqual(test2));
try {
new TimeOfDay(10, 20, 35, 40).isEqual(null);
fail();
} catch (IllegalArgumentException ex) {}
} | 1 |
private void handleClassPlacement(MouseEvent arg0, UMLButton selected_button) {
last_connector_id = "";
last_clicked_class = null;
ArrayList<JComponent> associated_components = new ArrayList<JComponent>();
JLabel lab = new JLabel(selected_button.getText() + ": ");
ClassInstance c = new ClassInstance(EntityMeta.all_classes.get(selected_button.id));
try {
restrictions.checkClassAddRestrictionMeta(c, model_instance);
}
catch(RestrictionException e) {
error.setText(e.getMessage());
error.setLocation(10, 10);
error.setSize(error.getPreferredSize());
return;
}
panel.rectangles.put(c.id, arg0.getPoint());
associated_components.add(lab);
model_instance.instanced_classes.put(c.id, c);
panel.add(lab);
lab.setLocation(arg0.getPoint());
lab.setSize(lab.getPreferredSize());
JTextField instance_name = new JTextField(c.instance_name);
panel.add(instance_name);
instance_name.setLocation(new Point(arg0.getPoint().x + lab.getSize().width, arg0.getPoint().y));
instance_name.setSize(200-lab.getWidth()-5, instance_name.getPreferredSize().height);
instance_name.setBorder(null);
instance_name.addFocusListener(new JTextFieldListener(instance_name, c));
associated_components.add(instance_name);
for(int i = 0; i < c.attributes.size(); ++i) {
JLabel attr_lab = new JLabel(c.attributes.get(i).meta.name + ": ");
panel.add(attr_lab);
attr_lab.setLocation(new Point(arg0.getPoint().x, arg0.getPoint().y+35+5*i));
attr_lab.setSize(attr_lab.getPreferredSize());
attr_lab.setToolTipText(c.attributes.get(i).meta.type);
associated_components.add(attr_lab);
JTextField attr_instance_name = new JTextField(c.attributes.get(i).value);
panel.add(attr_instance_name);
associated_components.add(attr_instance_name);
attr_instance_name.setLocation(new Point(arg0.getPoint().x + attr_lab.getSize().width, arg0.getPoint().y+35+20*i));
attr_instance_name.setSize(200-attr_lab.getWidth()-5, attr_instance_name.getPreferredSize().height);
attr_instance_name.setBorder(null);
attr_instance_name.setToolTipText(c.attributes.get(i).meta.type);
attr_instance_name.addFocusListener(new JTextFieldListener(attr_instance_name, c.attributes.get(i)));
}
for(int i = 0; i < c.enums.size(); ++i) {
EnumInstance enum_i = c.enums.get(i);
JLabel enum_lab = new JLabel(enum_i.meta.name + ": ");
panel.add(enum_lab);
associated_components.add(enum_lab);
enum_lab.setLocation(new Point(arg0.getPoint().x, arg0.getPoint().y+35+(c.attributes.size()+i)*20));
enum_lab.setSize(enum_lab.getPreferredSize());
String[] values = new String[enum_i.meta.possible_values.size()];
for(int j = 0; j < values.length; ++j)
values[j] = enum_i.meta.possible_values.get(j);
JComboBox<String> enum_values = new JComboBox<String>(values);
enum_values.addActionListener(new EnumComboBoxListener(enum_i));
panel.add(enum_values);
associated_components.add(enum_values);
enum_values.setLocation(new Point(arg0.getPoint().x+enum_lab.getSize().width, enum_lab.getLocation().y));
enum_values.setSize(enum_lab.getPreferredSize());
}
class_components.put(c.id, associated_components);
panel.revalidate();
panel.repaint();
} | 4 |
public synchronized void adicionar()
{
try
{
new LocalView(this);
}
catch (Exception e)
{
}
} | 1 |
private PDFObject findInArray(PDFObject[] array, String key)
throws IOException {
int start = 0;
int end = array.length / 2;
while (end >= start && start >= 0 && end < array.length) {
// find the key at the midpoint
int pos = start + ((end - start) / 2);
String posKey = array[pos * 2].getStringValue();
// compare the key to the key we are looking for
int comp = key.compareTo(posKey);
if (comp == 0) {
// they match. Return the value
return array[(pos * 2) + 1];
} else if (comp > 0) {
// too big, search the top half of the tree
start = pos + 1;
} else if (comp < 0) {
// too small, search the bottom half of the tree
end = pos - 1;
}
}
// not found
return null;
} | 6 |
public static AbstractInanimateEntity getInEnt(int uniqueID){
if (uniqueID <= inent.size() && inent.get(uniqueID) != null){
return inent.get(uniqueID);
} else {
System.out.println("Tried to access an ID not bound to an InEnt");
System.out.println(String.valueOf(uniqueID));
return inent.get(0);
}
//return null;
} | 2 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
if(CMLib.flags().hasAControlledFollower(mob, this))
{
mob.tell(L("You can only control one elemental."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
invoker=mob;
final CMMsg msg=CMClass.getMsg(mob,null,this,verbalCastCode(mob,null,auto),auto?"":L("^S<S-NAME> chant(s) and summon(s) help from another Plain.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
final MOB target = determineMonster(mob, mob.phyStats().level()+(2*getXLEVELLevel(mob)));
beneficialAffect(mob,target,asLevel,0);
if(target.isInCombat())
target.makePeace(true);
CMLib.commands().postFollow(target,mob,true);
if(target.amFollowing()!=mob)
mob.tell(L("@x1 seems unwilling to follow you.",target.name(mob)));
}
}
else
return beneficialWordsFizzle(mob,null,L("<S-NAME> chant(s), but nothing happens."));
// return whether it worked
return success;
} | 7 |
public PlayerListener(TotalPermissions p) {
plugin = p;
} | 0 |
public boolean removeStore(Chest chest){
if(chest==null)
return false;
if(!isStore(chest))
return false;
stores.remove(chest);
saveStores();
return true;
} | 2 |
public void transferBetweenOwnAccounts(double amount, BasicAccount source, BasicAccount destination){
if(source instanceof CustomerTransferSource){
if(source.getAccountOwner() == this){
if(destination.getAccountOwner() == this){
if(!(source == destination)){
if(amount > 0){
Transaction withdraw = new Transaction(amount, source.getAccountOwner(), source.getAccountOwner(), Transaction.WITHDRAWAL);
source.appendTransaction(withdraw, this);
Transaction deposit = new Transaction(amount, source.getAccountOwner(), source.getAccountOwner(), Transaction.TRANSFER);
destination.appendTransaction(deposit, this);
}
else throw new IllegalArgumentException("Transfers must be positive!");
}
else throw new IllegalArgumentException("Source and destination accounts cannot be the same!");
}
else throw new IllegalArgumentException("You must own the account you're transferring to!");
}
else throw new IllegalArgumentException("You must own the account you're transferring from!");
}
else throw new IllegalArgumentException("You may not transfer from this account type!");
} | 5 |
@Override
public void actionPerformed(ActionEvent e) {
revertOutlinerDocument((OutlinerDocument) Outliner.documents.getMostRecentDocumentTouched());
} | 0 |
public boolean hasNext() {
// is there more data to peruse
if (currentNode == null) {
return false;
}
if (currentNode.getData() != null) {
return true;
} else {
return false;
}
} | 2 |
public int nextSymbol() throws IOException {
final BZip2BitInputStream bitInputStream = this.bitInputStream;
// Move to next group selector if required
if (((++this.groupPosition % BZip2Constants.HUFFMAN_GROUP_RUN_LENGTH) == 0)) {
this.groupIndex++;
if (this.groupIndex == this.selectors.length) {
throw new BZip2Exception ("Error decoding BZip2 block");
}
this.currentTable = this.selectors[this.groupIndex] & 0xff;
}
final int currentTable = this.currentTable;
final int[] tableLimits = this.codeLimits[currentTable];
int codeLength = this.minimumLengths[currentTable];
// Starting with the minimum bit length for the table, read additional bits one at a time
// until a complete code is recognised
int codeBits = bitInputStream.readBits (codeLength);
for (; codeLength <= BZip2Constants.HUFFMAN_DECODE_MAXIMUM_CODE_LENGTH; codeLength++) {
if (codeBits <= tableLimits[codeLength]) {
// Convert the code to a symbol index and return
return this.codeSymbols[currentTable][codeBits - this.codeBases[currentTable][codeLength]];
}
codeBits = (codeBits << 1) | bitInputStream.readBits (1);
}
// A valid code was not recognised
throw new BZip2Exception ("Error decoding BZip2 block");
} | 4 |
public void doStuff() {
try {
if (radioCreditSlip.isSelected()) {
if (radioSpecificDate.isSelected()) {
Date startDate = pickerSpecificDate.getDate();
cal.setTime(pickerSpecificDate.getDate());
cal.add(Calendar.DATE, 1);
Date endDate = cal.getTime();
System.out.println(startDate + " | " + endDate);
String title = "Credit Slip Transactions - Report of " + sdf2.format(pickerSpecificDate.getDate());
InputStream path = getClass().getResourceAsStream("/resources/jasper/FuelMartReportsSlip.jrxml");
generateReport(startDate, endDate, title, path);
} else if (radioSpecificRange.isSelected()) {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(pickerSpecificRangeStart.getDate());
cal2.setTime(pickerSpecificRangeEnd.getDate());
if (!cal1.before(cal2)) {
JOptionPane.showMessageDialog(this, "Unable to generate Report. Invalid Date Range!", "Lanka Fuel Mart Sys.", javax.swing.JOptionPane.ERROR_MESSAGE);
return;
}
Date startDate = pickerSpecificRangeStart.getDate();
Date endDate = pickerSpecificRangeEnd.getDate();
System.out.println(startDate + " | " + endDate);
String title = "Credit Slip Transactions - Report of " + sdf2.format(pickerSpecificRangeStart.getDate())
+ " to " + sdf2.format(pickerSpecificRangeEnd.getDate());
InputStream path = getClass().getResourceAsStream("/resources/jasper/FuelMartReportsSlip.jrxml");
generateReport(startDate, endDate, title, path);
}
}
if (radioCreditCard.isSelected()) {
if (radioSpecificDate.isSelected()) {
Date startDate = pickerSpecificDate.getDate();
cal.setTime(pickerSpecificDate.getDate());
cal.add(Calendar.DATE, 1);
Date endDate = cal.getTime();
System.out.println(startDate + " | " + endDate);
String title = "Credit Card Transactions - Report of " + sdf2.format(pickerSpecificDate.getDate());
InputStream path = getClass().getResourceAsStream("/resources/jasper/FuelMartReportsCard.jrxml");
generateReport(startDate, endDate, title, path);
} else if (radioSpecificRange.isSelected()) {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(pickerSpecificRangeStart.getDate());
cal2.setTime(pickerSpecificRangeEnd.getDate());
if (!cal1.before(cal2)) {
JOptionPane.showMessageDialog(this, "Unable to generate Report. Invalid Date Range!", "Lanka Fuel Mart Sys.", javax.swing.JOptionPane.ERROR_MESSAGE);
return;
}
Date startDate = pickerSpecificRangeStart.getDate();
Date endDate = pickerSpecificRangeEnd.getDate();
System.out.println(startDate + " | " + endDate);
String title = "Credit Card Transactions - Report of " + sdf2.format(pickerSpecificRangeStart.getDate())
+ " to " + sdf2.format(pickerSpecificRangeEnd.getDate());
InputStream path = getClass().getResourceAsStream("/resources/jasper/FuelMartReportsCard.jrxml");
generateReport(startDate, endDate, title, path);
}
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error occurred while Generating the Report! Error : " + ex.getMessage(), "Lanka Fuel Mart Sys.", javax.swing.JOptionPane.ERROR_MESSAGE);
Logger.getLogger(ReportsCenter.class.getName()).log(Level.SEVERE, null, ex);
}
} | 9 |
public static boolean checkDungeonBounds(RoomReference reference,
Room[][] map, Room room) {
if (reference.getX() == 0 && room.hasWestDoor())
return false;
if (reference.getX() == map.length - 1 && room.hasEastDoor())
return false;
if (reference.getY() == 0 && room.hasSouthDoor())
return false;
if (reference.getY() == map[0].length - 1 && room.hasNorthDoor())
return false;
return true;
} | 8 |
@Override
public int readSampledBytes(int nBytes, byte[] samplesBuff) {
Header header = null;
try {
header = stream.readFrame();
} catch (IOException e) {
e.printStackTrace();
}
if (header == null) {
return 0;
}
if (decoder.channels == 0) {
int channels = (header.mode() == Header.MODE_SINGLE_CHANNEL) ? 1 : 2;
float sampleRate = header.frequency();
int sampleSize = 16;
audioFormat = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED, sampleRate,
sampleSize, channels, channels * (sampleSize / 8),
sampleRate, true);
// big endian
SourceDataLine.Info info = new DataLine.Info(
SourceDataLine.class, audioFormat);
//decoder.initOutputBuffer(line, channels);
}
// while (line.available() < 100) {
// Thread.yield();
// Thread.sleep(200);
// }
try {
decoder.decodeFrame(header, stream);
samplesBuff = decoder.getBuffer();
return decoder.getBufferSize();
} catch (IOException e) {
e.printStackTrace();
}
return 0;
} | 5 |
private void readMenuFile(String encoding, final boolean reload) {
final FileConfiguration data = new YamlConfiguration();
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), Charset.forName(encoding)))) {
String line;
StringBuilder sb = new StringBuilder();
while ((line = in.readLine()) != null) {
sb.append(line);
sb.append('\n');
}
data.loadFromString(sb.toString());
new BukkitRunnable() {
@Override
public void run() {
if (reload) {
onReload(data);
} else {
onLoad(data);
}
}
}.runTask(plugin);
} catch (FileNotFoundException ex) {
plugin.getLogger().warning(file.getPath() + " no longer exists");
} catch (IOException ex) {
plugin.getLogger().log(Level.WARNING, "Error reading " + file.getPath(), ex);
} catch (InvalidConfigurationException ex) {
if (encoding.equals("UTF8")) {
plugin.getLogger().warning("Outdated menu file detected, trying to read in ANSI: " + file.getName());
new BukkitRunnable() {
@Override
public void run() {
synchronized (file) {
readMenuFile("Cp1252", reload);
}
}
}.runTaskAsynchronously(plugin);
} else {
plugin.getLogger().log(Level.WARNING, "Corrupted menu file detected: " + file.getPath(), ex);
}
}
} | 6 |
public int getColumnCount(String sheetName){
// check if sheet exists
if(!isSheetExist(sheetName))
return -1;
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);
if(row==null)
return -1;
return row.getLastCellNum();
} | 2 |
public SoundPlayer(InputStream source) {
this.source = source;
} | 0 |
@Basic
@Column(name = "PRP_USUARIO")
public String getPrpUsuario() {
return prpUsuario;
} | 0 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final BloomFilter<E> other = (BloomFilter<E>) obj;
if (this.expectedNumberOfFilterElements != other.expectedNumberOfFilterElements) {
return false;
}
if (this.k != other.k) {
return false;
}
if (this.bitSetSize != other.bitSetSize) {
return false;
}
if (this.bitset != other.bitset && (this.bitset == null || !this.bitset.equals(other.bitset))) {
return false;
}
return true;
} | 8 |
@Override
protected void createForm() {
setSelectObject();
primitives.put(namePrimitives[1], new InformGraphPrimitive(x-430, y + 70, 500, 500, 120, 60, "Looker"));
} | 0 |
public String nextToken() throws JSONException {
char c;
char q;
StringBuilder sb = new StringBuilder();
do {
c = next();
} while (Character.isWhitespace(c));
if (c == '"' || c == '\'') {
q = c;
for (;;) {
c = next();
if (c < ' ') {
throw syntaxError("Unterminated string.");
}
if (c == q) {
return sb.toString();
}
sb.append(c);
}
}
for (;;) {
if (c == 0 || Character.isWhitespace(c)) {
return sb.toString();
}
sb.append(c);
c = next();
}
} | 9 |
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Artist artist = artists.get(rowIndex);
switch(columnIndex){
case -1 : return artist.getId(); // imam id iz baze, ali ga ne prikazujem
case 0 : return artist.getFirstName();
case 1 : return artist.getLastName();
case 2 : return artist.getBody();
case 3 : return artist.getKind();
case 4 : return "izmeni";
case 5 : return "obrisi";
default : return "GRESKA!";
}
} | 7 |
public static void main(String args[])
{
BufferedReader stdin =
new BufferedReader(new InputStreamReader(System.in));
String command;
Class klasses[] = {Album.class, Artist.class,
Track.class, Composer.class};
HibernateContext.addClasses(klasses);
do {
System.out.print("\nCommand? ");
try {
command = stdin.readLine();
}
catch (java.io.IOException ex) {
command = "?";
}
String parts[] = command.split(" ");
if (command.equalsIgnoreCase("create")) {
HibernateContext.createSchema();
}
else if (command.equalsIgnoreCase("load")) {
Artist.load();
Album.load();
Composer.load();
Track.load();
}
else if (command.equalsIgnoreCase("artists")) {
Artist.list();
}
else if (command.equalsIgnoreCase("composers")) {
Composer.list();
}
else if (command.equalsIgnoreCase("albums")) {
Album.list();
}
else if (!command.equalsIgnoreCase("quit")) {
System.out.println(HELP_MESSAGE);
}
} while (!command.equalsIgnoreCase("quit"));
} | 8 |
public void mouseClicked(MouseEvent e) {
//System.out.println(ta.getText());
String[] response = Compiler.instance.compileAssembler(ta.getText());
System.out.println("---------- maschin ----------");
String code = "v2.0 raw\r\n";
int counter = 0;
for (String line : response) {
counter++;
code += line+" ";
if (counter == 8) {
counter = 0;
code += "\r\n";
}
}
PrintWriter out;
try {
out = new PrintWriter("code");
out.print(code);
out.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(code);
//System.out.println(response.toString());
System.out.println("----------- fertig ----------");
//ta.setText(response);
} | 3 |
public void accept(Visitor visitor) {
if (visitor.visit(this)) {
if (repo != null) {
repo.accept(visitor);
}
if (chan != null) {
chan.accept(visitor);
}
super.visitContainedObjects(visitor);
visitor.endVisit(this);
}
} | 3 |
public List<Cubie> getCubes(int index, Axis axis) {
if (VERBAL)
System.out.println("Retrieving cubes of axis " + axis.name() + " on face " + index);
if (index < 1 || index > getSize()) {
System.out.println("### ERROR : Cannot rotate RubiksCube face n°" + index + " on " + axis.name() + " axis => allowed indexes are in [1-" + getSize() + "] range");
return Collections.emptyList();
}
List<Cubie> cubes = new ArrayList<Cubie>();
for (Cubie cube : config) {
ThreeDimCoordinate coord = cube.getCoordinates();
int i;
switch (axis) {
case X:
i = coord.getX();
break;
case Y:
i = coord.getY();
break;
case Z:
i = coord.getZ();
break;
default:
continue;
}
if (i == index) {
cubes.add(cube);
}
}
return cubes;
} | 8 |
public ChessMove[] getMoves(int n) {
// get size of array
int size = 0;
if (n == 0 || Math.abs(n) > log.size()) {
size = log.size();
} else {
size = Math.abs(n);
}
ChessMove[] moves = new ChessMove[size];
if (n > 0 && Math.abs(n) < log.size()) {
for (int i = 0; i < n; i++) {
moves[i] = log.get(i);
}
} else if (n < 0 && Math.abs(n) < log.size()) {
for (int i = 0; i < -n; i++) {
moves[i] = log.get(log.size() + n + i);
}
} else {
log.toArray(moves);
}
return moves;
} | 8 |
public static boolean login(Usuarios usu){
String sql = " SELECT * FROM usuarios WHERE usuario = '"+usu.getUsuario()+"' AND contrasena = '"+usu.getContraseña()+"' ";
if(!BD.getInstance().sqlSelect(sql)){
return false;
}
if(!BD.getInstance().sqlFetch()){
return false;
}
return true;
} | 2 |
public String processInput(String s) {
String reply;
// Do some input transformations first.
s = EString.translate(s, "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz");
s = EString.translate(s, "@#$%^&*()_-+=~`{[}]|:;<>\\\"",
" " );
s = EString.translate(s, ",?!", "...");
// Compress out multiple speace.
s = EString.compress(s);
String lines[] = new String[2];
// Break apart sentences, and do each separately.
while (EString.match(s, "*.*", lines)) {
reply = sentence(lines[0]);
if (reply != null) return reply;
s = EString.trim(lines[1]);
}
if (s.length() != 0) {
reply = sentence(s);
if (reply != null) return reply;
}
// Nothing matched, so try memory.
String m = mem.get();
if (m != null) return m;
// No memory, reply with xnone.
Key key = keys.getKey("xnone");
if (key != null) {
Key dummy = null;
reply = decompose(key, s, dummy);
if (reply != null) return reply;
}
// No xnone, just say anything.
return "I am at a loss for words.";
} | 7 |
public static void removeProductionsForVariable(String variable,
Grammar grammar) {
GrammarChecker gc = new GrammarChecker();
Production[] productions = GrammarChecker.getProductionsWithVariable(
variable, grammar);
for (int k = 0; k < productions.length; k++) {
grammar.removeProduction(productions[k]);
}
} | 1 |
public static void getInitData()
{
//here be parser!!!
tiles = new TileType[WIDTH][HEIGHT];
for (int i = 0; i < WIDTH; i++)
for (int j = 0; j < HEIGHT; j++)
tiles[i][j] = TileType.EMPTY;
labels = new String[WIDTH][HEIGHT];
for (int i = 0; i < WIDTH; i++)
for (int j = 0; j < HEIGHT; j++)
labels[i][j] = "";
//drawLine from 2 to 62 with y=2
/*for (int i = 2; i < 60; i++)
{
tiles[i][2] = TileType.HORIZONTAL;
} */
//ArrayList<JSONElement> = Parser.getDipArray();
//Parser parser("file.json");
//int[] dipsCountArray = parser.dipsCountArray();
//int[] dipsXesArray = parser.dipsXesArray();
//for (int i = 0; i < parser.dipsCount(); i++)
//{
// dips = new Dip(parser.dipsCount[i])
//}
try
{
Object obj = parser.parse(new FileReader(".\\src\\general\\json.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray dipsArray = (JSONArray) jsonObject.get("dips");
dips = new Dip[dipsArray.size()];
Iterator<JSONObject> iterator = dipsArray.iterator();
while (iterator.hasNext())
{
JSONObject temp = iterator.next();
Long pinCount = (Long) temp.get("pinCount");
JSONObject position = (JSONObject)temp.get("position");
Long coordX = (Long) position.get("x");
Long coordY = (Long) position.get("y");
dips[dipCount] = new Dip(pinCount.intValue(),coordX.intValue(),coordY.intValue());
dips[dipCount].setName((String)temp.get("name"));
dipCount++;
}
JSONArray wiresArray = (JSONArray) jsonObject.get("wires");
wires = new Wire[wiresArray.size()];
iterator = wiresArray.iterator();
while (iterator.hasNext())
{
JSONObject temp = iterator.next();
Pin[] argPins = new Pin[2];
JSONObject pin1 = (JSONObject) temp.get("pin1");
String dipName1 = (String) pin1.get("dip");
Long pinNumber1 = (Long) pin1.get("pin");
argPins[0] = getDipByName(dipName1).getPin(pinNumber1.intValue());
JSONObject pin2 = (JSONObject) temp.get("pin2");
String dipName2 = (String) pin2.get("dip");
Long pinNumber2 = (Long) pin2.get("pin");
argPins[1] = getDipByName(dipName2).getPin(pinNumber2.intValue());
wires[wireCount] = new Wire(argPins, new PathCoordinatesTracer());
wireCount++;
}
//declare array of pins, which should be connected by wire
//wires = new Wire[2];
//Pin[] argPins = new Pin[]{ dips[0].getPin(0), dips[3].getPin(11) };
//wires[0] = new Wire(argPins, new PathCoordinatesTracer());
//labels[5][9] = "8";
//it fails to draw more that one wire
// argPins = new Pin[]{ dips[2].getPin(7), dips[3].getPin(7) };
// wires[1] = new Wire(argPins);
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
} catch (ParseException e){
e.printStackTrace();
}
} | 9 |
private void followPlayer() {
Player p = getWorld().getPlayer();
// Print.say(xtemp + " " + p.xtemp);
if (getx() < p.getx()) {
setLeft(false);
setRight(true);
} else {
setRight(false);
setLeft(true);
}
} | 1 |
public void testRandomExceptionsThreads() throws Throwable {
MockRAMDirectory dir = new MockRAMDirectory();
MockIndexWriter writer = new MockIndexWriter(dir, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
((ConcurrentMergeScheduler) writer.getMergeScheduler()).setSuppressExceptions();
//writer.setMaxBufferedDocs(10);
writer.setRAMBufferSizeMB(0.2);
if (DEBUG)
writer.setInfoStream(System.out);
final int NUM_THREADS = 4;
final IndexerThread[] threads = new IndexerThread[NUM_THREADS];
for(int i=0;i<NUM_THREADS;i++) {
threads[i] = new IndexerThread(i, writer);
threads[i].start();
}
for(int i=0;i<NUM_THREADS;i++)
threads[i].join();
for(int i=0;i<NUM_THREADS;i++)
if (threads[i].failure != null)
fail("thread " + threads[i].getName() + ": hit unexpected failure");
writer.commit();
try {
writer.close();
} catch (Throwable t) {
System.out.println("exception during close:");
t.printStackTrace(System.out);
writer.rollback();
}
// Confirm that when doc hits exception partway through tokenization, it's deleted:
IndexReader r2 = IndexReader.open(dir, true);
final int count = r2.docFreq(new Term("content4", "aaa"));
final int count2 = r2.docFreq(new Term("content4", "ddd"));
assertEquals(count, count2);
r2.close();
_TestUtil.checkIndex(dir);
} | 6 |
public int esMejorMano(Mano m) {
/*primero comparamos la jugada*/
int comparacion = this.jugada.compareTo(m.jugada);
/*si son iguales, pasamos a comprobar la carta de la jugada
Ej: en pareja de ases, el As está almacenado en cartasJugada[0]
en dobles parejas de As, Dieces el As esta en cartasJugada[0]
y el Diez en cartasJugada[1]
*/
/*Ene el caso de que sean color, pasa directamente a los kickers*/
if (comparacion == 0) {
comparacion = this.cartasJugada[0].compareTo(m.cartasJugada[0]);
if (comparacion == 0) {
/*Si es trio o poker cartasJugada[1] = null así que pasamos a los kickers*/
if (this.cartasJugada[1] == null) {
comparacion = 0;
} else {
comparacion = this.cartasJugada[1].compareTo(m.cartasJugada[1]);
}
if (comparacion == 0) {
int i = 0;
/*comprobamos los kickers de mayor a menor*/
while (i < this.kickers.size()) {
comparacion = this.kickers.get(i).compareTo(m.kickers.get(i));
/*si alguno de los kickers no son iguales, gana el mayor*/
if (comparacion != 0) {
return comparacion;
} else {
i++;
}
}
}
}
}
return comparacion;
} | 6 |
public void compute(double[] data){
assert(data.length == input_nodes);
//Set initial net values
boolean first = true;
for (Node[] layer: layers){
for (int j=0; j<layer.length; j++){
Node temp = layer[j];
//Input node
if (first && j < data.length)
temp.net = data[j];
//Bias node
else if (temp.is_bias)
temp.net = 1;
//Default node, reset net value
else temp.net = 0;
//Reset training error
temp.err = 0;
temp.out = 0;
}
first = false;
}
//Go through each layer, incrementally, and compute net values
first = true;
for (Node[] layer: layers){
//Compute net values
for (Node in: layer){
//Compute activation function (sigmoid)
in.out = first ? in.net : 1/(1+Math.exp(-in.net));
for (int i=0, l=in.links_out.size(); i<l; i++)
in.links_out.get(i).net += in.out*in.weights.get(i);
}
first = false;
}
} | 9 |
public static void main(String[] argv)
{
if(argv.length < 1)
{
System.out.println("Usage: ");
System.out.println("irssi-log-parser "
+ "<irssi log file> [<options> <output>]");
return;
}
logFile = argv[0];
Parser p = new Parser(logFile, false);
long startTime = System.currentTimeMillis();
try
{
p.parse();
}
catch(IOException e)
{
e.printStackTrace();
}
long timeTaken = System.currentTimeMillis() - startTime;
if(argv.length > 2 && argv[1].equals("--json"))
{
// Change the output type to json with the given argument
OUTPUT = Output.JSON;
outFile = argv[2];
}
switch(OUTPUT)
{
case JSON:
// JSON output
String output = "{";
output += "\"parseTime\" : " + timeTaken + ",";
output += "\"parseDate\" : " + startTime + ",";
output += "\"startDate\" : " + p.getStartDate().getMillis() + ",";
output += "\"totalLines\" : " + p.getTotalLines() + ",";
output += "\"hours\" : " + serializeArrayToJSON(p.getTotalHours()) + ",";
output += "\"dates\" : " + serializeArrayToJSON(p.getLinesByDay()) + ",";
output += "\"top\" : " + Person.serializePersonsCollectionToJson(p.getTopUsers());
output += "}";
PrintWriter writer;
try
{
writer = new PrintWriter(outFile, "UTF-8");
writer.write(output);
writer.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
System.out.println("Done in " + timeTaken + "ms.");
break;
case TEXT:
// Text Output
System.out.println("Time Taken: " + timeTaken + "ms");
break;
default:
// Default case
break;
}
} | 8 |
public int getX(){
return x;
} | 0 |
public void signalNeedToDisplayFunction() {
needToDisplayFunction = true;
} | 0 |
public static void checkArrParam(SessionRequestContent request, Criteria criteria, String reqName, String critName){
String[] arr = (String[]) request.getAllParameters(reqName);
Collection<Integer> set = new HashSet();
if (arr != null && arr.length > 0) {
for (String param : arr) {
if (param != null && !param.isEmpty()) {
Integer currParam = Integer.decode(param);
if (currParam > 0) {
set.add(currParam);
}
}
}
}
criteria.addParam(critName, set);
} | 6 |
void wrapLines(int cx) throws Exception {
int lineLen = 0;
{
int len = 0;
CharSequence sb = pageData.roLines.getInLine(cy, 0, cx);
for (int i = 0; i < sb.length(); i++) {
len += (sb.charAt(i) > 255) ? 2 : 1;
}
lineLen = Math.max(10, len);
}
ui.message("wrapLine at " + lineLen);
if (ptSelection.isSelected()) {
ptSelection.cancelSelect();
}
List<CharSequence> newtext = new ArrayList<CharSequence>();
for (int y = 0; y < pageData.lines.size(); y++) {
if (pageData.lines.get(y).length() * 2 > lineLen) {
int len = 0;
CharSequence sb = pageData.roLines.getline(y);
int start = 0;
for (int i = 0; i < sb.length(); i++) {
len += (sb.charAt(i) > 255) ? 2 : 1;
if (len >= lineLen) {
newtext.add(sb.subSequence(start, i + 1).toString());
start = i + 1;
len = 0;
}
}
if (start < sb.length()) {
newtext.add(sb.subSequence(start, sb.length()).toString());
}
} else {
newtext.add(pageData.lines.get(y).toString());
}
}
String title = "wrapped " + pageData.getTitle() + " #" + U.randomID();
PlainPage p2 = new PlainPage(uiComp, PageData.newEmpty(title));
p2.pageData.workPath = pageData.workPath;
p2.pageData.setLines(newtext);
} | 9 |
public double getTotalBalance()
{
double sum = 0;
for (double a : accounts)
sum += a;
return sum;
} | 1 |
void reHeapElement( heap q, double[] v, int length, int i )
{
int up, here;
here = i;
up = i / 2;
if ((up > 0) && (v[p[here]] < v[p[up]]))
{
/// we push the new value up the heap
while ((up > 0) && (v[p[here]] < v[p[up]]))
{
swap(q,up,here);
here = up;
up = here / 2;
}
}
else
heapify(q,v,i,length);
} | 4 |
@Override
public List<AreaConhecimento> Buscar(AreaConhecimento obj) {
String sql = "select a from AreaConhecimento a";
String filtros = "";
if(obj != null){
if(obj.getId() != null){
filtros += "a.id = " + obj.getId();
}
if(obj.getNome() != null){
if(filtros.length() > 0)
filtros += " and ";
filtros += "a.nome like '%" + obj.getNome() + "%'";
}
}
if(filtros.length() > 0){
sql += " where " + filtros;
}
Query consulta = manager.createQuery(sql);
return consulta.getResultList();
} | 5 |
private ResultMessage handleResponse() throws IOException
{
DataInputStream input;
byte[] buffer;
MsgHeaderResponse_PI responseHeaderPI;
ProtocolToken pt = null;
RError_PI errMsg = null;
ProtocolToken bodyToken = null;
input = new DataInputStream(connection.getInputStream());
//1. Read response bytes
int responseHeaderSize = RodsUtil.parseInt(RodsUtil.readBytes(4, input));
if ( debug )
{
LOG.debug("Read response header size: " + responseHeaderSize);
}
if (responseHeaderSize < 0 || responseHeaderSize > MAX_HEADER_SIZE)
{
LOG.info("Unexpected header size " + responseHeaderSize + " is this even irods?");
throw new IOException("Unexpected header size " + responseHeaderSize);
}
//2. Read response header
buffer = RodsUtil.readBytes(responseHeaderSize, input);
pt = ProtocolToken.parseToken(new String(buffer));
responseHeaderPI = new MsgHeaderResponse_PI(pt);
if ( debug )
{
LOG.debug("Read response header " + responseHeaderPI);
}
//5. parse response body
if ( responseHeaderPI.getMsgLen() > 0 )
{
buffer = RodsUtil.readBytes(responseHeaderPI.getMsgLen(), input);
// get token and verify/ set w/ command
bodyToken = ProtocolToken.parseToken(new String(buffer));
if ( debug )
{
LOG.debug("Read message token: " + bodyToken);
}
}
//6. parse error message
if ( responseHeaderPI.getErrorLen() > 0 )
{
buffer = RodsUtil.readBytes(responseHeaderPI.getErrorLen(), input);
pt = ProtocolToken.parseToken(new String(buffer));
errMsg = new RError_PI(pt);
if ( debug )
{
LOG.debug("Read error token: " + errMsg);
}
}
//7. wrap input stream
if ( responseHeaderPI.getBsLen() > 0 )
{
activeInput =
new RodsInputStream(input, responseHeaderPI.getBsLen());
}
else
{
activeInput = null;
}
return new ResultMessage(responseHeaderPI, bodyToken, errMsg,
activeInput);
} | 9 |
@Override
public String runMacro(HTTPRequest httpReq, String parm, HTTPResponse httpResp)
{
final java.util.Map<String,String> parms=parseParms(parm);
final String last=httpReq.getUrlParameter("LEVEL");
if(parms.containsKey("RESET"))
{
if(last!=null)
httpReq.removeUrlParameter("LEVEL");
return "";
}
int lastLevel=CMProps.getIntVar(CMProps.Int.LASTPLAYERLEVEL);
for(final String key : parms.keySet())
{
if(CMath.isInteger(key))
lastLevel=CMath.s_int(key);
}
if((last==null)||(last.length()>0))
{
int level=0;
if(last!=null)
level=CMath.s_int(last);
level++;
if(level<=lastLevel)
{
httpReq.addFakeUrlParameter("LEVEL",""+level);
return "";
}
}
httpReq.addFakeUrlParameter("LEVEL","");
if(parms.containsKey("EMPTYOK"))
return "<!--EMPTY-->";
return " @break@";
} | 9 |
private boolean validarDatos() {
//unicamente valido el numero de cuenta
boolean valido = false;
Validaciones val = new Validaciones();
if (jTextField1.getText().equals("") || jTextField2.getText().equals("")){
mensajeError("Ingrese un valor para Desde.. Hasta.");
}
else{
if (!val.isInt(jTextField1.getText()) || !val.isInt(jTextField2.getText())){
mensajeError("Ingrese un valor NUMERICO para Desde.. Hasta.");
}
else{
if ((Integer.parseInt(jTextField1.getText())>0) || (Integer.parseInt(jTextField1.getText())>0)){
valido = true;
mensajeError(" ");
}
else{
mensajeError("Ingrese un valor POSITIVO para Desde.. Hasta.");
}
}
}
return valido;
} | 6 |
private HTMLPanel createGuessPanel(List<String> history) {
StringBuilder htmlBuilder = new StringBuilder();
htmlBuilder.append("<div id = 'guessHistoryPanel'>"
+ "<div class='panelTitle'>"+constants.Guess()+"</div>");
for (String h : history) {
htmlBuilder.append("<div class='GuessEntry'>"+h+"</div>");
}
htmlBuilder.append("</div>");
String html = htmlBuilder.toString();
HTMLPanel panel = new HTMLPanel(html);
return panel;
} | 1 |
@Override
public void doTask()
{
if (this.control)
{
if (Keyboard.getInstance().isKeyPressed(Keys.W) && !collisions.contains(Direction.TOP))
{
y -= speed;
}
if (Keyboard.getInstance().isKeyPressed(Keys.S) && !collisions.contains(Direction.BOTTOM))
{
y += speed;
}
if (Keyboard.getInstance().isKeyPressed(Keys.A) && !collisions.contains(Direction.LEFT))
{
x -= speed;
}
if (Keyboard.getInstance().isKeyPressed(Keys.D) && !collisions.contains(Direction.RIGHT))
{
x += speed;
}
}
} | 9 |
public Model getAnimatedModel(int frame1Id, int frame2Id, boolean active) {
Model model;
if (active)
model = getModel(modelTypeActive, modelIdActive);
else
model = getModel(modelTypeDefault, modelIdDefault);
if (model == null)
return null;
if (frame2Id == -1 && frame1Id == -1 && model.triangleColours == null)
return model;
Model animatedModel = new Model(true, Animation.isNullFrame(frame2Id)
& Animation.isNullFrame(frame1Id), false, model);
if (frame2Id != -1 || frame1Id != -1)
animatedModel.createBones();
if (frame2Id != -1)
animatedModel.applyTransformation(frame2Id);
if (frame1Id != -1)
animatedModel.applyTransformation(frame1Id);
animatedModel.applyLighting(64, 768, -50, -10, -50, true);
return animatedModel;
} | 9 |
public void visitLineNumber(final int line, final Label start) {
if (lineNumber == null) {
lineNumber = new ByteVector();
}
++lineNumberCount;
lineNumber.putShort(start.position);
lineNumber.putShort(line);
} | 1 |
private void method394(int i, int j, byte abyte0[], int k, int l, int i1,
int j1)
{
int k1 = j + l * DrawingArea.width;
int l1 = DrawingArea.width - k;
int i2 = 0;
int j2 = 0;
if(l < DrawingArea.topY)
{
int k2 = DrawingArea.topY - l;
i1 -= k2;
l = DrawingArea.topY;
j2 += k2 * k;
k1 += k2 * DrawingArea.width;
}
if(l + i1 >= DrawingArea.bottomY)
i1 -= ((l + i1) - DrawingArea.bottomY) + 1;
if(j < DrawingArea.topX)
{
int l2 = DrawingArea.topX - j;
k -= l2;
j = DrawingArea.topX;
j2 += l2;
k1 += l2;
i2 += l2;
l1 += l2;
}
if(j + k >= DrawingArea.bottomX)
{
int i3 = ((j + k) - DrawingArea.bottomX) + 1;
k -= i3;
i2 += i3;
l1 += i3;
}
if(k <= 0 || i1 <= 0)
return;
method395(abyte0, i1, k1, DrawingArea.pixels, j2, k, i2, l1, j1, i);
} | 6 |
private List<EntityVote> verifyAction(HashoutUserToDelegate hashoutUserToDelegate, long time) {
Pair<EntityUser> users = EntityUser.load(new Pair<Id>(voterId, delegateId));
if (!users.getFirst().getType().equals(UserType.VOTER)) {
throw new VoteUserException("Voter type " + users.getFirst().getType() + ": " + voterId);
}
if (!users.getSecond().getType().equals(UserType.DELEGATE)) {
throw new VoteUserException("Delegate is not of type delegate: " + delegateId);
}
List<EntityUserAndVote> currentVotes = hashoutUserToDelegate.loadEntities(voterId.getKey());
List<EntityVote> activeVotes = new ArrayList<EntityVote>();
for (EntityUserAndVote userAndVote : currentVotes) {
EntityVote vote = userAndVote.getVote();
if (vote.getEndTime() > time) {
activeVotes.add(vote);
}
}
if (activeVotes.size() > 1) {
throw new VoteUserException("More then one current vote: " + voterId + " " + delegateId);
}
return activeVotes;
} | 5 |
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("AST Explorer");
shell.setLayout(new FillLayout());
ASTExplorer astExplorer = new ASTExplorer(shell,SWT.NONE);
final Point minimum = shell.computeSize(SWT.DEFAULT,SWT.DEFAULT,true);
shell.addControlListener(new ControlAdapter() {
public void controlResized(ControlEvent e) {
Shell shell = (Shell)e.widget;
Point size = shell.getSize();
boolean change = false;
if (size.x < minimum.x) {
size.x = minimum.x;
change = true;
}
if (size.y < minimum.y) {
size.y = minimum.y;
change = true;
}
if (change)
shell.setSize(size);
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
} | 5 |
public void addData(ArrayList<String> cells) {
if (cells.size() != attribute.size())
throw new IllegalArgumentException("Wrong size on row, was "
+ cells.size() + " expected " + attribute.size());
String[] row = cells.toArray(new String[0]);
HashMap<String, String> newRow = new HashMap<String, String>();
for (int i = 0; i < row.length; i++) {
newRow.put(attribute.get(i), row[i]);
}
rows.add(newRow);
String rowGoal = newRow.get(goalAttribute);
Integer i = frequenzy.get(rowGoal);
if (i == null) {
i = 0;
}
i++;
frequenzy.put(rowGoal, i);
} | 3 |
@Override
public void consume(String str)
{
/* New message received from the message board --> pass it to the client*/
System.out.println(this.getClass().getSimpleName() +" Consume");
if (!wasClosed)
{
if (output == null)
{
try
{
output = new DataOutputStream(socket.getOutputStream());
} catch (IOException e)
{
e.printStackTrace();
}
}
// if we are here the output and output streams are good
try
{
output.writeUTF(str);
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
System.out.println("Does not write to the connection, it was closed ");
}
// after we received the str from the GUI we need to sent it to the server, that he would be able to notify all
// TODO Auto-generated method stub
} | 4 |
@Override
public boolean activate() {
return (Bank.isOpen()
&& (
Constants.FALADOR_BANK_AREA.contains(Players.getLocal())
|| Constants.EDGEVILLE_BANK_AREA.contains(Players.getLocal())
|| Constants.AL_KHARID_BANK_AREA.contains(Players.getLocal())
|| Constants.NEITIZNOT_BANK_AREA.contains(Players.getLocal())
)
&& !Widgets.get(13, 0).isOnScreen()
);
} | 5 |
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(this.interval);
}
catch (InterruptedException e) {
return;
}
notifyObservers();
}
} | 2 |
public static void main(String[] args) {
// TODO code application logic here
} | 0 |
public List[] matches(List list, int centerList) {
centerList -= center;
try {
List sub = list.subList(centerList, centerList + tokens.size());
if (sub.equals(tokens))
return results;
} catch (IndexOutOfBoundsException e) {
}
return EMPTY_ARRAY;
} | 2 |
@SuppressWarnings("unchecked")
public static void main(String args[]) {
// if provided, first command line argument is class of evaluator
// default is FractalEvaluator
Repl<?, ?> repl;
if (args.length == 0) {
repl = new Repl<>(FractalEvaluator.class);
repl.loop();
} else {
try {
repl = new Repl(Class.forName(args[0]));
ArrayList<String> fileList = new ArrayList<>();
for (int i = 1; i < args.length; i++) {
fileList.add(args[i]);
}
repl.visitFiles(fileList);
repl.loop();
} catch (ClassNotFoundException cnfe) {
System.err.println(cnfe.getMessage());
System.exit(1);
}
}
} | 5 |
@Override
public ResponseInfo sendToGroup(String groupId, MessageType messageType, String message) {
//验证
if (StringUtils.isEmpty(groupId)) {
throw new IllegalArgumentException("群发消息时,没有指定组的ID!");
}
if (StringUtils.isEmpty(message)) {
throw new IllegalArgumentException("群发消息时,没有指定消息的内容!");
}
if (messageType == null) {
throw new IllegalArgumentException("群发消息时,没有指定消息类型!");
}
//组装消息
JsonObject jsonObject = new JsonObject();
jsonObject.add(GROUP, GsonHelper.addElement("group_id", "2"));
if (MessageType.NEWS.equals(messageType)) {//图文消息
jsonObject.add("mpnews", GsonHelper.addElement("media_id", message));
jsonObject.addProperty(MESSAGE_TYPE, "mpnews");
} else if (MessageType.TEXT.equals(messageType)) {//文本消息
jsonObject.add("text", GsonHelper.addElement("content", message));
jsonObject.addProperty(MESSAGE_TYPE, "text");
} else if (MessageType.VOICE.equals(messageType)) {//语音消息
jsonObject.add("voice", GsonHelper.addElement("media_id", message));
jsonObject.addProperty(MESSAGE_TYPE, "voice");
} else if (MessageType.VIDEO.equals(messageType)) {//视频消息
jsonObject.add("mpvideo", GsonHelper.addElement("media_id", message));
jsonObject.addProperty(MESSAGE_TYPE, "mpvideo");
} else if (MessageType.IMAGE.equals(messageType)) {//图片消息
jsonObject.add("image", GsonHelper.addElement("media_id", message));
jsonObject.addProperty(MESSAGE_TYPE, "image");
}
//获得要发送的数据
Gson gson = new Gson();
String json = gson.toJson(jsonObject);
String url = RequestWrapper.getUrl(WeChatUrl.SEND_TO_GROUP);
StringEntity entity = null;
try {
entity = new StringEntity(json, "application/json", "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//发送
String result = SimpleRequest.doPost(url, entity);
return RequestWrapper.getResponseInfo(result);
} | 9 |
@Test
public void testMultipleJobsWithMultipleClients() {
System.out.println("multipleJobsWithMultipleClients");
final Random rnd = new Random();
final Counter counter = new Counter();
final Set<AssignmentListener> computingClients = new HashSet<AssignmentListener>();
final AssignmentListener l = new AssignmentListener() {
@Override
public void receiveTask(Assignment task) {
try {
Object tsk = task.getTask();
if (!(tsk instanceof Integer)) {
fail("Illegal task received");
}
Integer count = (Integer) tsk;
synchronized (task) {
task.wait(count);
}
counter.add(count);
task.submitResult(GenericResponses.OK);
} catch (ConnectionException ex) {
fail("Connection to servr failed - " + ex);
} catch (InterruptedException ex) {
fail("Waiting has been interrupted - " + ex);
}
}
@Override
public void cancelTask(Assignment task) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
};
c.setAssignmentListener(new AssignmentListenerWrapper(computingClients, l));
final int clientCount = rnd.nextInt(5) + 2;
Client cl;
for (int i = 0; i < clientCount - 1; i++) {
try {
cl = ClientImpl.initNewClient();
cl.registerToServer(GlobalConstants.IP_LOOPBACK);
cl.setAssignmentListener(new AssignmentListenerWrapper(computingClients, l));
clients.add(cl);
} catch (Exception ex) {
fail("Initialization of one of the clients failed - " + ex);
}
}
int cnt = 0, val;
final int jobCount = clientCount * (rnd.nextInt(3) + 2);
Set<Job> allJobs = new HashSet<Job>(jobCount);
for (int i = 0; i < jobCount; i++) {
val = (rnd.nextInt(4) + 1) * 10;
cnt += val;
allJobs.add(s.submitJob(val));
}
s.getJobManager().waitForAllJobs();
// check all result if OK
for (Job j : allJobs) {
assertEquals(GenericResponses.OK, j.getResult(true));
}
assertEquals(cnt, counter.getCount());
assertEquals(clientCount, computingClients.size());
} | 7 |
protected int getClosestTab(int x, int y) {
int min = 0;
int tc = Math.min(rects.length, tabPane.getTabCount());
int max = tc;
int tabPlacement = tabPane.getTabPlacement();
boolean useX = (tabPlacement == TOP || tabPlacement == BOTTOM);
int want = (useX) ? x : y;
while (min != max) {
int current = (max + min) / 2;
int minLoc;
int maxLoc;
if (useX) {
minLoc = rects[current].x;
maxLoc = minLoc + rects[current].width;
} else {
minLoc = rects[current].y;
maxLoc = minLoc + rects[current].height;
}
if (want < minLoc) {
max = current;
if (min == max) {
return Math.max(0, current - 1);
}
} else if (want >= maxLoc) {
min = current;
if (max - min <= 1) {
return Math.max(current + 1, tc - 1);
}
} else {
return current;
}
}
return min;
} | 8 |
@Override
public void attributesVisibilityChanged(OutlinerDocumentEvent e) {
calculateTextState(e.getOutlinerDocument());
} | 0 |
void crawl(String[] args) throws IOException {
Validate.isTrue(args.length == 1, "usage: supply url to fetch");
String url = args[0];
print("Fetching %s...", url);
Document doc = Jsoup.connect(url).get();
// price-wrap post-right full
Elements num_oferta = doc.select("div[class=post-right full] > h3 > a");
System.out.println(num_oferta);
for (Element href : num_oferta){
String fileName = href.attr("abs:href").substring( href.attr("abs:href").lastIndexOf('/')+1, href.attr("abs:href").length() );
print("%s - %s", href.attr("abs:href"),fileName);
}
/*
Elements links = doc.select("a[href]");
Elements media = doc.select("[src]");
Elements imports = doc.select("link[href]");
print("\nMedia: (%d)", media.size());
for (Element src : media) {
if (src.tagName().equals("img"))
print(" * %s: <%s> %sx%s (%s)",
src.tagName(), src.attr("abs:src"), src.attr("width"), src.attr("height"),
trim(src.attr("alt"), 20));
else
print(" * %s: <%s>", src.tagName(), src.attr("abs:src"));
}
print("\nImports: (%d)", imports.size());
for (Element link : imports) {
print(" * %s <%s> (%s)", link.tagName(),link.attr("abs:href"), link.attr("rel"));
}
print("\nLinks: (%d)", links.size());
for (Element link : links) {
print(" * a: <%s> (%s)", link.attr("abs:href"), trim(link.text(), 35));
}
* */
} | 1 |
public Color getColor(int index) {
if (index == lastExchangeA || index == lastExchangeB) {
return Color.RED;
} else if (index == lastCompareA || index == lastCompareB) {
return Color.GREEN;
} else if (index == lastPlace) {
return Color.BLUE;
} else {
return Color.BLACK;
}
} | 5 |
public void cargarListaComprobantes(){
try{
r_con.Connection();
ResultSet rs=r_con.Consultar("select * from tipo_comprobante");
DefaultListModel modelo = new DefaultListModel();
while(rs.next()){
String cadena=rs.getString(1)+" - "+rs.getString(2);
cadena=validar.soloPrimerMayus(cadena);
modelo.addElement(cadena);
}
listaComprobantes.setModel(modelo);
// ##################### Multiple seleccion ####################
// me permite seleccionar varios elementos dentro de la lista
listaComprobantes.setSelectionModel(new DefaultListSelectionModel() {
private int i0 = -1;
private int i1 = -1;
public void setSelectionInterval(int index0, int index1) {
if(i0 == index0 && i1 == index1){
if(getValueIsAdjusting()){
setValueIsAdjusting(false);
setSelection(index0, index1);
}
}else{
i0 = index0;
i1 = index1;
setValueIsAdjusting(false);
setSelection(index0, index1);
}
}
private void setSelection(int index0, int index1){
if(super.isSelectedIndex(index0)) {
super.removeSelectionInterval(index0, index1);
}else {
super.addSelectionInterval(index0, index1);
}
}
});
// ############################################################
} catch (SQLException ex) {
Logger.getLogger(IGUI_Asignar_Pto_Venta_Comprobante.class.getName()).log(Level.SEVERE, null, ex);
} finally {
r_con.cierraConexion();
}
} | 6 |
public static void main(String[] args) {
System.out.println("begin:" + (System.currentTimeMillis() / 1000));
final SynchronousQueue<String> sq = new SynchronousQueue<String>();
final Semaphore semaphore = new Semaphore(1);
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();
String input = sq.take();
String output = TestDo.doSome(input);
System.out.println(Thread.currentThread().getName() + ":" + output);
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
for (int i = 0; i < 10; i++) {
String input = i + "";
try {
sq.put(input);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} | 4 |
public int compareTo(Object obj) {
if ((obj == null) || (!(obj instanceof UUID))) {
throw new RuntimeException("Can't compare UUIDs to non-UUIDs: " + obj);
}
UUID val = (UUID)obj;
// The ordering is intentionally set up so that the UUIDs
// can simply be numerically compared as two numbers
return (this.mostSigBits < val.mostSigBits ? -1 :
(this.mostSigBits > val.mostSigBits ? 1 :
(this.leastSigBits < val.leastSigBits ? -1 :
(this.leastSigBits > val.leastSigBits ? 1 :
0))));
} | 6 |
public void buildComponent(StructureComponent par1StructureComponent, List par2List, Random par3Random)
{
int var4 = this.getComponentType();
switch (this.corridorDirection)
{
case 0:
StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.minX + 1, this.boundingBox.minY, this.boundingBox.maxZ + 1, 0, var4);
StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.minX - 1, this.boundingBox.minY, this.boundingBox.minZ + 1, 1, var4);
StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.maxX + 1, this.boundingBox.minY, this.boundingBox.minZ + 1, 3, var4);
break;
case 1:
StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.minX + 1, this.boundingBox.minY, this.boundingBox.minZ - 1, 2, var4);
StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.minX + 1, this.boundingBox.minY, this.boundingBox.maxZ + 1, 0, var4);
StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.minX - 1, this.boundingBox.minY, this.boundingBox.minZ + 1, 1, var4);
break;
case 2:
StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.minX + 1, this.boundingBox.minY, this.boundingBox.minZ - 1, 2, var4);
StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.minX - 1, this.boundingBox.minY, this.boundingBox.minZ + 1, 1, var4);
StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.maxX + 1, this.boundingBox.minY, this.boundingBox.minZ + 1, 3, var4);
break;
case 3:
StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.minX + 1, this.boundingBox.minY, this.boundingBox.minZ - 1, 2, var4);
StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.minX + 1, this.boundingBox.minY, this.boundingBox.maxZ + 1, 0, var4);
StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.maxX + 1, this.boundingBox.minY, this.boundingBox.minZ + 1, 3, var4);
}
if (this.isMultipleFloors)
{
if (par3Random.nextBoolean())
{
StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.minX + 1, this.boundingBox.minY + 3 + 1, this.boundingBox.minZ - 1, 2, var4);
}
if (par3Random.nextBoolean())
{
StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.minX - 1, this.boundingBox.minY + 3 + 1, this.boundingBox.minZ + 1, 1, var4);
}
if (par3Random.nextBoolean())
{
StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.maxX + 1, this.boundingBox.minY + 3 + 1, this.boundingBox.minZ + 1, 3, var4);
}
if (par3Random.nextBoolean())
{
StructureMineshaftPieces.getNextComponent(par1StructureComponent, par2List, par3Random, this.boundingBox.minX + 1, this.boundingBox.minY + 3 + 1, this.boundingBox.maxZ + 1, 0, var4);
}
}
} | 9 |
public String getAffiliatId() {
return affiliateId;
} | 0 |
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.